Movement Of Numbers in an array row - java

I am having trouble visualizing what happens when I have e.g. a row of numbers [1,2,3,4,5] and I either want to shift these numbers to the front of the row or to the back of the row.
Essentially here, I am going through my row, back to front and adding each number. But at the same time, shifting the indexes one to the right in my row.
A code snippet:
void addCoordinateRowFront(CoordinateRow rowOfCoordinates) {
for(int j = rowOfCoordinates.numberOfElements; j > 0; j--) {
for(int i = numberOfElements; i > 0; i--) {
newCoordinateArray[i] = newCoordinateArray[i-1];
}
newCoordinateArray[0] = rowOfCoordinates.newCoordinateArray[j-1];
numberOfElements++;
}
}
}
But I am still not really understanding what is happening.
For instance, if I have a row [1,2,3,4,5] what is the outcome if I add these numbers to the front or to the back of the row?

newCoordinateArray[i] = newCoordinateArray[i-1]; is basically shifting the elements to the back, i.e. the element at index 2 will get the value from index 1, then index 1 will get the value from index 0. Finally, index 0 will get the new value.
Inner loop
This means, your inner loop would turn [1,2,3,4,5] into [1,1,2,3,4] if it were correct:
a[4] = a[3] -> value at index 4 will be the value of index 3, result is [1,2,3,4,4]
a[3] = a[2] -> [1,2,3,3,4]
a[2] = a[1] -> [1,2,2,3,4]
a[1] = a[0] -> [1,1,2,3,4]
If you look at the example, you should be able to spot the error in your inner loop:
int i = numberOfElements would mean i = 5 if numberOfElements actually means rowOfCoordinates.numberOfElements (which would be 5 in the example). However, a[5] = ... will cause an ArrayOutOfBoundsException because the highest index in a 5-element array is 4.
Outer loop
Your outer loop moves into index 0 starting at the last element (a[0] = a[j-1]). This means after the first run of the inner loop you have [1,1,2,3,4] and now a[0] = a[4] will result in [4,1,2,3,4].
Now let's look at the other iterations of the outer loop:
j = 4 -> inner loop result: [4,4,1,2,3], a[0] = a[3] results in [2,4,1,2,3] (value at a[3] is 2)
j = 3 -> inner loop result: [2,2,4,1,2], a[0] = a[2] results in [4,2,4,1,2] (value at a[2] is 4)
j = 2 -> inner loop result: [4,4,2,4,1], a[0] = a[1] results in [4,4,2,4,1] (value at a[1] is 4)
j = 1 -> inner loop result: [4,4,4,2,4], a[0] = a[0] doesn't change anything so the end result would be [4,4,4,2,4]
How to shift in place
If you want to shift elements in an array without creating a copy of the array, i.e. shift in place, you can do the following:
//replace 1st element
int replacedIndex = dir;
int replacedValue = array[replacedIndex];
array[replacedIndex] = array[0];
//replace all other elements
for( int i = 1; i < array.length; i++) {
replacedIndex = (replacedIndex + dir) % array.length;
int temp = array[replacedIndex];
array[replacedIndex] = replacedValue;
replacedValue = temp;
}
What this means is the following:
You shift the first element to its new position which replaces another element. So you keep track of the replaced element and what index it was at. The loop now shifts the replaced element which replaces another one which the next iteration takes care of.
So shifting [A,B,C,D,E] by 2 would mean:
Initially shift A from index 0 to index 2, so C will be replaced. Result: [A,B,A,D,E].
C will be shifted from index 2 to index 4: [A,B,A,D,C]
E will be shifted from index 4 to index 1 (wrap around): [A,E,A,D,C]
B will be shifted from index 1 to index 3: [A,E,A,B,C]
D will be shifted from index 3 to index 0 (wrap around): [D,E,A,B,C]
The modulo operator can also be used to allow for larger shifts which basically are brought back into range, i.e. shifting a 4 element array by 13 is the same as shifting it by 1 (13 % 4 = 1).
Negative shifts can be supported by bringing the shift into a positive range by adding the length, i.e. given a 5 element array a shift by -1 (1 to the left) is the same as a shift by 4 (4 to the right).
So you could do this at the start:
//copy the initial parameter to keep the original value
int dir = direction;
//shift direction into a positive range
while( dir < 0) {
dir += array.length;
}
//bring any out-of-range direction back into range
dir %= array.length;

