Add array to another array of larger size - java

I have an array A of size 5000, and a smaller array B of arbitrary size but smaller than A. My smaller array always produces new values which I do not want to loose hence I add them to the array A and continue, however I am stuck because whenever I try to copy the smaller to the larger instead of appending from where it was left of it completely erases the prior values and array A becomes equal to array B.
offset = offset + B.length;
System.arraycopy(B, 0, A, offset, B.length);
This statement is in a loop that updates B everytime.

It would be a much better idea to use ArrayLists instead. An ArrayList is essentially an array with infinite capacity. You can just keep adding stuff and it will never run out of room. It also adds things to the end for you, without you having to compute the end index. So, if you make A and B ArrayLists, then your code becomes the following:
A.addAll(B);
That's it.

First of all, take a look at this link, and look at the section explaining the length parameter: http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/System.html. I think your problem resides in the length argument being passed in.
Also the statement offset = offset + B.length; should come after the loop, because you are passing in a variable size A.length + B.length, as supposed to just B.length, which is were you want to place array B.
the argument where A is is the destination array. So you have to redeclare A to be the length of offset.
Hope this helps.

Related

Why does the multidimensional array syntax work

When we create a 2d array such as int[][] a = new int[2][3] why is the resulting 2d array consist of a two-element array that contains three-element int arrays instead of the other way around. The reason why I'm confused is that when we make an array we do datatype[], so when we do int[2][3] why don't we put three int[2] arrays into an array with three spots (from the [3]).
The way it's implemented in Java is more logical. Consider the array element access expression: a[x][y]. Currently, it could be nicely decomposed to (a[x])[y] which means "we get an x-th element of a, then we get a y-th element of the result". So imagine if new int[2][3] produced an array of three elements, each is a two-element array. Then the x should be in range 0..2 and y should be in range 0..1 which is the opposite of the dimension order used at the array creation point. That would be absolutely confusing.
I guess you have a point with your logic. Eventhough you could also argument, writing int[2][3] means "first index can have 2 different values, second 3", what leads to the same as how it really works.
In the end, this is just a matter of specification and compilerbuilding. And since it is specified this way and not that way, it is implemented and works this way.

How to make zeros for next n-1 elements of n similar elements in an array?

I have an integer 667778 and I need to output it as 607008.
I used an array 6,6,7,7,7,8 and xor next similar elements.
I need to this in constant time.
suppose
int arr[]={6,6,7,7,7,8}
int ele=arr[0];
for (int i=1;i<arr.length;i++)
{
if(arr[i]==ele)
arr[i]=0;
else
ele=arr[i];
}
output array arr has [6,0,7,0,0,8]
It is taking O(n) n is size of the array
How can i do this in constant time?
Unless the number given will always be 6 digits (in which case you can hard code it, which is technically constant time, but will give equal performance to the loop), then you can't get constant time because the basis of the problem requires looping through the array in the first place.
Is there are reason you want it to work in constant time anyways, as O(n) is the fastest a program can read the data anyways.
Edit:
After reading your comments, I think you need to come up with a different approach so calculating the XORs won't be inside the loop. I can't provide much more help without the original problem.

How can I write this variable in the right way?

I have to write in Java (with Cplex) the variable x[i][j] that is the sum on k of x[i][j][k].
i,j and k are the indices of three sets.
I have already declare x[i][j][k], but i would like to know the right expression.
Thanks
You appear to be confusing yourself regarding the type of x[i][j]. Is it a set with several elements, indexed by k, or is it a number representing their sum? You seem to start out this step in computation with the first answer and conclude with the second.
A solution to this is to use another variable to store the result, maybe something like:
sums[i][j] = sum(x[i][j]);
where sum(list) is a function that takes in a list, starts with a return value of 0, and iterates over the elements of the input list adding each one to the return value, then returns that value. You can check here for some ideas about how to implement that.

Adding value to list initialize list size

