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 :)
Related
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;
I'm a student and I'm taking a DSA course. On our latest assignment we were asked to implement a recursive variation of bubble sort. The assignment was alrady submitted but I couldn't make it work and it's frustrating me. I've triple checked everything and I can't find the problem.
The general pseudo-code for the algorithm is:
if (n > 10) // n being the size of array A
sort recursivley the first 2/3 elements in A (from 0 to ceil(2n/3))
sort recursivley the last 2/3 elements in A (from floor(n/3) to n)
sort recursivley the first 2/3 elements in A (from 0 to ceil(2n/3))
else
use bubbleSort
This is the code I wrote:
public static void weirdSort(double[] arr, int start, int end, int size) {
if (size > 10) {
int weirdStart = (size / 3) - 1;
int weirdEnd = (end - weirdStart) - 1;
int weirdSize = (weirdEnd - start + 1);
weirdSort(arr, start, weirdEnd, weirdSize);
weirdSort(arr, weirdStart, end, weirdSize);
weirdSort(arr, start, weirdEnd, weirdSize);
}
else
bubbleSort(arr, start, end);
} // end of method
private static void bubbleSort(double arr[], int start, int end) {
int size = end - start + 1;
boolean noSwaps;
for (int i = start; i < size; i++) {
noSwaps = true;
for (int j = start + 1; j < size - i; j++) {
if (arr[j - 1] > arr[j]) {
swap(arr, j, j - 1);
noSwaps = false;
} // end of condition
} // end of (j) for loop
if (noSwaps) // If no two elements were swapped by inner loop, array is sorted
break;
} // end of (i) for loop
} // end of method
The problem is that it only sorts the array up to 2/3 of the first elements, the last 1/3 are unsorted (bubbleSort by itself works fine). I would really like to solve this on my own but I'm stuck, so I would apreciate any thoughts or suggestions on the matter but not a full solution.
After calling weirdSort for all the 3 parts, those parts will be sorted but it has to be arranged so that the whole array is sorted, just like in a mergesort. So after calling the weirdSort, you have to run a loop and convert those 3 independent sorted arrays into a single sorted array.
Your interpolation is wrong. Take an example,
weirdSort([...], 0, 11, 12):
weirdStart = 12 / 3 - 1 = 3
weirdEnd = 11 - 3 - 1 = 8
weirdSize = 8 - 0 + 1 = 9
// so far so good, but look at the second recursive call
weirdSort([...], 3, 11, 9):
weirdStart = 9 / 3 - 1 = 2 // Wrong!
// Other vars are now also wrong
You need to account for start when determining weirdStart and weirdEnd.
To get you started, you want something like,
third = (end - start + 1) / 3;
weirdStart = start + third;
weirdEnd = end - third;
In fact, don't pass size around at all, just compute it as end - start + 1.
You might want to adjust weirdStart/End by +/-1 depending on your specific needs.
recently I met a question like this:
Assume you have an int N, and you also have an int[] and each element in this array can only be used once time. And we need to design an algorithm to get 1 to N by adding those numbers and finally return the least numbers we need to add.
For example:
N = 6, array is [1,3]
1 : we already have.
2 : we need to add it to the array.
3 : we can get it by doing 1 + 2.
4: 1 + 3.
5 : 2 + 3.
6 : 1 + 2 + 3.
So we just need to add 2 to our array and finally we return 1.
I am thinking of solving this by using DFS.
Do you have some better solutions? Thanks!
Here's an explanation for why the solution the OP posted works (the algorithm, briefly, is to traverse the sorted existing elements, keep an accumulating sum of the preceding existing elements and add an element to the array and sum if it does not exist and exceeds the current sum):
The loop tests in order each element that must be formed and sums the preceding elements. It alerts us if there is an element needed that's greater than the current sum. If you think about it, it's really simple! How could we make the element when we've already used all the preceding elements, which is what the sum represents!
In contrast, how do we know that all the intermediate elements will be able to be formed when the sum is larger than the current element? For example, consider n = 7, a = {}:
The function adds {1,2,4...}
So we are up to 4 and we know 1,2,3,4 are covered,
each can be formed from equal or lower numbers in the array.
At any point, m, in the traversal, we know for sure that
X0 + X1 ... + Xm make the largest number we can make, call it Y.
But we also know that we can make 1,2,3...Xm
Therefore, we can make Y-1, Y-2, Y-3...Y-Xm
(In this example: Xm = 4; Y = 1+2+4 = 7; Y-1 = 6; Y-2 = 5)
Q.E.D.
I don't know if this is a good solution or not:
I would create a second array (boolean array) remembering all numbers I can calculate.
Then I would write a method simulating the adding of a number to the array. (In your example the 1, 3 and 2 are added to the array).
The boolean array will be updated to always remember which values (numbers) can be calculated with the added numbers.
After calling the add method on the initial array values, you test for every Number x ( 1 <= x <= N ) if x can be calculated. If not call the add method for x.
since my explanation is no good I will add (untested) Java code:
static int[] arr = {3,5};
static int N = 20;
//An Array remembering which values can be calculated so far
static boolean[] canCalculate = new boolean[N];
//Calculate how many numbers must be added to the array ( Runtime O(N^2) )
public static int method(){
//Preperation (adding every given Number in the array)
for(int i=0; i<arr.length; i++){
addNumber(arr[i]);
}
//The number of elements added to the initial array
int result = 0;
//Adding (and counting) the missing numbers (Runtime O(N^2) )
for(int i=1; i<=N; i++){
if( !canCalculate[i-1] ){
addNumber(i);
result++;
}
}
return result;
}
//This Method is called whenever a new number is added to your array
//runtime O(N)
public static void addNumber( int number ){
System.out.println("Add Number: "+(number));
boolean[] newarray = new boolean[N];
newarray[number-1] = true;
//Test which values can be calculated after adding this number
//And update the array
for(int i=1; i<=N; i++){
if( canCalculate[i-1] ){
newarray[i-1] = true;
if( i + number <= N ){
newarray[i+number-1] = true;
}
}
}
canCalculate = newarray;
}
Edit: Tested the code and changed some errors (but rachel's solution seems to be better anyway)
It is a famous problem from dynamic programming. You can refer to complete solution here https://www.youtube.com/watch?v=s6FhG--P7z0
I just found a possible solution like this
public static int getNum(int n, int[] a) {
ArrayList<Integer> output = new ArrayList<Integer>();
Arrays.sort(a);
int sum = 0;
int i = 0;
while(true) {
if (i >= a.length || a[i] > sum + 1) {
output.add(sum + 1);
sum += sum + 1;
} else {
sum += a[i];
i++;
}
if (sum >= n) {
break;
}
}
return output.size();
};
And I test some cases and it looks correct.
But the one who write this didn't give us any hints and I am really confused with this one. Can anybody come up with some explanations ? Thanks!
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);
}
I need to randomly generate an array with 7 slots in Java. All these slots must have a value of at LEAST 1, but combined, have a total value of another defined number. They also all need to be an int value, no 1.5 or 0.9816465684646 numbers.
Example:
int a=10;
int[] ar = new int[7]
ar[0] = 1
ar[1] = 1
ar[2] = 2
ar[3] = 2
ar[4] = 1
ar[5] = 2
ar[6] = 1
I want it to generate something like that, but if int a=15, all the numbers would total 15 in any order
The standard way to generate N random numbers that add to a given sum is to think of your sum as a number line, generate N-1 random points on the line, sort them, then use the differences between the points as your final values. To get the minimum 1, start by subtracting N from your sum, run the algorithm given, then add 1 back to each segment.
public class Rand {
public static void main(String[] args) {
int count = 8;
int sum = 100;
java.util.Random g = new java.util.Random();
int vals[] = new int[count];
sum -= count;
for (int i = 0; i < count-1; ++i) {
vals[i] = g.nextInt(sum);
}
vals[count-1] = sum;
java.util.Arrays.sort(vals);
for (int i = count-1; i > 0; --i) {
vals[i] -= vals[i-1];
}
for (int i = 0; i < count; ++i) { ++vals[i]; }
for (int i = 0; i < count; ++i) {
System.out.printf("%4d", vals[i]);
}
System.out.printf("\n");
}
}
A good way to achieve uniformity is, for example, to fill up a = 15 units into an 8 element array:
Put 1 in each element in the array as this is your requirement, you have now 7 values left to distribute
Roll a random number between 0 and the max index of the array, and add 1 to that element, and subtract 1 from 7. Do this until 7 goes down to zero.
In this way, you'll meet your minimum conditions by having each element have minimum value 1. Then you distribute the remaining totals in a completely random way.
Adding on to what #Kon said, you could use two random numbers rather than one for more randomness. That is:
Fill every element in the array with the value 1
valuesToDistribute = a - array.length-1
randomIndex = Roll a number between 0 and array.length-1
randomValue = Roll a number between 1 and valuesToDistribute
Add to randomIndex the value randomValue
Subtract randomValue from valuesToDistribute
Repeat until valuesToDistribute = 0
My java is horrible, so I'm not providing the actual code here, as it would probably be wrong. I've done this exact thing in SQL before though, so I know it works...
Let Y be the Total value you want the elements to add up to
Begin a loop with variable Z going from 1 to X where X is the number elements in your array (here called AR)
In the loop, set AR(Z) to a random number between 1 and Y-X+Z
Subtract the new value from Y, so Y = Y - AR(Z)
End loop : back to step 2, advancing Z by 1