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).
Related
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.
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.
I have an ArrayList of int.
The main program - calls a method to get a list of the sum of all (n member) combination of the members of the list. Where n can be anywhere between 2 - 6. E.g. Original List is {1,2,3,4,5}; Then the output should be {6, 7, 8, 8, 9, 10, 9, 10, 11, 12} where n = 3;
I am looking for the optimum way to do this. Right now, the way I have written the program (which is working) is without recursion. I have methods for all numbers i.e.
MyMethod2 -- gives me all the sum of 2 member combinations of MyArrayList
MyMethod3 -- gives me all the sum of 3 member combinations of MyArrayList
MyMethod4 -- gives me all the sum of 4 member combinations of MyArrayList
......
So, you can see that there is a lot of duplicate set of codes.
Also the way the program has currently been written (e.g. My Method3):
MyMethod3
ArrayList<Integer> sum = new ArrayList<Integer>();
for (i = 0; i < MyArrayList.size(); i++){
for (j = i + 1; j < MyArrayList.size(); j++){
for (k = j + 1; k < MyArrayList.size(); k++){
int total = MyArrayList.get(i) + MyArrayList.get(j) + MyArrayList.get(k);
sum.add(total);
}
}
}
return sum;
The MyMethod for n = 6, can become pretty long. Also "n" can change in the future.
Is there a better way to do this using recursion to minimize duplicate code, and using the number n as a variablefor the method call. Is there a standard package in Java that can help with recursion.
Adding the Code based on #Maertin suggestion - which worked for me
ArrayList<Integer> myArray = new ArrayList<Integer>();
myArray.add(5);
myArray.add(6);
myArray.add(4);
myArray.add(2);
myArray.add(1);
ArrayList<Integer> finalSumArray = combineTwoArrayList(3, myArray, myArray);
public static ArrayList<Integer> combineTwoArrayList(int n, ArrayList<Integer> origArray, ArrayList<Integer> finalSumArray) {
if (n == 1) return finalSumArray;
ArrayList<Integer> finalSumArray = new ArrayList<Integer>();
for (int i = 0; i < sumArray.size() - 1; i++){
for (int j = i + 1; j < origArray.size(); j++){
finalSumArray.add(sumArray.get(i) + origArray.get(j));
}
}
--n;
return combineTwoArrayList(n, origArray, finalSumArray);
}
You are correct in wanting to do this via recursion, because now, instead of having three separate methods, you could have one method with a parameter n for n-member combinations.
public int nCombinationSum( int n, int i, ArrayList<Integer> arr, ArrayList<Integer> sumArr) {
/* Gets n-combination sums and puts into sumArr
Input: n consecutive element combination, current index i in arr, and output ArrayList
Output: Gets n consecutive element combinations in arr from index i to index (i + n) and puts into sumArr
*/
//**BASE CASE**
//if index out of arr bounds
if( i + n > arr.size() )
return 0;
//**RECURSIVE CASE**
else {
//sum of values in arr from i to (i + n)
int currComboSum = 0;
for( int j = 0; j < n; j++ )
currComboSum += arr.get(j);
//adding sum to next element in resultant array
sumArr.add( currComboSum );
return nCombinationSum( n, i + 1, arr, sumArr );
}
}
USAGE
In your main method, you can call nCombinationSum and provide it with the kind of combination (n), starting index (in your case, 0), and arrayList (arr), and the arrayList you want to append the sums in (sumArr).
This also has the potential added benefit of allowing you to add any n-combination sum starting from a certain index. If you would like, you could add an end index as well, but this is fairly extended as it is.
EDIT: Please edit your question to reflect that you want the result to be an arrayList of sums, rather than the total sum. It is not clear right now.
Basically, what you want to do with recursion, in general, is to set a base case and a recursive case.
Your base case would be if your index is out of bounds, because you're going to call all elements from index i to i + n.
For the recursive case, use the algorithm below to account for each element in arr, then just keep returning the function with the next index value, and the function will continue running until it is out of bounds.
Algorithm
Getting sum of n-combination elements
Appending that sum into resultant array sumArr
Feel free to refer to the code above for reference.
You can use recursion. Basically, you should have only two for loops. (which is the code for two member combinations). When you compute 'total', pass each 'total' value to an ArrayList MyArrayList2. Now for MyMethod3, you use the elements of MyArrayList2 and the original ArrayList and find new 'total' values again and pass that to MyArrayList3. For MyMethod4, you use the elements of MyArrayList3 and the original ArrayList and find new 'total' values again and pass that to MyArrayList4.... ....
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.
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;
}