I need to create an add method for a PositionalList... It uses an Array to store data. Here is the private members and the constructor:
private static int DEFAULT_CAPACITY = 10;
private Object[] items;
private int listSize;
private int curPos;
private int lastItemPos;
public FSAPositionalList(){
items = new Object[DEFAULT_CAPACITY];
listSize= 0;
curPos = 0;
lastItemPos = -1;
}
Psuedo-Code for the method that I made up is:
1.) Check for Array OOB.
2.) Create Temporary Array From Current Position -> End of the List
3.) Add item at Current Position
4.) Re-add items from the Temporary Array starting at curPos+1.
Here is my current code for the method:
public void add(Object obj){
// Check For Out of Bounds
if(listSize+1 > DEFAULT_CAPACITY){
throw new RuntimeException("Too many items.");
}else{
//if first time then otherwise
if(listSize == 0){
System.out.println("Permission Granted");
items[curPos] = obj;
listSize++;
return;
}
System.out.println("Access");
// Create temp array from curPos --> end
Object temp[] = new Object[listSize-curPos];
//populate temp array
int counter = 0;
for(int i = curPos; i<listSize; i++){
temp[counter] = items[i];
System.out.print("Temp - " + temp[counter]);
counter++;
}
System.out.println();
// Insert obj
items[curPos] = obj;
System.out.println(" Temp Array: ");
for(int i = 0; i < temp.length; i++){
System.out.println(temp[i]);
}
// re-add temparray after obj
int c = 0;
for(int i = curPos+1; i<listSize; i ++){
System.out.println("Replacing " + i + " " + items[i] + " with " + temp[c]);
items[i] = temp[c];
c++;
}
listSize++;
}
Using a Tester Class as follows:
FSAPositionalList list = new FSAPositionalList();
System.out.println("Adding 1");
list.add(1);
System.out.println(" List : " + list);
System.out.println("Adding 2");
list.add(2);
System.out.println(" List : " + list);
System.out.println("Adding 3");
list.add(3);
System.out.println(" List : " + list);
System.out.println("Adding 66");
list.next();
list.add(66);
System.out.println(" List : " + list);
System.out.println(list);
I have gotten this output:
Adding 1
Permission Granted
List : 1
Adding 2
Access
Temp - 1
Temp Array:
1
List : 2 null
Adding 3
Access
Temp - 2Temp - null
Temp Array:
2
null
Replacing 1 null with 2
List : 3 2 null
Adding 66
Access
Temp - 2Temp - null
Temp Array:
2
null
Replacing 2 null with 2
List : 3 66 2 null
3 66 2 null
I'm not sure why it won't re-add the Temp Array of "1" back to the List afterwords. Can anyone help?
Found a better solution if anyone is ever looking for it:
if (isFull())
throw new RuntimeException("The list is full");
for (int i = listSize - 1; i >= curPos; i--) //Open a space in
items[i + 1] = items[i]; //the array
items[curPos] = obj; //and insert obj in this space
lastItemPos = -1; //Block remove and set until after a successful
//next or previous
listSize++;
Related
I am trying to find the COUNT of repeated elements in an array list.
for example if array named "answerSheerPacketList" list contains values like {20,20,30,40,40,20,20,20},i need to show output like {20=2,30=1,40=2,20=3}.
Map<String, Integer> hm = new HashMap<String, Integer>();
for (String a : answerSheerPacketList) {
Integer j = hm.getinsAnswerSheetId(a);
hm.put(a, (j == null) ? 1 : j + 1);
}
// displaying the occurrence of elements in the arraylist
for(Map.Entry<String, Integer> val : hm.entrySet()){
System.out.println("Element " + val.getKey() + " "
"occurs" + ": " + val.getValue()+ " times");
}
when i executed above code i got output like {20=5,30=1,40=2} but i am trying to get a output like {20=2,30=1,40=2,20=3}.
A simple approach here would be to just iterate the arraylist once, and then keep tallies as we go along:
List<Integer> list = new ArrayList<>();
list.add(20);
list.add(20);
list.add(30);
list.add(40);
list.add(40);
list.add(20);
list.add(20);
list.add(20);
Integer curr = null;
int count = 0;
System.out.print("{");
for (int val : list) {
if (curr == null) {
curr = val;
count = 1;
}
else if (curr != val) {
System.out.print("(" + curr + ", " + count + ")");
curr = val;
count = 1;
}
else {
++count;
}
}
System.out.print("(" + curr + ", " + count + ")");
System.out.print("}");
{(20, 2)(30, 1)(40, 2)(20, 3)}
This is a classic problem of counting runs of consecutive elements in an array. I have renamed the array to arr in the code for brevity.
int run = 1;
for (int i = 0; i < n; ++i) { // n is the size of array
if (i + 1 < n && arr[i] == arr[i + 1]) {
run++; // increment run if consecutive elements are equal
} else {
System.out.println(arr[i] + "=" + run + ", ");
run = 1; // reset run if they are not equal
}
}
Performance-wise, this approach is aysmptotically optimal and runs in O(n), where n is the number of elements in the array.
Set<Integer> distinctSet = new HashSet<>(answerSheerPacketList);
HashSet<Integer,Integer> elementCountSet=new HashSet<>();
for (Integer element: distinctSet) {
elementCountSet.put(element,Collections.frequency(answerSheerPacketList, element));
}
What you need is basically frequency counting. The following code will do it with a single pass through your answerSheerPacketList array:
int[] answerSheerPacketList = // initialization
Map<Integer, Integer> frequencyCount = new LinkedHashMap<>();
for (int i : answerSheerPacketList) {
Integer key = Integer.valueOf(i);
if (frequencyCount.containsKey(key)) {
frequencyCount.put(key, Integer.valueOf(frequencyCount.get(key) + 1));
} else {
frequencyCount.put(key, Integer.valueOf(1));
}
}
for (Integer key : frequencyCount.keySet()) {
System.out.println("Element " + key + " occurs: " + frequencyCount.get(key)
+ " times");
}
public static void main(String[] args)
{
loadDependencies ld = new loadDependencies();
List<String> ls = ld.loadDependenciesFromPom();
getAvailableHigherVersions ah = new getAvailableHigherVersions();
List<List<String>> vl = ah.versionListOnly();
String previousVersion=null;
for ( int a=0; a<vl.size();a++) {
List<String> tmp = vl.get(a);
for(int i=0; i<ls.size();i++){
String firstE = ls.get(i);
for(int j=0;j<tmp.size();j++) {
if (i==0 && j==0){
//xu.versionUpdate(previousVersion, tmp.get(j));
//String previousVersiontt = ls.get(i);
System.out.println(firstE + "----" + tmp.get(j));
}
/*xu.versionUpdate(previousVersion, tmp.get(j));
previousVersion=tmp.get(j);*/
//System.out.println(previousVersion+"-"+tmp.get(j));
// previousVersion = tmp.get(j);
}
}
}
}
"ls" is a String list. It contains like this
[1,4,5,7]
"vl"is a List of string list. It contains like this
[[1.5,1.6,1.7],[4.1,4.2,4.3],[5.1,5.2],[7.1,7.4]]
what I need to do is first take the 1st element of ls list
1
then i need to get the first element in the vl list
[1.5,1.6,1.7]
then output should be
[1,1.5]
then the next output would be
[1.5,1.6]
likewise iterate through the array.
Then next take the 2nd element of ls
4
then it should go like 4,4.1 then 4.1,4.2 likewise until the ls is empty.
I tried above code but some times it iterate multiple times. Any hint to fix this issue?
So if I understood well, you want something like this:
for (int a = 0; a < ls.size(); a++)
{
// Get first element
String firstE = ls.get(a);
// Get corresponding vl elements
List<String> vls = vl.get(a);
// Now print the elements
// The first element of vl should be preceeded by the corresponding element in ls
// The others by the predecessor in the same array
for (int b = 0; b < vls.size(); b++)
{
System.out.print("[");
if (b == 0)
System.out.print(firstE);
else
System.out.print(vls.get(b - 1));
System.out.println(", " + vls.get(b) + "]");
}
}
for(int i=0;i<ls.size();i++){
List<String> tmp = vl.get(i);
System.out.println(ls.get(i)+" "+temp.get(0));
for(int j=1;j<tem.size()-1;j++){
System.out.println(temp.get(j)+" "+temp.get(j+1));
}
}
for ( int a=0; a<vl.size();a++) {
List<String> tmp = vl.get(a);
String firstE = ls.get(a);
for (int j = 0; j < tmp.size(); j++) {
if (j == 0) {
//xu.versionUpdate(previousVersion, tmp.get(j));
//String previousVersiontt = ls.get(i);
System.out.println(firstE + "----" + tmp.get(j));
}
/*xu.versionUpdate(previousVersion, tmp.get(j));
previousVersion=tmp.get(j);*/
//System.out.println(previousVersion+"-"+tmp.get(j));
// previousVersion = tmp.get(j);
}
}
}
Example of list:
List1 =[[1,2,3],[4,5],[6,7],[8,9,10]]
List2 =[[11,12],[13,14,15,16],[17,18,19],[20]]
I have two lists of list and want to compare list element in below fashion
1=>11, 2=>12,3=>No element present in List2
4=>13, 5->14,15->No element present in List1,16->No element present in List1
but the condition is List 2 can contain more element than list1. How i can compare two lists with each other?
I have checked online solutions and tried to iterate through for loop as well but none of them are fulfilled my requirement.
Size of list1 and list2 are equal and I have already added a check to start comparison only if size is equal.
I can iterate through both the lists with the help of for loop but struggling with the comparison.
for (int m = 0; m < List1 .size(); m++) {
for (int n = 0; n < List1 .get(m).size(); n++) {
System.out.println("List1" + m + "==>" + List1 .get(m).get(n));
}
System.out.println("========================================================");
}
for (int i = 0; i < List2.size(); i++) {
for (int k = 0; k < List2.get(i).size(); k++) {
System.out.println("========================================================");
System.out.println("List2" + i + "==>" + List2.get(i).get(k));
}
}
public static boolean isEqualsDeeply(List<List<Integer>> one, List<List<Integer>> two) {
one = one != null ? one : Collections.emptyList();
two = two != null ? two : Collections.emptyList();
if (one.size() != two.size())
return false;
Iterator<List<Integer>> it1 = one.iterator();
Iterator<List<Integer>> it2 = two.iterator();
while (it1.hasNext() && it2.hasNext()) {
List<Integer> subOne = it1.next();
List<Integer> subTwo = it2.next();
subOne = subOne != null ? subOne : Collections.emptyList();
subTwo = subTwo != null ? subTwo : Collections.emptyList();
if (subOne.size() != subTwo.size() || !subOne.equals(subTwo))
return false;
}
return true;
}
P.S.
It seems that for Integer standard equals works fine as well:
public static boolean isEqualsDeeply(List<List<Integer>> one, List<List<Integer>> two) {
one = one != null ? one : Collections.emptyList();
two = two != null ? two : Collections.emptyList();
return one.equals(two);
}
You can use Math.max(int n, int m) to compare the list sizes and get the longest one for your nested for loop. Example:
public static void main(String[] args) {
List<List<Integer>> list1 = Arrays.asList(
Arrays.asList(1,2,3),
Arrays.asList(4,5),
Arrays.asList(6,7),
Arrays.asList(8,9,10));
List<List<Integer>> list2 = Arrays.asList(
Arrays.asList(11,12),
Arrays.asList(13,14,15,16),
Arrays.asList(17,18,19),
Arrays.asList(20));
for(int i = 0; i <list2.size();i++){
int j = Math.max(list1.get(i).size(),list2.get(i).size());
for(int k = 0; k<j; k++){
System.out.print(k<list1.get(i).size()?list1.get(i).get(k) +" => ":"No element present in List1 => ");
System.out.print(k<list2.get(i).size()?list2.get(i).get(k) :"No element present in List2");
System.out.println("");
}
System.out.println("===============================");
}
}
Not sure if you're stuck on the java aspect of checking whether a list has another element remaining, of if you're stuck on the logic. If its the logic, here's some javascript code that gets the job done :
var list1 = [[1,2,3],[4,5],[6,7],[8,9,10]];
var list2 = [[11,12],[13,14,15,16],[17,18,19],[20],[21]];
function compareLists(l1,l2){
var i = 0;
var maxLength = Math.max(list1.length,list2.length);
for(i = 0; i< maxLength; i++){
var sl1 = list1[i], sl2 = list2[i];
compareSublists(sl1,sl2);
}
}
function compareSublists(sl1,sl2){
if(sl1 === undefined){
console.log(sl2 + " has no corresponding sublist in list 1");
}else if(sl2 === undefined){
console.log(sl1 + " has no corresponding sublist in lis 2");
}else{
var i = 0;
var maxLength = Math.max(sl1.length,sl2.length);
for(i=0; i<maxLength;i++){
var sl1e = sl1[i], sl2e = sl2[i];
if(sl1e === undefined){
console.log(sl2e+" has no element in list 1");
}else if(sl2e === undefined){
console.log(sl1e+" has no element in list 2");
}else{
console.log(sl1e + " => " + sl2e);
}
}
}
}
compareLists(list1,list2);
Converting to java should not be too much of an issue; however I haven't touched java in years, so I can't help you out there, apologies.
I need to do a method to check two string for example bod and bot or crab and rab. The method needs to print out what the user must do in order to make them equal. For example in bod and bot it will print "replace,2,d in the string". I used this code which seems to work.
if(a.length()==b.length()){
int i;
for(i=0; i<=a.length(); i++){
if(a.charAt(i)!=b.charAt(i)){
return "replace,"+ i + "," + b.charAt(i);
}
}
}
But I am having troubles if the two string are not equal in size. I use this but it doesn't work because one of the strings is bigger.
int aS = a.length();
int bS = b.length();
if(bS - aS == 1){
int i;
for(i=0; i<=b.length(); i++){
if(b.charAt(i)!=a.charAt(i)){
return "remove," + i;
}
}
}
Can you guys give me a suggestion what method I can use to check which is the extra letter or vice versa a letter I can add and then return a string saying either to remove a character or add an extra one. Thank you
Maybe something like this?
public ArrayList<String> createConversionList(String primary, String secondary){
//Determine which string is shorter.
String shorter;
String longer;
boolean primaryIsShorter = false;
if (primary.length() >= secondary.length()){
longer = primary;
shorter = secondary;
} else{
longer = secondary;
shorter = primary;
primaryIsShorter = true;
}
//Fills an array with all the character positions that differ between the
//two strings, using the shorter string as the base.
int[] posOfCharsToChange = new int[shorter.length()];
for(int i = 0; i < shorter.length(); i++){
if(shorter.charAt(i) != longer.charAt(i)){
posOfCharsToChange[i] = i;
} else{
posOfCharsToChange[i] = -1;
}
}
//Adds to an ArrayList all of the "Replace" strings.
ArrayList<String> conversionList = new ArrayList();
for(int pos: posOfCharsToChange){
if(pos != -1){
String s = "Replace " + secondary.charAt(pos) + " with " + primary.charAt(pos) + ". \n";
conversionList.add(s);
}
}
//Depending on which string was bigger, either adds "Add" or "Remove"
//strings to the ArrayList. If the strings were the same size, does
//nothing.
if(primary.length() != secondary.length()){
if(primaryIsShorter){
for(int i = primary.length(); i < secondary.length(); i++){
String s = "Remove " + secondary.charAt(i) + ". \n";
conversionList.add(s);
}
}
else{
for(int i = secondary.length(); i < primary.length(); i++){
String s = "Add " + primary.charAt(i) + ". \n";
conversionList.add(s);
}
}
}
return conversionList;
}
My Approach works as follows
1) We take the smaller string and put all its contents in an arraylist
2) We take the bigger string and put its contents in the arraylist only if its not present in the arraylist
3) The last character in the arraylist must be removed from the bigger string to make them equal
Ex 1:
a = rab
b = crab
1) arraylist = rab -> contents of a added
2) arraylist = rabc -> only unique content of b is added
Ex 2:
a = crab
b = rab
1) arraylist = rab
2) arraylist = rabc
similarly if the positions are in the middle or not at start ,
ex : a = racb
b = rab
1) arraylist = rab
2) arraylist = rabc
public class Replace {
public static void main(String args[]) {
int p = 0, j = 0;
String a = "rab";
String b = "crab";
if (b.length() < a.length()) {
ArrayList al = new ArrayList();
for (j = 0; j < b.length(); j++) {
if (!al.contains(b.charAt(j))) {
al.add(b.charAt(j));
}
}
for (j = 0; j < a.length(); j++) {
if (!al.contains(a.charAt(j))) {
al.add(a.charAt(j));
}
}
System.out.println("Remove " + al.get(al.size() - 1)
+ " from String a");
} else {
ArrayList al = new ArrayList();
for (j = 0; j < a.length(); j++) {
if (!al.contains(a.charAt(j))) {
al.add(a.charAt(j));
}
}
for (j = 0; j < b.length(); j++) {
if (!al.contains(b.charAt(j))) {
al.add(b.charAt(j));
}
}
System.out.println("Remove " + al.get(al.size() - 1)
+ " from String b");
}
}
}
Note - The program only works under your given contraints that strings only differ in one character and the ordering of both the strings is not different if we remove or add that charcter.
I would like to create a code that will help me copy elements from the 'allWords' ArrayList to the 'distinctWords'. but his time in the distinct words ArrayList I want a word to appear just one, eliminating redundancy in the "distinctWords' ArrayList.
this is the code that I have come up with and I am getting no output.
import java.util.ArrayList;
public class copyElements {
static ArrayList<String> distinctWords = new ArrayList<String> ();
static ArrayList<String> allWords = new ArrayList<String> ();
static int allWordsCount = 0;
static int distinctWordsCount;
static int tracker;
public static void main(String[] args) {
allWords.add("you");
allWords.add("want");
allWords.add("to");
allWords.add("go");
allWords.add("to");
allWords.add("dubai");
allWords.add("and");
allWords.add("you");
allWords.add("also");
allWords.add("want");
allWords.add("to");
allWords.add("go");
allWords.add("to");
allWords.add("seychelles");
//printing all items in the 'allwords' arraylist
//System.out.println("CONTENTS OF 'ALL WORDS' ARRAYLIST : ");
distinctWords.add(0,allWords.get(0));
distinctWordsCount = 1;
int i = 1;
for(int j = 1; j <= distinctWords.size(); j++){
if(i < allWords.size()){
tracker = 0;
if (tracker == j){
distinctWords.add(j, allWords.get(i));
System.out.println("\t\t\t" + distinctWords.get(j));
distinctWordsCount ++;
i++;
} else
if (tracker != j){
if(allWords.get(i) != distinctWords.get(tracker)){
//distinctWords.add(allWords.get(i));
//distinctWordsCount ++;
tracker++;
}
else
if(allWords.get(i) == distinctWords.get(tracker)){
i++;
}
//System.out.println("CONTENTS OF 'ALL WORDS' ARRAYLIST : ");
//System.out.println("\t\t\t" + distinctWords.get(j));
}
}
//System.out.println("\t\t\t" + distinctWords.get(j));
}
//System.out.println("\n\nTHE NUMBER OF ITEMS IN THE 'ALLWORDS' ARRAYLIST IS : " + allWords.size());
//System.out.println("\n\nTHE NUMBER OF ITEMS IN THE 'DISTINCTWORDS' ARRAYLIST IS : " + allWords.size());
System.out.println("\n\nITEMS IN THE 'DISTINCTWORDS' ARRAYLIST ARE : " + distinctWords.size());
}
}
How about the following code:
for (int i = 0, size = allWords.size(); i < size; i++)
{
String word = allWords.get(i);
// add the word if it is not in distinctWords
if (!distinctWords.contains(word))
{
distinctWords.add(word);
}
}
If you don't care about the order of the words, then you could use a Set as suggested.
Set<String> distinctSet = new HashSet<String>(allWords);
// if you want the set put into your other arrayList
distinctWords.addAll(distinctSet);
//al1 and al2 are ArrayList<Object>
for(Object obj:al1){
if(!al2.contains(obj))
al2.add(obj);
}
I think this can give you a set of all distinct words.
Set<String> distinctWords = new HashSet<>(allWords);
If you do need an array, you can simple do this:
ArrayList<String> distinctWordsArr = new ArrayList<>(distinctWords);