I have this piece of code:
List<ArrayList<Integer>> tree = new ArrayList<ArrayList<Integer>>();
tree.add(0, new ArrayList<Integer>(Arrays.asList(1)));
tree.add(1, new ArrayList<Integer>(Arrays.asList(2,3)));
tree.add(2, new ArrayList<Integer>(Arrays.asList(4,5,6)));
I would like, for example, to replace 5 with 9. how can I do this?
use
tree.get(2).set(1,Integer.valueOf(9));
to get the ArrayList at the position 2 and then set the second element to 9.
tree.get(2).set(1, 9)
This gets the third (i.e. index = 2) element of the outer ArrayList, which returns the inner ArrayList. Then set the 2nd element (index = 1) to 9. Autoboxing takes care of the int to Integer conversion.
find index of elements that you want to replace and use twice set(index, newElement)
method to do the replacement
The major methods we use in a 2-Dimensional ArrayList are -->
let say we have a 2-Dimensional ArrayList as
ArrayList<ArrayList<Integer>> ArrayList_2D = new ArrayList<>()
To find the size
ArrayList_2D.size();
To access some element at position (i , j)
ArrayList_2D.get(i).get(j);
To set value of an element at position (i , j) equal to x
ArrayList_2D.get(i).set(j , x);
To remove (i , j) element
ArrayList_2D.get(i).remove(j);
To find the index of first occurring of element y
int col , row;
for(int a=0;a<ArrayList_2D.size();a++){
for(int b=0;b<ArrayList_2D.size();b++){
if(ArrayList_2D.get(i).get(j)==y){
col = i;
row = j;
break;
}
}
}
Hope This Is Will Be HelpFul
Related
I have an an array [1,1,1,1,1,1] and I want to make a for loop that will insert a 0 in between all the 1s.
I’ve tried using
for(int i=0;i<array.length;i+2) {
insertItem(array,i,0);
}
But this doesn’t work since the array increases in length every time you insert an item, and my client crashes.
Create a new array that is twice the length of the input, then loop through your input array and for each element, add it to the new array followed by a 0 updating an index as you go so that you are putting your 1s and 0s in the right position.
Not sure if you want a 0 at the end, if not adjust the details above accordingly (eg new array is twice size of input minus 1)
I'm assuming insertItem increases the length of array as needed. In that case the trick is to calculate the number of new insertions required (array.length - 1) before starting the loop. New values are inserted at odd locations, given by 2*i+1
int n = array.length - 1;
for(int i=0; i<n; i++) {
insertItem(array, 2*i+1, 0);
}
An alternative would be to create a new array and populate it like this:
int[] narr = new int[2*arr.length-1];
for(int i=0; i<narr.length; i++) {
narr[i] = (i % 2 == 0) ? arr[i/2] : val;
}
I think you just created an infinite loop. In your for loop, the i+2 should be replaced by i+=2. If not, the condition will never be met.
How can I add value to appropriate element of an array?
E.g. if I have created an int array
int[] scores = new int[4];
And I want to add the value '3' to the first element in the 'scores' array (index 0).
Can you advice on how do this?
Array supports index based access. Simply do:
scores[0] += 3;
lets say i have this array
int [] array= new int[26];
it has 26 places because the position 0 is 'a' , position 1'b' ... position 25 is 'z'
so in each position i have an int number so
if in position array[0]=5 it means i have 5 'a'
if in position array[1]=6 it means i have 6'b'
if in position array[0]=0 it means that i do not have the 'a' letter
what i want is to find in each loop the 2 smallest frequencies and the letters of the two smallest frequencies
for(int i=0;i<array.length;i++)
if(array[i]==0)
continue;
else{
cmin1=(char)('a'+i);
posi=i;
min1=array[posi] ;
break;
}
for(int j=posi+1;j<array.length;j++){
if(array[j]==0)
continue;
else if(array[j]<=min1){
posj=posi;
posi=j;
cmin2=cmin1;
cmin1=(char)(j+'a');
min2=min1;
min1=array[j];
}
i have tried this which is wrong
Java is Object Oriented so...
Let's take a class, which name would be LetterFrequency
LetterFrequency has 2 attributes:
1) Char character
2) Integer occurrences
You need to sort the LetterFrequency objects by their "occurrences" atrribute. To do that, make LetterFrequancy implements Comparable and define method compareTo() accordingly.
Then put all your LetterFrequency objects in a List and use the method
Lists.sort(yourList)
Sort would work but it's not the best performing method.
How about a single loop which would be O(n)?
int min1 = Integer.MAX_INT;
int idx1 = -1;
int min2 = Integer.MAX_INT;
int idx2 = -1;
for(int i=0;i<array.length;i++) {
// skip empty items
if(array[i]==0)
continue;
if (array[i] < min1) {
min2 = min1;
idx2 = idx1;
min1 = array[i];
idx1 = i;
}
else if (array[i] < min2) {
min2 = array[i];
idx2 = i;
}
}
sort the array first...now apply the searching algorithm...and here you go
once you find the smallest element you can get the second smallest as the array is already sorted...i guess there would be no difficulty doing this...for sorting you can use quicksort with complexity(nlogn)...hope it helps you
I would create a class representing each frequency count. Then I would create a Comparator which orders the records by the frequency. Then I would use Arrays.sort() or Collections.sort() to sort the collection using the Comparator.
Alternatively, if you simply want to find the entries in the array but can't change your data type, then you need to define an algorithm for searching (not sorting) the array. To do this, and do it in one pass, I would define local variables for the positions and corresponding frequencies of the two least frequently occurring. Initialize the least to the first item in the array, then proceed by comparing the current one and if it is less then rotate the values of the variables which are keeping track. At the end you'll have the two least frequent.
If you just want to find the smallest element in an array, you can use the following code :
List<int> list = Arrays.asList(ArrayUtils.toObject(array));
// Print the smallest element of your array
System.out.println(Collections.min(list));
First of all, this array declaration will never work:
int [] array= new array[26];
You need:
int [] array= new int[26];
This is my current progress on a project. I am trying to implement this ArrayList stuff but file continues to trow the same exception.
import java.util.*;
public class Numerican{
public static void main( String [] args ){
Scanner input = new Scanner(System.in);
ArrayList<Integer> array = new ArrayList<Integer>(10);
int count = input.nextInt() * 2;
while (count > 0){
array.add( 0 );
count = count - 1;
array.add(count, 2);
}
array.add(2, input.nextInt());
System.out.println(array.get(2));
}
}
It was my understanding that = new ArrayList<Integer>(10); would set the array size to 10. Did I do something wrong?
= new ArrayList<Integer>(10);
This line initializes the CAPACITY to 10, meaning the memory is allocated in the backend, but as far as you are concerned, the array is still empty.
Javadoc -
public ArrayList(int initialCapacity)
Constructs an empty list with the specified initial capacity.
This is why the calls to add might fail, if you try to add beyond the size of the ArrayList.
p.s. remember that add function takes index first and then element, when using the 2 parameter variant.
Edit:
ArrayList has 2 different member variables, size and capacity. Capacity is how much memory is allocated, size is how many elements are inserted by programmer.
Here, Capacity = 10, Size = 0;
According to the javadocs:
Constructs an empty list with the specified initial capacity.
Note that the ArrayList is empty (i.e. does not contain any items). The value indicates the capacity of the ArrayList which is the number of elements which can be added before more memory must be allocated.
On the other hand, calling add() actually adds an item to the ArrayList. In your example, array.add( 0 ); adds a 0 at the end of the list and array.add(count, 2); adds a 2 at index count. I suspect the problem is that count is not a valid index in your ArrayList. You should check what its value is by inserting an SOP or using a debugger.
count maybe >= 10, maybe souce code can answer you question:
public void add(int index, E element) {
rangeCheckForAdd(index);
ensureCapacityInternal(size + 1); // Increments modCount!!
System.arraycopy(elementData, index, elementData, index + 1,
size - index);
elementData[index] = element;
size++;
}
rangeCheckForAdd():
/**
* A version of rangeCheck used by add and addAll.
*/
private void rangeCheckForAdd(int index) {
if (index > size || index < 0)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
if the index is out of range (index < 0 || index > size()) IndexOutOfBoundsException will be thrown.
So i think you are accessing index > size() of the list.
size() ===> Returns the number of elements in this list.
array.add(2, input.nextInt()); here is the possible exception when your list size is 1...
From my understanding of ArrayList, you need to add items to the list in a sequential index.
i.e. You cannot add an item to the 7th index position if 1 to 6 have not been filled in.
ArrayList.add(indexPosition, element);
If you add elements to the list, starting at indexPosition 0, and increasing the indexPosition by 1 each time, it should work.
Ex.
int i = 0;
(while i < 10){
array.add(i, numberToAdd);
i++; }
Hey seems like your Problem is because of the line
array.add(count, 2);
adds a 2 at index count
For example your input size is 5 then array.add(9,2); the array size is only 1 by that time as capacity and size are two different parameters for a ArrayList. So you can use a for loop instead of while to insert your values
for(int i=0; i<count;i++)
{
array.add(i,2);
}
I am looking for some help with my Java programming assignment. Using a linked list, I need to print out its power set. For example, the set {1,2,3} should print out
{{},{1}{1,2}{1,3}{1,2,3}{2}{2,3}{3}}. The number of elements in the power set is 2^n.
This needs to be done by calling
HeadNode.PrintPowerSet();
where HeadNode is the first element in the linked list.
I have tried a few things and nothing is working that well. I think the best way to do it would be to call the method recursively until the end sentinel is reached and then work backwards, adding the elements that are left. Sorry I can't post more code or more ideas because nothing I have tried has worked that well. Thanks in advance.
EDIT:
This is the non working code. It returns the set {{1,2,3}{2,3}{3}}
public RSet powerSet()
{
if (this == EMPTY_SET)
return EMPTY_SET;
RSet q = new RSet();
if (q != EMPTY_SET)
q.next = next.powerSet();
q = new RSet(this, n, q.next);
return q;
}
EMPTY_SET is the end sentinel. I've tried writing it out by hand. It helps but I still can't get it. Also this class, RSet, is essentially just a linked list node.
Just iterate all the numbers from 0 to 2^n - 1. Each defines an element of the power set:
The list defines a fixed index on your set. For each number, create a new set. Considering the number in its binary format, add the item in the original set at index i to the set if the bit at index i is 1 and don't add it otherwise.
Then, for each number you will have a set that is an element of the power set.
int n = list.size();
Set<Set<T>> powerSet = new HashSet<Set<T>>();
for( long i = 0; i < (1 << n - 1); i++) {
Set<T> element = new HashSet<T>();
for( int j = 0; j < n; j++ )
if( (i >> j) % 2 == 1 ) element.add(list.get(j));
powerSet.add(element);
}
return powerSet;