Sequence of loops making indefinite program - java

I am trying to make a program that takes all the combinations of a dice (got that part done) but now I am trying to take all the combinations and put them in an array by there total ( (1,1) = 2, (2,4) = 6 ) and I will eventually implement it into a game. But when trying to organize them I created an infinite loop that does not seem like it should be running infinitely.
for (int dice1 = 1; dice1 < 7; dice1++)
for (int dice2 = 1; dice2 < 7; dice2++)
for (int j = 0; j < 6;)
{
msg = "";
msg = "(" +dice1 + ", " + dice2 + ")";
arrayDice[dice1 - 1][dice2 - 1] = msg;
add = dice1 + dice2 - 2;
arrayAdd[add][j] = msg;
if (add == 10 - j)
j = j + 1;
}
the arrayDice is just the array of all combinations while the arrayAdd is all the added combinations. I really can't find where the problem is coming from.

Third for loop in your program is the one that is running infinitely. In the third loop, you are not incrementing the counter 'j' within the for statement but you increment it within the body of the loop. However, the only place in the body of the third loop where the counter 'j' is increasing is within an if statement - if (add == 10 - j). Since you start this loop with j=0, the expression 10 - 0 = 10 for the first iteration while the variable 'add' is 1 + 1 -2 = 0. So this expression if (add == 10 - j) evaluates to false. So j never gets incremented. The only other variable in this expression is 'add' which doesn't get changed until you come out of the third loop. So in short the expression if (add == 10 - j) never evaluates to true and hence j is never incremented resulting in the third loop running infinitely.

Related

Why wont console print values of i under 2 in FOR loop if it can print values over 2?

Basically what my title says. Here's a piece of code
for (int i = 9; i >= 2; i--) {
system.out.println(i + " ");
}
this prints all values until 2, hence suggesting that starting from 9 and provided it doesn't go lower than 2, i should be printed. which it does.
now this one doesn't
for (int i = 9; i <= 2; i--) {
system.out.println(i + " ");
}
what i figure is it should count down to 2 without printing anything, then print 2 and 1, since the criteria is for all values equal or under 2, print i. However nothing shows on the console.
my understanding of the FOR loop might be wrong and i'm really trying to perfect my knowledge of basic concepts so id appreciate your help.
The basic concept is :
first loop => i=9, check if 9 >=2 = true , print 9 , i = i - 1
second loop => i=8, check if 8 >=2 = true , print 8 , i = i - 1
.
.
.
last loop=> i=1, check if 1 >=2 = false , end
in your second example
first loop => i=9, check if 9 <=2 = false , end
Hope i help you understand the for loop
Loop is only executed if the condition is true. If it is false, then loop will never be executed.
If you wanted to count down from 9 and only print 2 and 1, you'd have to write something like this:
for (int i = 9; i >= 1; --i) {
if (i <= 2) {
System.out.print(i + " ");
}
}
Of course, if all you wanted was to print 2 and 1, you'd normally just write:
for (int i = 2; i >= 2; --i) {
System.out.print(i + " ");
}
You wouldn't typically start the count at 9 unless you wanted to do something with the numbers 9 to 3 (other than ignore them, that is) as well as 2 and 1:
for (int i = 9; i >= 1; --i) {
if (i <= 2) {
System.out.print(i + " ");
} else {
System.out.println("We're not going to print " + i);
}
}

how many times will this loop execute

