Core Java Array Insertion - java

I want to insert an elements inside an array. I have one array1 of size 5(where all teh indexs are full).I have created one more array2 of size 6 and inserted all the elemnts of array1 inside array2. Now I want to insert an element in 3rd postion of array2 such that elements present in 3rd position will move to 4th, 4th will move to 5th and 5th will move to 6.
I have developed a program below. But getting string index out of bound exception. Please help me to fix this issue.

System.arraycopy(...) method is your helper. The rest you will do by yourself.

Sadly array is not the best for this task. I would recommend you to use List (ArrayList) in case if you don't have to bind yourself to arrays. And also you have the method toArray().
Here is a tutorial, but you will find numerous others: http://www.java-samples.com/showtutorial.php?tutorialid=234

I whipped you up something quick.
public int[] insert(final int[] array, final int index, final int...nums){
if(nums.length == 0){
return array;
}
int[] newArray = new int[array.length + nums.length];
int i = 0;
for(; i < index; i++){
newArray[i] = array[i];
}
for(int j = 0; j < nums.length; j++){
newArray[i + j] = nums[j];
}
for(; i < array.length; i++){
newArray[i + nums.length] = array[i];
}
return newArray;
}
I try to avoid System.arraycopy personally, as here you can see a better flow easier. It is more beneficial if you can see how it works, better than relying on someone else's code.

If You need insertions in the middle of array and change it's size dynamically - it's better to use LinkedList collection.

Related

i want fix my method to reverse int array

trying to write a method reverseIntArray(int[] array) which should return a reverse copy of an integer array. For example, if array = [1,2,3,4], then the method should return the array [4,3,2,1].
The program compiles without any error messages. What are the errors causing incorrect incorrect behavior of the program at runtime?
public static int[] reverseIntArray(int[] array) {
int[] result = new int[10];
int j = array.length;
for (int i = 1; i < array.length; i++ ) {
result[i] = array[j];
j++;
}
return result;
}
how should the error be corrected?
what exactly is the error?
what effect the error would have?
You need to set j to be array.length -1 instead of array.length and decrement it instead of incrementing it, and start your for loop index at 0 not 1.
There are a couple of issues with your code:
Your result array is being created with a size of 10 rather than the size of the array being passed in. This will cause an issue if you pass in an array with a smaller or larger size than 10. You can resolve this with: int[] result = new int[array.length];
You're initializing i with a value of 1. Java arrays start at index 0, so your loop will skip populating the first element of the array. You instead want: for (int i = 0; i < array.length; i++) {
Because java arrays start at index 0, the last element's index will be 1 less than array's size. You want: int j = array.length - 1;
You want to retrieve array's elements in reverse order, but your code is incrementing j rather than decrementing it. You want j-- where you have j++
To solve array related problem you must know only about its storage in memory and its index.
In your solution you are trying to overwrite values. In your solution you need to make sure that you are saving older value before writing any new value to any index.
NOTE: You must know that how to swap two numbers.
int[] arr={1,2,3,4};
int i=0;
int j=arr.length-1;
while(i<j)
{
//Swapping two numbers
int temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
i++;
j--;
}
You can also do the same using for loop.

Need help Removing Element from an Ordered Array using For Loop

I want to remove a single element from an array. This is what I have tried so far:
for (int i = pos + 1; i < currentSize; i++)
values[???] = values[i];
currentSize--;
I'm so confused on what goes inside the [???]
If anyone can help I would really really appreciate it.
Arrays are not very kind in nature, as they can't be resized. As soon as you have learned about objects and generics you will pretty much stop using arrays and transition to Collections. But for now, you'll have to create a new (smaller) array and copy all - but one - value. I will keep it very basic, so you learn the most:
int indexToRemove = 3;
Object[] newArray = new Object[values.length - 1];
for (int i = 0; i < newArray.length; i++) {
if (i < indexToRemove) {
newArray[i] = values[i];
} else {
newArray[i] = values[i + 1];
}
}
I didn't know of which type your values are, so I just took Object. You may want to replace that.
The ??? In this case indicates the index of the array where you wish to get the value from. If you have an array A with elements 5, 10, 15, and 20 then each of the elements can be retrieved with their index. I.e. the index for 5 is 0, for 10 its 1.
An array of size n will have n-1 elements in it due to zero indexing (A[0] is the first element).

Putting an array into a bigger array

I have an array of terms (terms meaning an object with a coefficient and a degree, represented as for example 1.0x^6). The array that I have right now contains 3 terms:
[1.0x^6, 4.0x^5, 10.0x^0].
My goal is to create a bigger array with these terms, but ALSO with terms with a 0 coefficient that are not represented in my array. That probably was not too clear, so here is basically what I want my new array to look like:
[1.0x^6, 4.0x^5, 0.0x^4, 0.0x^3, 0.0x^2, 0.0x^1, 10.0x^0].
Currently, I am iterating through my original array, and if the degree equals the new array.length - 1, I am setting newArray[i] = array[i], if that makes sense. For example, for the first term and i = 0, the degree is 6, and so if 6 = newArray.length - 1 (which is 6), then newArray[i] = array[i].
The problem, however is that array is smaller than newArray, so I am getting an out of bounds error. Any ideas on how to fix this? Sorry for the long post, thanks!
EDIT: Here is my actual code. Sorry if the explanation was unclear.
int max = 0;
Term temp;
for(int i=0; i<array.length; i++) {
max = i;
for(int j=i; j< array.length; j++) {
if(array[j].getDegree() > array[max].getDegree()) {
max = j;
}
}
temp = array[i];
array[i] = array[max];
array[max] = temp;
}
Above, the array is sorted in terms of descending degree. I want to now have the new array contain the old terms, but also 0x^i for all the i that are not used in my set of terms.
Term[] newArray = new Term[this.degree()+1];
for (int c = 0; c < newArray.length; c++) {
if (array[c].getDegree()==newArray.length-1-c) {
newArray[c] = array[c];
}
else {
newArray[c] = new Term(0, newArray.length-1-c);
}
}
There are issues in my code above, and I can see that now because in that for loop, array[c] is not defined for any c > 2. Eclipse is telling my that I have an out of bounds error.
Arrays have a fixed size. If you want to create a bigger array, you need to know the size beforehand and define it accordingly. Also, it seems that you are going through both the arrays using the same iteration variable.
I assume you are doing something like this:
for(i=0;i<newArray.length;i++){
newArray[i] = array[i]; //size of newArray is bigger than array
}
Then you will always get an array index out of bounds exception because "array" is smaller than "newArray" and you go out of bounds when i>=array.length.
You need to fix your code logic.