Related

Reversing elements in array

I've been looking at a for-loop that reverses the elements in an array, but I do not quite understand what's going on inside it. This is the code:
int middleIndex = (array.length) / 2;
for (int i = 0; i < middleIndex; i++) {
int temporaryVariable = array[i];
array[i] = array[array.length - 1 - i];
array[array.length - 1 - i] = temporaryVariable;
}
What exactly does the two lines below int temporaryVariable = array[i] do? How exactly does it reverse the elements?
It effectively reverses the elements of the array by swapping first with last element, second with second_last etc. In this way the number of operations are ayrray_length / 2.
The 2 lines after int temporaryVariable = array[i]; simply swap the i'th element with the i'th from last element, and we run this loop half time the number of elements in array.
First of all remember that array indexes start from 0.
So the index of the last element is the array.length - 1.
Those 3 lines are swapping the first item with the last item, then the 2nd item with the 2nd-from-last item, etc. The temporaryVariable is used as a temporary place to store one of the values during swapping, so that it doesn't get lost when it is overwritten by the other value.
Take a copy of the value at i:
int temporaryVariable = array[i];
Put item i from the end of the array (array.length - 1 - i) instead of it.
array[i] = array[array.length - 1 - i];
Put the temporarily stored item which was item i at i from the end (array.length - 1 - i).
array[array.length - 1 - i] = temporaryVariable;
The loop stops when i reaches the middle of the array. (If the array has an odd number of elements the middle one stays where it is.)
This algorithm is taking N/2 iterations of swapping values stored in an array. It starts from the beggining of the array (Index 0) and goes until its half(index N/2). It swaps the first element(indexed 0) with the last one (indexed N - 1 - 0), then swaps the second element(indexed 0 + 1) with the one before the last one(indexed N - 1 - (0 + 1)), and so on.
another part was to return the second biggest number, but for some reason it returns the third biggest number, which is really weird.
This is the code:
public static int returnSecondBiggest(int[] array) {
int largestElement = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] > largestElement) {
largestElement = array[i];
}
}
int secondBiggest = Integer.MIN_VALUE;
for (int i = 0; i < array.length; i++) {
if (array[i] > secondBiggest && array[i] != largestElement) {
secondBiggest = array[i];
}
}
return secondBiggest;
}
How does it return the third when the code should return the second? I'm so lost.

What is this algorithm doing?