I was just wondering how many times a nested loop like this would run
int sum = 0;
for(int i = 0; i < total; i++) {
for(int j = i + 1; j < total; j++) {
for(int k = j; k < total; k++) {
sum++;
}
}
}
System.out.println(sum);
I can easily see the output of sum, but I would like to be able to mathematically calculate the total of sum with any number for total.
TL;DR
The loop will be executed for ((total ^ 3) - total) / 6 times and hence that will be the value of sum at the end of the loop.
int sum = 0;
for(int i = 0; i < total; i++) {
for(int j = i + 1; j < total; j++) {
for(int k = j; k < total; k++) {
sum++;
}
}
}
It is easy to see that the outer loop runs for a total times. The second loop is the trickier one
Let's try to work this out
i = 0, j runs from 1..total - 1
i = 1, j runs from 2..total - 1
i = 2, j runs from 3..total - 1
...
i = total - 2, j runs from total - 1 ..total - 1 (will only run once)
i = total - 1, inner loop does not execute as the loop termination condition is true.
The third loop is dependent on the second inner loop - k runs from j..total - 1
Let us take total as 6
j runs from 1..5 -> k runs for 5 times (j = 1) + 4 times(j = 2) + 3 times(j = 3)+ 2 times(j = 4) + 1 time(j = 4)
(Showing a minified version for others)
2..5 -> 4+3+2+1
3..5 3+2+1
4..5 2+1
5..5 1
Which is
1 + 2 + 3 + 4 + 5+
1 + 2 + 3 + 4 +
1 + 2 + 3 +
1 + 2 +
1
Generally,
1 + 2 + 3 + .. n +
1 + 2 + 3 +..n - 1+
1 + 2 + 3 +..n - 2+
1 + 2 + 3 +
1 + 2 +
1
This boils down to the sum
n * (n - 1)) / 2
For all values of n ranging from 1 to total
This can be verified with the below
int res = 0;
for (int i = 1; i <= total; i++) {
res += (i * (i - 1))/2;
}
res will be equal to your sum.
Mathematically, the above is
((total ^ 3) - total) / 6
Derivation:
References:
Sums of the First n Natural Numbers
Sum of the Squares of the First n Natural Numbers
The first iteration of the middle loop adds
total-1 + total-2 + ... + 1
to the sum.
The second iteration of the middle loop adds
total-2 + total - 3 + ... + 1
to the sum
The last iteration of the middle loop adds
1
to the sum.
If you sum all of these terms, you get
(total - 1) * 1 + (total - 2) * 2 + (total - 3) * 3 + ... + 2 * (total - 2) + 1 * (total - 1)
It's been a while since I studied math, so I don't remember if there's a simpler formula for this expression.
For example, if total is 10, you get:
9 * 1 + 8 * 2 + 7 * 3 + 6 * 4 + 5 * 5 + 4 * 6 + 3 * 7 + 2 * 8 + 1 * 9 =
9 + 16 + 21 + 24 + 25 + 24 + 21 + 16 + 9 =
165
It needs only a little bit knowledge of programming.Actually logic that is running behind is only computational kind of thing.
let's say:
total=10,sum=0
- when i is 0:
That time j is initialised with 1(i+1) and k as well. So k will lead us to execute the loop 9 times and and as j is incremented ,it will lead us to execute sum statement 8 times and 7 times and further 6 times till 1 time. (9+8+7+6+5+4+3+2+1=45 times.)
- when i is 1:
That time j is initialised with 2 and k as well.So sum statement is going to execute 8 times and then 7 times and then 6 times till 1.
(8+7+6+5+4+3+2+1=36 times).
- when i is 2:
Same thing happens repeatedly but starting with difference number ,so this time (7+6+5+4+3+2+1=28)
So this sequence continues until there is significance of occuring the condition with trueness.
This happens till i is 9.
So the final answer is 1+3+6+10+15+21+28+36+45=165.
The equation is like below
and the k is equal to total :
outermost loop runs 'total' number of times.
for each outer loop , middle loop runs 'total-i' times.
i.e total * total+total * (total-1)+total * (total-2)....total * 1
= total*(total+total-1+total-2...1)
= total*(1+2+3....total)
= total*(sum of first 'total' natural numbers)
= total*(total*(total+1)/2)
now the innermost loop also runs 'total-j' times for each middle loop
i.e
total*(total*(total+1)/2)*(total+(total-1)+(total-2)....+1)
= total*(total*(total+1)/2)*(1+2+3....+total)
= total*(total*(total+1)/2)* (sum of first 'total' natural numbers)
= total*(total*(total+1)/2) * (total*(total+1)/2)..
So finally you will get something close to
total * (total*(total+1)/2) * (total*(total+1)/2).
Sorry there's a correction as #andreas mentioned innermost and middle loops run only till total-i-1 times
in which case it will be the sum of first (total-1) no.s which should be (total-1)*total/2 so the final output should be
total * (total*(total-1)/2) * (total*(total-1)/2) .
As we know, the sum of an arithmetic progression is:
The inner-most loop will loop for
times, which is a function to j.
You sum it up and get a function to i, aka:
You sum it up again and get a function to total, aka:
For Mathematica users, the result is:
f[x_]:=Sum[Sum[x-j,{j,i+1,x-1}],{i,0,x-1}]
From here, we can see it more clearly, and the FINAL result is:
where x is total.
That function will loop (total/6)*(total*total - 1) times
The snippet bellow just verifies that
var total = 100
var sum = 0;
for(var i = 0; i < total; i++) {
for(var j = i + 1; j < total; j++) {
for(var k = j; k < total; k++) {
sum++;
}
}
}
function calc(n) {
return n*(n-1)*(n+1)/6
}
console.log("sum: "+sum)
console.log("calc: "+calc(total))
If we run this loop 100 times and generate a data set, then graph it, we get this:
Now, this graph is clearly a cubic. So we can do a solve using the cubic equation of ax^3+bx^2+cx+d.
Using 4 points, the values of them all are:
So the full equation is
y=x^3/6-x/6
y=x(x^2/6-1/6)
y=(x/6)(x^2-1)
Interactive Graph:
<iframe src="https://www.desmos.com/calculator/61whd83djd?embed" width="500px" height="500px" style="border: 1px solid #ccc" frameborder=0></iframe>
A simple loop like this:
for (i = a; i < b; i ++) {
....
}
runs b-a iterations (i takes the values: a, a+1, a+2... b-2, b-1) if a < b and 0 iterations otherwise. We will assume below that a < b always.
Its number of iterations can be compute using the simple maths formula:
Applying the formula to your code
We start with the innermost loop:
for(int k = j; k < t; k++) {
sum++;
}
Its number of iterations is:
Using the formula above, the value of U is (t-1)-j+1 which means:
U = t - j
Adding the middle loop
Adding the middle loop, the number of iterations becomes:
The terms of the second sum are t-(i+1), t-(i+2), ... t-(t-2), t-(t-1).
By solving the parentheses and putting them in the reverse order they can be written as:
1, 2, ... t-i-2, t-i-1.
Let p = t - j. The second sum now becomes:
It is the sum of the first t-i-1 natural numbers and its value is:
Adding the outer loop
Adding the outer loop the sum becomes:
On the last sum, the expression (t - i) starts with t (when i = 0), continues with t-1 (when i = 1) and it keeps decreasing until it reaches 1 (when i = t - 1). By replacing q = t - i, the last sum becomes:
The last expression subtracts the sum of the first n natural numbers from the sum of the first n square numbers. Its value is:
Now it's easy to simplify the expression:
The final answer
The number of iterations of the posted code is:

