Magic square code loop - java

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

Related

programming puzzle : how to count number of bacteria that are alive?

Recently, I had encountered an interesting programming puzzle which had some good twist and turn mentioned in the puzzle. Below the question which amazed me, I simply eager to know if any relevant solution probably in java is feasible for below scenario.
Problem statement:
There is a grid of dimension m*n, initially, a bacterium is present at the bottom left cell(m-1,0) of the grid with all the other cells empty. After every second, each bacteria in the grid divides itself and increases the bacteria count int the adjacent(horizontal,vertical and diagonal) cells by 1 and dies.
How many bacteria are present at the bottom right cell(m-1,n-1) after n-1 seconds?
I had taken references from
https://www.codechef.com/problems/BGH17
but failed to submit the solution
Below is the image for more insite of problem
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.Stack;
public class BacteriaProblem {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Number of Rows: ");
int m = sc.nextInt();
System.out.println("Number of Columns: ");
int n = sc.nextInt();
int[][] input = new int[m][n];
input[m - 1][0] = 1;
Stack<String> stack = new Stack<>();
stack.push(m - 1 + "~" + 0);
reproduce(stack, input, n - 1);
System.out.println("Value at Bottom Right corner after n-1 secs: " + input[m - 1][n - 1]);
}
private static void reproduce(Stack<String> stack, int[][] input, int times) {
//exit condition
if (times < 1) {
return;
}
//bacteria after splitting
List<String> children = new ArrayList<>();
//reproduce all existing bacteria
while (!stack.isEmpty()) {
String[] coordinates = stack.pop().split("~");
int x = Integer.parseInt(coordinates[0]);
int y = Integer.parseInt(coordinates[1]);
for (int i = -1; i <= 1; i++) {
for (int j = -1; j <= 1; j++) {
if (i == 0 && j == 0) continue;
split(input, x + i, y + j, children);
}
}
input[x][y]--;
}
//add all children to stack
for (String coord : children) {
stack.push(coord);
}
//reduce times by 1
reproduce(stack, input, times - 1);
}
private static void split(int[][] input, int x, int y, List<String> children) {
int m = input.length;
int n = input[0].length;
if (x >= 0 && x < m && y >= 0 && y < n) {
input[x][y]++;
children.add(x + "~" + y);
}
}
}
Well, I was asked this question in an Online Hackerrank test and couldn't solve it at that time.
I did later try to code it and here's the soln in C++,
long countBacteriasAtBottomRight(int m, int n){
long grid[m][n];
// Set all to 0, and only bottom left to 1
for (int i=0; i<m; i++){
for (int j=0; j<n; j++){
grid[i][j] = 0;
}
}
grid[m-1][0] = 1;
// Start the cycle, do it for (n-1) times
int time = n-1;
vector<long> toBeUpdated;
while (time--){
cout << "\n\nTime: " << time;
for (int i=0; i<m; i++){
for (int j=0; j<n; j++){
while (grid[i][j] > 0){
grid[i][j]--;
// upper left
if (i > 0 && j > 0){
toBeUpdated.push_back(i-1);
toBeUpdated.push_back(j-1);
}
// upper
if (i > 0){
toBeUpdated.push_back(i-1);
toBeUpdated.push_back(j);
}
// upper right
if (i > 0 && j < n-1){
toBeUpdated.push_back(i-1);
toBeUpdated.push_back(j+1);
}
// left
if (j > 0){
toBeUpdated.push_back(i);
toBeUpdated.push_back(j-1);
}
// bottom left
if (i < m-1 && j > 0){
toBeUpdated.push_back(i+1);
toBeUpdated.push_back(j-1);
}
// bottom
if (i < m-1){
toBeUpdated.push_back(i+1);
toBeUpdated.push_back(j);
}
// bottom right
if (i < m-1 && j < n-1){
toBeUpdated.push_back(i+1);
toBeUpdated.push_back(j+1);
}
// right
if (j < n-1){
toBeUpdated.push_back(i);
toBeUpdated.push_back(j+1);
}
};
}
}
// Update all other cells
for (int k=0; k<toBeUpdated.size(); k+=2){
grid[toBeUpdated[k]][toBeUpdated[k+1]]++;
}
for (int i=0; i<m; i++){
cout << endl;
for (int j=0; j<n; j++)
cout << grid[i][j] << " ";
}
// Clear the temp vector
toBeUpdated.clear();
};
return grid[m-1][n-1];
}
The starting situation only has a value in the left-most column 0. We need to know the situation in the right-most column n-1 after time n-1. This means that we only have to look at each column once: column x at time x. What happens to column x after time x is no longer important. So we go from left to right, adding up the cells from the previous column:
1
1 8
1 7 35
1 6 27 104
1 5 20 70 230
1 4 14 44 133 392
1 3 9 25 69 189 518
1 2 5 12 30 76 196 512
1 1 2 4 9 21 51 127 323 ...
You will also notice that the result for the last cell is only influenced by two cells in the previous column, and three in the one before that, so to calculate the end result for e.g. the case n=9, you only need to calculate the values in this triangle:
1
1 4 14
1 3 9 25 69
1 2 5 12 30 76 196
1 1 2 4 9 21 51 127 323
However high the grid is, we only ever have to go up n/2 (rounded up) rows. So the total number of sums we have to calculate is n2/4, or n×m if m < n/2.
Also note that we don't have to store all these values at once, because we go column by column from left to right. So we only need a one-dimensional array of size n/2, and the current values in it are transformed like this (e.g. going from column 4 to 5 in the example above):
[4, 5, 3, 1] (0) -> 0 + 5 - 0 = 5
[9, 5, 3, 1] (5) -> 9 + 3 - 5 = 7
[9,12, 3, 1] (7) -> 12 + 1 - 7 = 6
[9,12, 9, 1] (6) -> 9 + 0 - 6 = 3
[9,12, 9, 4] (3) -> 4 + 0 - 3 = 1
[9,12, 9, 4, 1] (1) (additional value is always 1)
where we iterate over the values from left to right, add up the value to the left and right of the current element, subtract a temporary variable which is initialized to 0, store the result in a temporary variable, and add it to the current element.
So the theoretical time complexity is O(n2) or O(n.m) and the space complexity is O(n) or O(m), whichever is smaller. In real terms, the number of steps is n2/4 and the required space is n/2.
I don't speak Java, but here's a simple JavaScript code snippet which should easily translate:
function bacteria(m, n) {
var sum = [1];
for (var col = 1; col < n; col++) {
var temp = 0;
var height = Math.min(col + 1, n - col, m);
if (height > sum.length) sum.push(0);
for (var row = 0; row < height; row++) {
var left = row > 0 ? sum[row - 1] : 0;
var right = row < sum.length - 1 ? sum[row + 1] : 0;
temp = left + right - temp;
sum[row] += temp;
}
}
return sum[0];
}
document.write(bacteria(9, 9));