I got a pseudocode:
Input: Array A with n (= length) >= 2
Output: x
x = 0;
for i = 1 to n do
for j = i+1 to n do
if x < |A[i] - A[j]| then
x = |A[i] - A[j]|;
end if
end for
end for
return x;
I have converted that to a real code to see better what it does:
public class Test
{
public static void main (String[] args)
{
int A[] = {1,2,3,4,5,6,7,8,9};
int x = 0;
for (int i = 1; i < A.length; i++)
{
for (int j = i + 1; j < A.length; j++)
{
if (x < Math.abs(A[i] - A[j]))
{
x = Math.abs(A[i] - A[j]);
}
}
}
System.out.println(x);
}
}
The output was 7 with the array in the code.
I have used another array (1 to 20) and the putput was 18.
Array 1-30, the output was 28.
The pattern seems clear, the algorithm gives you the antepenultimate / third from last array value. Or am I wrong?
I think the pseudo code tries to find the greater of the difference between any 2 elements within an array.
Your real code however, starts from 1 instead of 0 and therefore excludes the first element within this array.
I think pseudocode is trying to find the greatest difference between two numbers in an array. It should be the difference between the minimum and maximum value of the array.
I personally think this is a really poor algorithm since it is doing this task in O(n^2). You can find the min and maximum value of an array in O(n). and take the difference between those numbers and result will be the same. check the pseudocode
Input: Array A with n (= length) >= 2
min=A[0];max = A[0];
for i = 1 to n do
if min > A[i] then
min = A[i];
end if
if max < A[i] then
max = A[i]
end if
end for
return (max-min);
The code gives the biggest difference between any two elements in the array.
There are 2 nested loops, each running over each element of the array. The second loop starts at the element after the first loop's element, so that each possible pair is considered only once.
The variable x is the current maximum, initialized to 0. If x is less than the absolute value of the current pair's difference, then we have a new maximum and it is stored.
However, because you directly copied the pseudocode's starting index of 1, you are inadvertently skipping the first element of the array, with index 0. So your Java code is giving you the maximum difference without considering the first element.
If you have an array of values between 1 and n, you are skipping the 1 (in index 0) and the returned value is n - 2, which happens to be the third-to-last value in the array. If you had shuffled the values in the array as a different test case, then you would see that the returned value would have changed to n - 1 as now both 1 and n would be considered (as long as n itself wasn't in the first position).
In any case, you would need to set the index of the first element to 0 so that the first element is considered. Then {1,2,3,4,5,6,7,8,9} would yield 8 (or any other order of those same elements).
Assuming all positive integers, the algorithm in a nutshell finds the difference between the maximum and the minimum value in the array. However, it will not work correctly unless you initialize i to 0 in the for loop.
for (int i = 0; i < A.length; i++)

Testing elements in an array

Hello I have searched for a simple way to check ,
if any number of elements up to 6 in the array add up to seven. I have yet to find one my array is this,
private int[] diceRoll = new int[6];
The question is a bit vague, however, here's my attempt at an answer:
If what you're trying to do is take two indices x and y in diceRoll[] and see if they add up to 7, the simplest thing to do is
if(diceRoll[x] + diceRoll[y] ==7){
return true;}
If you're trying to see if ANY item with any other item adds up to 7, use a double for-loop (these are weird, but very helpful)
for(int i = 0; i < diceRoll.length; i++){
for(int j = 0; i < diceRoll.length; i++){
if(diceRoll[i] + diceRoll[j] != 7){
return false;
}
}
}
Hope this helps!
-katie
It sounds like what you need to do is take every subset of the diceRoll array and see which ones add up to 7. This is how it can be done.
Assuming you know that 1 & 1 = 1, and that 1 & 0 = 0, imagine each element of the array having a number in 0 0 0 0 0, if the element is selected, say element 5, the subset representation in binary form would be 0 0 0 0 1. If element 2 and 3 are selected, the subset representation would be 0 0 1 1 0. If you take a binary one, keep track of its index, and move it from right to left in the array computing index&1 each time, you can get which indexes of the array are in the current subset (if the index&1 computation results in a 1 for that index). Translating this to a smaller array called currSubset, you can sum it up and check if it is equal to 7.
The termination of the outer for loop comes from the maximum value of a 5 digit binary number, which is 11111 = 31 = 2^5-1, hence the use of the less than sign.
int sum = 0;
int index = 0;
ArrayList<ArrayList<Integer>> subsetsThatAddTo7 = new ArrayList<ArrayList<Integer>>();
for(int subsetRep = 0b00001; i < Math.pow(2,5); i++){
ArrayList<Integer> currSubset = new ArrayList<Integer>
for(index = 0; index < 5; index++){
if(subsetRep & (1 << index))
currSubset.add(diceRoll[5-index]);
}
int sum = 0;
for(int num : currSubset)
sum += num;
if(sum == 7)
subsetsThatAddTo7.add(currSubset);
}

Java - create a array with the length of an index

I am trying to create a array with Java that can hold as many numbers as the index 'i' is big.
for (int i = 0; i <= 10; i++)
{
int[] zahlenListe = new int[i];
zahlenListe[i] = i + 5;
System.out.println(zahlenListe[i]);
}
but I am always getting the error message:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at Start.main(Start.java:27)
Java:27 is this line of code: zahlenListe[i] = i + 5;.
But everything is working fine when I change this line
int[] zahlenListe = new int[i];
to this:
int[] zahlenListe = new int[11];
Anybody cares to explain where the error is?
Array indices are zero based. Hence the maximum index for i sized array is i-1.
An array of length i doesn't have an i'th index. The valid indices go from 0 to i-1.
If you initialize your array with int[] zahlenListe = new int[i+1];, you'll be able to assign a value to zahlenListe[i].
int[] zahlenListe = new int[i];
zahlenListe[i] = i + 5;
Arrays start at index 0.
So index i will never be in an i-dimensional array. It stops at i-1.
For i == 0 the array is empty (no entries at all).
You may want to start your loop at i=1.
From your code it is also not clear why you need an array at all (but you probably have more code in there that you are not showing).
If you creating an array using:
int[] zahlenListe = new int[i];
The last element in array zahlenListe would be zahlenListe[i-1] instead of zahlenListe[i]. In addition, assuming i should start with 1 instead of 0 because an array of length is pointless.
Therefore, use
zahlenListe[i-1] = i + 5;
System.out.println(zahlenListe[i-1]);
You need to start 0 to size-1 in an array as you see;
int[] zahlenListe = new int[i];
Your array size is always i which means you can allowed to access max i-1
Assuming that i always bigger than 0
Basically because in your condition you are telling the computer to go to the 11th element. Think of it this way ...
int i = 0;
First iteration i = 0
if i <= 10; then i = i + 1
Second iteration i = 1
if i <= 10; then i = i + 1
Third iteration i = 2
if i <= 10; then i = i + 1
Fourth iteration i = 3
if i <= 10; then i = i + 1
Fifth iteration i = 4
if i <= 10; then i = i + 1
Sixth iteration i = 5
if i <= 10; then i = i + 1
Seventh iteration i = 6
if i <= 10; then i = i + 1
Eighth iteration i = 7
if i <= 10; then i = i + 1
Ninth iteration i = 8
if i <= 10; then i = i + 1
Tenth iteration i = 9
if i <= 10; then i = i + 1
Eleventh iteration i = 10
if i <= 10; then i = i + 1
Once you get here you are trying to access an element that does not exist. Because your condition says that as long as i is less that or equal that 10, it should repeat the task. If you change <= for < then you stop at the last element available.

Pseudo code needed if possible?

I was wondering if I could have some pseudo code for working out the following
i need to loop through a 2d array(the method i am working on takes an int). It starts at the position of the value passed in and then goes down until it hits the same value on the left hand side. As its doing this every int in the 2d array is added to a local variable.
Now we are at position (x,x) i guess? Then from here i need to loop across to the right adding all variables to the same previous local var and then return that number
The 2d array for illustration purposed looks something like this for example
1 2 3 4
2 3 4 5
1 2 3 4
3 2 1 4
So if i were to pass in 2 we would start at the number 3 top line i guess, we would loop down until position 3,3 ( 3 + 4 + 3) and then loop to the right until the end (+ 4)
those numbers would be added and returned.
I hope pseudo code is possible and I haven't just given it already myself lol (thus proving i cant actually code it lol :D )
if not any examples you could provide me with that my help me out :D
thanks guys
I think this pseudocode should do what you're looking for:
array[][] := ...
position := ...
sum := 0
//add the contents of the outer array
for i := 0 to array.length do
sum := sum + array[i][position]
//if we're at (pos, pos) then start looping over the inner array
if i = position then
//note we start at pos + 1 so as not to count array[i][position] twice
for j := position + 1 to array[j].length do
sum := sum + array[i][j]
end
break from loop
end
end
Not sure what you are trying to achieve, I assume this is just an assignment.
If you are looping to the right, shouldn't 1 be included if not the 2 as well?
i.e. then loop to the right until the end (+1 + 4)
The answer depends on whether you store the columns or the rows of matrix. Assuming you have a n * n size matrix and you store the rows, so
A = [[1,2,3,4], [2,3,4,5], [1,2,3,4], [3,2,1,4]]
and the starting point is i, you should go from the array no. m = i div n (the integer part of the division, rounding down), and inside the array, the staring element should be the no. p = i mod n (the modulus). And from that point, you can select every array from m to n, and in every array, the pth element, until the most recent element is the same as your original.
In Java-like code:
int n = 4;
int[][] A = new int[n][n];
... // initialize A
int sumValues(int i) {
int original = A[i/n][i%n];
int sum = original;
int p = i % n;
for (m = i/n + 1, m<n, ++m) {
if (A[m][p] != orginal) sum += A[m][p];
else break;
}
return sum;
}
If you are storing the columns, so
A = [[1,2,1,3], [2,3,2,2], [3,4,3,1], [4,5,4,4]]
then m and p are inversed, meaning that from A you should select array no. m = i mod n and inside that array, element no. p = i div n. After this, you stay in your selected array, and just increase p until A[m][p] equals to the originally selected value.
In Java-like code:
int n = 4;
int[][] A = new int[n][n];
... // initialize A
int sumValues(int i) {
int original = A[i%n][i/n];
int sum = original;
int p = i / n;
for (p = i/n +1, p<n, ++p) {
if (A[m][p] != orginal) sum += A[m][p];
else break;
}
return sum;
}
But correct me, if I'm wrong :)

Categories