Magic square code loop

This is the code for a method which creates a magic square. n is the length of the square. It has to look like:
static int[][] magicSquare(int n) {
int[][] square=new int[n][n];
I don't understand this k=(k+1)%n; especially, why is it %n ?? Doesn´t that put k to 1 every loop again?
for (int i=0; i<n; i++){
in k=i;
for (int j=0; j<n; j++){
square[i][j]=k+1;
k=(k+1)%n;
1 2 3 4
2 3 4 1
3 4 1 2
4 1 2 3
The % in Java is used for modular division. Whenever the operator is applied the right-hand operand will be subtracted as many times as it can from the left-hand operand and what's left will be the output. You can easily check it by dividing the left-hand operand by the right-hand operand and take the leftover as an integer. In the case of a%b it will be like
a - (a/b)*b.
here are some examples:
10 % 4 = 2 // 2*4 = 8 + 2 = 10
10 % 5 = 0 // 2*5 = 10 + 0 = 10
0 % 4 = 0 // result here is 0 thus 0*4 = 0 + 0 = 0
// if you try to extract 4 from 0, you will not succeed and what's left will be returned (which was originally 0 and it's still 0)...
In your case:
k = (k + 1) % n;
is assuring that the value of k will never exceed 4, thus if it is dividable by 4 then it will be divided and the leftover will be written there. In the case when k is exactly 4 you will have the value of 0 written down into k but since you are always adding k + 1 it is writing the value of 1.
For beginners I do recommend to print the values you are interested in and observe how do the data migrate. Here I've added some printlns for you just to get the idea. Run the code and test it yourself. I do believe the things are going to be a bit cleaner.
public static void main(String[] args) {
int n = 4;
int[][] square = new int[n][n];
System.out.println("--------------");
for (int i = 0; i < n; i++) {
int k = i;
System.out.println("Filling magic cube line " + (i + 1) + ". The k variable will start from " + i + "."); // i initial value is 0 so we add 1 to it just to get the proper line number.
for (int j = 0; j < n; j++) {
System.out.println("Filling array index [" + i + "][" + j + "] = " + (k + 1)); // array indexes start from 0 aways and end at array.length - 1, so in case of n = 4, last index in array is 3.
square[i][j] = k + 1; // add 1 to k so the value will be normalized (no 0 entry and last entry should be equal to n).
k = (k + 1) % n; // reset k if it exceeds n value.
}
System.out.println("--------------");
}
Arrays.stream(square).forEach(innerArray -> {
Arrays.stream(innerArray).forEach(System.out::print);
System.out.println();
});
}
You could always play around and refactor the code as follows:
public static void main(String[] args) {
int n = 4;
int[][] square = new int[n][n];
System.out.println("--------------");
for (int i = 1; i <= n; i++) {
int k = i;
System.out.println("Filling magic cube line " + i + ". The k variable will start from " + i + ".");
for (int j = 0; j < n; j++) {
System.out.println("Filling array index [" + (i - 1) + "][" + (j - 1) + "] = " + k); // array indexes start from 0 aways and end at array.length - 1, so in case of n = 4, last index in array is 3. Subtract both i and j with 1 to get the proper array indexes.
square[i - 1][j - 1] = k;
k = (k + 1) % n; // reset k if it exceeds n value.
}
System.out.println("--------------");
}
Arrays.stream(square).forEach(innerArray -> {
Arrays.stream(innerArray).forEach(System.out::print);
System.out.println();
});
}
Remember that the array's indexing starts from 0 and ends at length - 1. In the case of 4, the first index is 0 and the last one is 3. Here is the diff of two implementations, try to see how does the indexes and values depends both on the control variables i and j.
https://www.diffchecker.com/x5lIWi4A
In the first case i and j both start from 0 and are growing till they it's values are both less than n, and in the second example they start from 1 and are growing till they are equal to n. I hope it's getting clearer now. Cheers

Array value post-increment

I've been working on a few array examples. with some success along alone the way. I've been working on this code for the pass few days and just cant understand the purpose of this increment in the loop body. it usually makes since when it is isolated but this time i have no idea what it does.
Count the occurrences of integers between 1 and 10
Scanner input = new Scanner(System.in);
int[] count = new int[10];
System.out.println("Enter the integers between 1 and 10: ");
// Read all numbers
// 2 5 6 5 4 3 9 7 2 0
for (int i = 0; i < count.length; i++)
{
int number = input.nextInt();
count[number]++; //this is the one that perplexes me the most
}
//Display result
for (int i = 0; i < 10; i++)
{
if (count[i] > 0)
{
System.out.println(i + " occurs " + count[i]
+ ((count[i] == 1) ? " time" : " times"));
}
}
count[number]++; //this is the one that perplexes me the most
It increments the value in the array count at index number. Perhaps, splitting it may help understand:
int tmp = count[number];
tmp = tmp + 1;
count[number] = tmp;
i.e. The value of count[number] will be incremented after the execution of the the statement count[number]++;.
Also a note on how post-increment works.
If it were used as:
int value = count[number]++;
then value will have the old value at count[number] and the increment will be done after the execution of the statement.

Need explanation for the output of the following java code

public class Test {
public static void main (String args[]) {
int i = 0;
for (i = 0; i < 10; i++);
System.out.println(i + 4);
}
}
The output of the following code is 14.Why it is not 4?
And how can it be 14? Need some explanation
Thank you in advance...
for (i = 0; i < 10; i++);
This loop does nothing but incrementing i by one, 10 times .
Then
System.out.println(i + 4);
evaluates to
System.out.println(10 + 4);
// output
14
If you drop the semi colon at the end of for (i = 0; i < 10; i++);, you shall get
4
5
6
7
8
9
10
11
12
13
as an output.
Simple.
The loop increments i by 10 without doing anything else (notice the ; after the for loop definition)
The System.out statement prints i + 4 outside the loop (only once), i.e. 14
See description in comments:
// Declare variable 'i' of type int and initiate it to 0
// 'i' value at this point 0;
int i = 0;
// Take variable 'i' and while it's less then 10 increment it by 1
// 'i' value after this point 10;
for (i = 0; i < 10; i++);
// Output to console the result of the above computation
// 'i' value after this point 14;
System.out.println(i + 4);
System.out.println(i + 4); will get evaluated and executed after for (i = 0; i < 10; i++); statement is evaluated.
Result of for (i = 0; i < 10; i++); will be 10. The condition i < 10 will be true till i=9 which is the 10th iteration and in the 11th iteration i will be 10 as i++ will be computed and here the i<10 condition fails. Now final value of i will be 10.
The next statement System.out.println(i + 4); is evaluated which is i(=10)+4 = 14

Categories

Resources