i want to find sum of array first and last element and 2nd and 2nd last element and 3rd and 3rd last element and so on

here remember array size and values is defined by user by the help of scanner class and i am using java
task is to find sum of first and last element and 2nd and 2nd last and so on
i already try research but failed
thanks in advance
int sum = 0;
int f = 0;
System.out.println("Your Array is even");
System.out.println("Kinldy enter Your Values of Array");
for(int i = 0 ; i<array.length ; i++)
{
array[i] = s.nextInt();
for(int j = 0 ; j< array.length-i-1 ; j++)
{
sum = j + array.length+1 ;
}
}
System.out.println("Your Sum " + sum);
You could just loop over your array and use the index to find the corresponding numbers from both sides.
The first element can be found by simply doing: array[i].
The corresponding element from the other side can be found by: array[array.length - 1 - i].
The complete code could be something like this:
public static void main(String[] args) {
int[] array = {1, 3, 6, 4, 1, 8};
for(int i = 0; i < array.length / 2; i++)
{
int firstNumber = array[i];
int secondNumber = array[array.length - 1 - i];
int sum = firstNumber + secondNumber;
System.out.println(firstNumber + " + " + secondNumber + " = " + sum);
}
}
Output:
1 + 8 = 9
3 + 1 = 4
6 + 4 = 10
I made the assumption that you only want to do this for half of the array. That's why the for loop is only executed as long as i<array.length / 2. This solution assumes that the length of your array is always an even number. If your array has an uneven length, the middle element will not be considered.
In case you do want to do this for the complete array, all you have to do is remove the / 2 from the for loop statement. The output will be:
1 + 8 = 9
3 + 1 = 4
6 + 4 = 10
4 + 6 = 10
1 + 3 = 4
8 + 1 = 9

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:

How can we find the sum for each subset of array

I am trying to finding the sum of each in the below code in java.What changes should i have to made in this code.
import java.io.IOException;
class as {
static void printSubsets(int set[]) {
int n = set.length;
for (int i = 0; i < (1 << n); i++) {
for (int j = 0; j < n; j++) {
if ((i & (1 << j)) > 0) {
System.out.print(set[j] + " ");
}
}
System.out.println();
}
}
public static void main(String[] args) {
int set[] = { 1, 2, 3 };
printSubsets(set);
}
}
Output of above code is:
1
2
1 2
3
1 3
2 3
1 2 3
I want To Multiply each element of subset by its last number for e.g.
1*1=1
2*2=4
1*2+2*2=6
3*3=9
likewise all elements
and lastly generate sum of all these subset 1+4+6+9+.. and so on.
Above code also print null set and subset are in order.How this program can be edited to make changes such that it does'nt print null set and print random substring.
As far as I understand your question, you want to multiply all the elements with each other and print out each step of iteration with the result. Here you are:
static void printSubsets(int set[]) {
int sum = 0;
for (int i=0; i<set.length; i++) {
for (int j=i; j<set.length; j++) {
int var = set[i] * set[j];
sum += var;
System.out.println("( " + set[i] + " * " + set[j] + " = " + var + " ) -> sum=" + sum);
}
}
System.out.println("final sum=" + sum);
}
In case of input [1,2,3], the sum is supposed to grow according my algorithm by:
1, 3, 6, 10, 16 up to 20
Just a note about << shift operator which shifts a bit pattern to the left. Let's say that number 2 is understood as 10 in binary. Shifting this number by 2 << 4 will result 100000 in binary that is understood as 32 in decimal. I am not sure you really need this pattern.

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.

Categories

Resources