Getting the largest k elements of a double array

The problem I am facing is this one:
I have an array of doubles from which I want to keep the top k greater values.
I have seen some implementations involving Arrays.sort. For example in this example with relative issue it is suggested to use this approach.
Since I am only interested in the first k elements I have also experimented with MinMaxPriorityQueue. I have created a MinMaxPriorityQueue with a maximumSize:
Of course there is again autoboxing.
Builder<Comparable> builder = MinMaxPriorityQueue.maximumSize(maximumSize);
MinMaxPriorityQueue<Double> top2 = builder.create();
The problem is that the order is the ascending one that it's the opposite of the one I want. So I cannot use it this way.
To state the problem's real parameters my arrays is about 50 elements long and I am interested in up to the top k = 5 elements.
So is there any way to bypass this problem using the second approach? Should I stay with the first one even though I don't really need all elements sorted? Do you know if there is any significant difference in speed performance (I will have to use this in a lot of situations so that's where the speed is needed)? Is there any other solution I could use?
As for the performance, I know I can theoretically check it myself but I am a bit out of time and if someone have any solution I am happy to hear it (or read it anyway).
If you only have like 50 elements, as noted in my comment, just sort it and take the last k elements. It's 2 lines only:
public static double[] largests(double[] arr, int k) {
Arrays.sort(arr);
return Arrays.copyOfRange(arr, arr.length - k, arr.length);
}
This modifies (sorts) the original array. If you want your original array unmodified, you only need +1 line:
public static double[] largests2(double[] arr, int k) {
arr = Arrays.copyOf(arr, arr.length);
Arrays.sort(arr);
return Arrays.copyOfRange(arr, arr.length - k, arr.length);
}
You can use System.arraycopy on a sorted array:
double[] getMaxElements(double[] input, int k) {
double[] temp = Arrays.copyOf(input, input.length);
Arrays.sort(temp); // Sort a copy to keep input as it is since Arrays.sort works in-place.
return Arrays.copyOfRange(temp, temp.length - k, temp.length); // Fetch largest elements
}
For 50 elements, it is much faster to sort an array than to mess with generics and comparables.
I will write up an additional "fast" algorithm...
double[] getMaxElements2(double[] input, int k) {
double[] res = new double[k];
for (int i = 0; i < k; i++) res[i] = Double.NEGATIVE_INFINITY; // Make them as small as possible.
for (int j = 0; j < input.length; j++) // Look at every element
if (res[0] < input[j]) { // Keep the current element
res[0] = input[j];
Arrays.sort(res); // Keep the lowest kept element at res[0]
}
return res;
}
This is O(N*k*log(k)) while the first one is O(N*log(N)).

Most efficient way to remove an element from an array, then reduce the size of the array

Say I have an array of 10 elements. Another part of my program determines I must remove the item at index 4.
What is the most efficient method to remove the item and shorten the array?
I wrote the following method, however it does not seem to work properly. Am I missing something, for example if the index to remove is 0? The method is called by sending an array and the index to be removed.
I realize there are Array Lists and other types of lists. However this is an assignment for a programming course and MUST use ARRAYs.
//Removes the index from the array and returns the array.
NumberTile[] removeAndTrim(NumberTile[] array, int index){
NumberTile[] save = array;
array = new NumberTile[save.length-1];
for (int i=0; i<index; i++){
array[i]=save[i];
}//end for loop
for (int j=index; j<save.length-1; j++){
array[j]=save[(j+1)];
}
return array;
}//end removeAndTrim
public NumberTile[] removeAndTrim(NumberTile[] a, int index){
NumberTile[] result = new NumberTile[a.length-1];
for (int i = 0; i < result.length; i++){
result[i] = a[((i < index) ? i : i + 1)];
}
return result;
}
Your most efficient way would be one loop / traversal and one array creation.
(Without using arraycopy that is).
Note: This doesn't alter the values of the parameter array at all, just returns a new one.
Your method is the most efficient possible assuming this is an exercise where you are not allowed to use libraries, utility classes like arraylist or System.arraycopy. Reasoning:
You can't avoid constructing a new array since a) you need one that is one element shorter and b) Java arrays are fixed size so you can't change the existing one
You need to copy length-1 elements in order to populate the new array. Doing this in a tight loop is the fastest you can do in pure Java.
As a style point, you should probably call the new array "result" or somthing similar and avoid the fiddling around with trying to save the array. This is pointless - you can't alter the input parameter.
Note that your function needs to be used as follows:
NumberTile[] newArray=removeAndTrim(oldArray,index);
NumberTile[] removeAndTrim(NumberTile[] array, int removeIndex) {
NumberTile[] newArray = new NumberTile[array.length - 1];
for (int i = 0; i < removeIndex; i++) {
newArray[i] = array[i];
}
for (int i = removeIndex + 1; i < array.length - 1; i++) {
newArray[i] = array[i + 1];
}
return newArray;
}

Categories