I have below code:
Hashtable<Integer, List<Model>> map = new Hashtable<Integer, List<Model>>();
for (int i = 0; i < arraylistAssignment.size(); i++) {
List<Model> temp = null;
for (int j = 0; j < arraylistModel.size(); j++) {
if (arraylistAssignment.get(i).getId() == arraylistModel.get(j)
.getId()) {
if (temp == null)
temp = new ArrayList<Model>();// DEBUG POINT 1
temp.add(arraylistModel.get(j));
}// DEBUG POINT 2 AFTER ADD FUNCTION ABOVE
}
map.put(arraylistAssignment.get(i).getId(), temp);
}
In the above code at debug point 1 when when i hv intitilzed the temp variable , there the object size is 0 as showm below :
but as soon as i add i.e temp.add the size is 1 but objects create is 12 out of which 11 values are null as shown below ...i could not understand the reason for null values here can anyone plz exaplin ...m i initilzing wrong?
An ArrayList is a dynamic array, what means that it grows as elements are added. But it doesn't change its size "one by one". Its size grows a "reasonable" amount, so the operation of resizing the list is not repeated each time you add an element, because this would be inefficient.
The reason for null values is because that's how ArrayLists work on the inside. They start off with a blank array inside, and as you add things they resize themselves as they see fit. The reason the array is larger than the number of objects you put in is because it'd be highly inefficient to resize the array every time you added something, so instead the ArrayList implementers just made the inner array start off at a certain size and approximately double in size every time it needs to be resized. They track how many elements you put in by tracking a separate size variable.
So in other words, you're initializing things just fine. Don't worry about the internals of the ArrayList -- if you look at the internal size variable, you'll see that it is 1, just as you expect.
ArrayList is a data structure in the Collections framework which is built on top of arrays I.e. It's implementation is done with the help of arrays. Since size is to be defined in arrays, it initializes size to be 10 at first. When you add values, it becomes the 11th item.
Now you might wonder how is this dynamic and how it works, well when size is reached to its limit it creates a new array double the size, copies the old stuff and discards the prev array. Would recommend you to take a look at the implementation.
To the user, it looks like dynamic but when you look through debugger you would see nulls. Array STARTS at 0 to 10 which makes it 11 elements and your newly added item becomes 12th but for public api, it's still the first element.
Check here for complete implementation of ArrayList: link
From Java Dokumentation:
http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html
Each ArrayList instance has a capacity. The capacity is the size of the array used to store the elements in the list. It is always at least as large as the list size. As elements are added to an ArrayList, its capacity grows automatically. The details of the growth policy are not specified beyond the fact that adding an element has constant amortized time cost.
Default capacity is somehow 12 in your case, even though it should be 10.

Replacing two characters with one character in a char array

How to replace two characters with one character in a char array? Let me explain a bit more. I have a char array of length n . In this char array i want to replace two characters with one character in a specified index i. In this process the array length is going to decrease by 1.
The idea which i came to my mind is, first create a new char array of length n-1 then copy all elements from index 0 to index i (i excluding) then insert desired character at index i then copy elements from index i+2 (i including) to the index n-1. But this process require two times for loop. Is there any better approach which can do the same in efficient manner.
Or a more efficient way of doing this is to use a StringBuilder which is a wrapper for char[] and let it do it for you.
char[] chars = "Hello".toCharArray();
StringBuilder sb = new StringBuilder();
sb.append(chars);
sb.replace(2, 4, "L");
System.out.println(sb);
prints
HeLo
You can look at the code for replace to see how it does it.
Copy array portions with System.arraycopy() instead of iterating over its elements.
Given that you want a new array object, there's no faster way than by copying each array element once, so there's no more efficient method than this. If you use two calls to System.arraycopy(), you don't have to write the loops yourself.
If you don't need a new array object, you could just move the higher-numbered array elements down by one, which involves just half the number of copies -- but then you're going to need to keep track of the length some other way.
It could use a single for loop. Just put in an IF statement indicating if iteration (i) = index you want to replace then do a different operation rather than just copy.
Written in basic:
For i = 0 to n - 1
If i = x then
arrayCopy(i) = replaceChars
Else
arrayCopy(i) = arraySource(i)
End If
Next

Categories