Can someone explain how this left rotating array code works? - java

I am trying to learn more about arrays and how to rotate them. I stumbled upon a code and I'm trying to figure out how it prints out the rotation correctly.
public static void main(String[] args)
{
Scanner sc = new Scanner (System.in);
int n = sc.nextInt();
int d = sc.nextInt();
int arr [] = new int [n];
for (int i = 0; i < n; i++)
{
arr [i] = sc.nextInt();
}
for (int i = 0; i < n; i++)
{
System.out.print (arr [(i + d) % n] + " ");
}
}
I have tried doing the math myself to see how it works, but it doesn't add up and I'm not sure what I'm doing wrong. The n is for the number for integers in the array and d is the number of rotations.
The equation is: (i + d) % n with n = 5, d = 4, and the array being {1,2,3,4,5}
(1 + 4) % 5 = 5 % 5 = 0
(2 + 4) % 5 = 6 % 5 = 1
(3 + 4) % 5 = 7 % 5 = 2
(4 + 4) % 5 = 8 % 5 = 3
(5 + 4) % 5 = 9 % 5 = 4
The answer that it prints out is 5 1 2 3 4 which is correct, but from what I calculated it should print out as 1 2 3 4 5. How I got this is that from the following calculations it says that 1 should go to index 0, 2 should go to index 1, etc... If you guys can help explain how the code works, that would much appreciated.

Here,
for (int i = 0; i < n; i++)
{
System.out.print (arr [(i + d) % n] + " ");
}
The array will start from 0 since in the for loop you gave i as 0. so it will start from 0 to 4.
(0 + 4) % 5 = 4 % 5 = 5
(1 + 4) % 5 = 5 % 5 = 1
(2 + 4) % 5 = 6 % 5 = 2
(3 + 4) % 5 = 7 % 5 = 3
(4 + 4) % 5 = 8 % 5 = 4

First, you collect arrays with the contents {1,2,3,4,5}, this means you have 5 indexes with details :
arr[0] = 1
arr[1] = 2
arr[2] = 3
arr[3] = 4
arr[4] = 5
Then you want each index content to be added to the value d then modulus % with the value n.
What's wrong is in your second iteration ?
for (int i = 0; i < n; i++){
System.out.print (arr [(i + d) % n] + " ");
}
If you print this (i + d)% n, it will produce this :
(0 + 4) % 5 = 4
(1 + 4) % 5 = 0
(2 + 4) % 5 = 1
(3 + 4) % 5 = 2
(4 + 4) % 5 = 3
So with this command :
System.out.print (arr [(i + d) % n] + " ");
Actually you are printing :
arr[4]
arr[0]
arr[1]
arr[2]
arr[3]
So if you want the results that you want, change the second iteration by holding the value of each index of your array with the following code:
for (int i = 0; i < n; i++){
arr[i] = (arr[i] + d) % n;
System.out.print(arr[i] + " ");
}
This will print 0 1 2 3 4
Hope this helps

Related

How to write an vertical Histogram

So, right now I managed to output the Histogram like this:
The code for this picture is as following:
int max = getBiggest(arr);
int min = getSmallest(arr);
int n = max / 50 + 1;
for (int i = 0; i < arr.length; i++) {
for (int j = min; j < arr[i]; j += n) {
System.out.print(i + 1);
}
System.out.println("(" + arr[i] + ")");
}
But my task is to output the Histogram like this:
Can someone explain me please how to write this code?
Try this.
public static void main(String[] args) {
int[] arr = {12, 28, 11, 16, 21, 12};
int length = arr.length;
int max = IntStream.of(arr).max().getAsInt();
int min = IntStream.of(arr).min().getAsInt();
System.out.println("Histgramm:");
for (int h = min; h <= max; ++h) {
for (int i = 0; i < length; i++)
System.out.print(arr[i] >= h ? (i + 1) + " " : " ");
System.out.println("(" + h + ")");
}
}
output:
Histgramm:
1 2 3 4 5 6 (11)
1 2 4 5 6 (12)
2 4 5 (13)
2 4 5 (14)
2 4 5 (15)
2 4 5 (16)
2 5 (17)
2 5 (18)
2 5 (19)
2 5 (20)
2 5 (21)
2 (22)
2 (23)
2 (24)
2 (25)
2 (26)
2 (27)
2 (28)

Non Recursive Merge Sort With 2 Array List

I'm trying non-recursive Merge Sort with 2 Arrays, But it doesn't work when given array's size is not 2^n.
It works fine when the given array's size is 2^n.
For example, given array which's size is not 2^n : 7 2 9 11 4 3 8 6 1 10
As step is 1, sort result is :
2 7 9 11 3 4 6 8 1 10
And now it will sort with 4 items, 4 items, 2 items.
But it doesn't work.
so I checked the console, and it seems like, the problem is
while(leftStart <= leftLast && rightStart <= rightLast).
As I catched, when checking 2 7 9 11 and 3 4 6 8 to sort, the leftStart is going to higher than leftLast, 2 < 7 (leftStart++), 2 < 9 (leftStart++) so leftStart > leftLast, the while loop is broken ).
It should check for the others, because it could be L1.get(leftStart) > L1.get(rightStart)
But I don't know how to solve this problem..
Thank you for your help.
public statid void main(String[] args){
ArrayList<Integer> l = new ArrayList<>();
l.add(7);
l.add(2);
l.add(9);
l.add(11);
l.add(4);
l.add(3);
l.add(8);
l.add(6);
l.add(1);
l.add(10);
sort(l);
}
public static void sort(ArrayList l) {
L1 = null;
L2 = null;
step = 1;
L1 = l;
L2 = new ArrayList<>();
for(int i = 0; i < L1.size(); i++)
L2.add(null);
int tSize = l.size();
while(step <= l.size() ) {
for(int i = 0; i < tSize; i += this.step*2) {
int leftStart = i;
int leftLast = (leftStart + this.step)-1;
if(leftLast >= tSize-1)
continue;
int rightStart = i + this.step;
int rightLast = (rightStart + this.step)-1;
if(rightStart >= tSize)
rightStart = tSize - 1;
int idx = i;
// System.out.println("step : " + step + " || idx : " + idx + " || leftStart : " + leftStart + " || rightStart : " + rightStart);
// System.out.println("step : " + step + " || idx : " + idx + " || leftEnd : " + leftLast + " || rightEnd : " + rightLast);
// System.out.println();
while(leftStart <= leftLast && rightStart <= rightLast) {
System.out.println("leftStart : " + leftStart + " || rightStart : " + rightStart + " || idx : " + idx);
Object a = L1.get(leftStart);
Object b = L1.get(rightStart);
if(comp.compare ( a, b ) < 0 ) {
L2.set(idx++, L1.get(leftStart++));
L2.set(idx, L1.get(rightStart));
}else {
System.out.println("idx :::: " + idx);
L2.set(idx++, L1.get(rightStart++));
L2.set(idx, L1.get(leftStart));
}
}
}
for(int i = 0; i < L1.size(); i++) {
L1.set(i, L2.get(i));
}
System.out.println("============================");
for(int j = 0; j < L1.size(); j++) {
System.out.print(L1.get(j) + " ");
}
System.out.println("\n============================");
step *= 2;
}
}
The result:
1 2 3 4 6 7 8 9 8 10
If an array has an odd number of items, then splitting it will result in one subarray will have one more item than the other.
[2,7,9,11,3,4,6,8,1,10]
/ \
[2,7,9,11,3] [4,6,8,1,10]
/ \ / \
[2,7,9] [11,3] [4,6,8] [1,10]
/ \ / \
[2,7] [9] [4,6] [8]
Both recursive and non-recursive merge sort have the same time complexity of O(nlog(n)).
The iterative version doesn't use recursion to split the array. Rather, it uses nested loops.

Magic Square program Java with array

I want to program a Magic Square wherein the utilization of arrays is at place but when i want to run it, it shows Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at MagicSquare.main(MagicSquare.java:6)
What should I do? It would show
4 9 2 7 1 6
3 5 7 not 3 5 7
8 1 6 4 9 2
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
int n = Integer.parseInt(args[3]);
if (n % 2 == 0) throw new RuntimeException("n must be odd");
int[][] magic = new int[n][n];
int row = n-1;
int col = n/2;
magic[row][col] = 1;
for (int i = 2; i <= n*n; i++) {
if (magic[(row + 1) % n][(col + 1) % n] == 0) {
row = (row + 1) % n;
col = (col + 1) % n;
}
else {
row = (row - 1 + n) % n;
}
magic[row][col] = i;
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (magic[i][j] < 10) System.out.print(" ");
if (magic[i][j] < 100) System.out.print(" ");
System.out.print(magic[i][j] + " ");
}
System.out.println();
}
}
What else should I add or take away from this program?
According to your program, need to provide 4 arguments when running. ex: If class name is Test:
java Test 1 1 1 3
Result:
4 9 2
3 5 7
8 1 6

numeric pyramid in java.

i need to print out a numeric pyramid using java. that counts in multiples of 2 along with the spaces like how it is below. but the code i have it only bring up multiples of 1 of no spaces.
1
1 2 1
1 2 4 2 1
1 2 4 8 4 2 1
1 2 4 8 16 8 4 2 1
1 2 4 8 16 32 16 8 4 2 1
1 2 4 8 16 32 64 32 16 8 4 2 1
this is my code.
import java.util.Scanner;
public class NumericPyramid {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
//Taking noOfRows value from the user
System.out.println("How Many Rows You Want In Your Pyramid?");
int noOfRows = sc.nextInt();
//Initializing rowCount with 1
int rowCount = 1;
System.out.println("Here Is Your Pyramid");
//Implementing the logic
for (int i = noOfRows; i > 0; i--) {
//Printing i*2 spaces at the beginning of each row
for (int j = 1; j <= i*2; j++) {
System.out.print(" ");
}
//Printing j value where j value will be from 1 to rowCount
for (int j = 1; j <= rowCount; j++) {
System.out.print(j+" ");
}
//Printing j value where j value will be from rowCount-1 to 1
for (int j = rowCount-1; j >= 1; j--) {
System.out.print(j+" ");
}
System.out.println();
//Incrementing the rowCount
rowCount++;
}
}
}
Output:
How Many Rows You Want In Your Pyramid?
7
Here Is Your Pyramid
1
1 2 1
1 2 3 2 1
1 2 3 4 3 2 1
1 2 3 4 5 4 3 2 1
1 2 3 4 5 6 5 4 3 2 1
1 2 3 4 5 6 7 6 5 4 3 2 1
For each j from 1 to n you need write 2^j. Currently you are writting only j.
So write function which for given k returns 2^k.
EDIT: For bigger n you need to use BigInteger:
import java.math.BigInteger;
public class NumericPyramid {
private static BigInteger pow(int exponent) {
BigInteger result = new BigInteger("1");
BigInteger two = new BigInteger("2");
for (int i = 0; i < exponent; i++) {
result = result.multiply(two);
}
return result;
}
and use it in both for loops. Replace
System.out.print(j+" ");
with
System.out.print(pow(j)+" ");
the pyramid goes 1 2 4 8 16, that's a sequence of 1 * 2 = 2, 2 * 2 = 4, 4 * 2 = 8 and so on, and then goes inverse, 8 / 2 = 4, 4 / 2 = 2, 2 / 2 = 1, you only need to multiply by 2 and divide by 2 when the center
for (int i = 0; i < noOfRows; i++) {
int cont = 1;
for (int j = 0; j <= i; j++) {
System.out.print(cont + " ");
cont = cont * 2;
}
cont = cont / 2;
for (int j = 0; j < i; j++) {
cont = cont / 2;
System.out.print(cont + " ");
}
System.out.println();
}

How do I read a loop that has no braces?

I'm trying to read the output of this code, but it simply just doesn't make sense to me.
Even after learning that a loop without braces only loops through the first line, the output still makes no sense, at all. Some numbers do, but others just don't.
My code:
int n = 8;
int i = 1;
int j = 1;
j = n + 2;
System.out.println (n + " " + i + " " + j );
while (n > 1)
{
n = n/2;
for (i = 2; i <= n; i = i+2)
System.out.println (n + " " + i + " " + j );
j++;
}
System.out.println (n + " " + i + " " + j );
And it outputs:
8 1 10
4 2 10
4 4 10
2 2 11
1 2 13
I get the 8-1-10
and the 4-2-10
but anything after that, I'm stumped, I don't get how the computer calculates the rest.
Would someone mind going through the rest of the output with me, step by step?
Thank's in advance.
No braces means that the loop affects only the next statement that follows the loop.
So
for (i = 2; i <= n; i = i+2)
System.out.println (n + " " + i + " " + j );
is equivalent to
for (i = 2; i <= n; i = i+2)
{
System.out.println (n + " " + i + " " + j );
}
Usually, indentation is used in those cases to make the code more comprehensible, like this:
for (i = 2; i <= n; i = i+2)
System.out.println (n + " " + i + " " + j );
EDIT: Now, this is the actual answer to the question. It all depends on the different iterations the loop does and how do the variables get incremented.
int n = 8;
int i = 1;
int j = 1;
j = n + 2; //This means that j takes the value 10.
System.out.println (n + " " + i + " " + j ); // 8 1 10 So far, so good.
Now, on with the iteration:
while (n > 1)
{
n = n/2;
for (i = 2; i <= n; i = i+2)
System.out.println (n + " " + i + " " + j );
j++;
}
For the first iteration, we have n=8 i=1 j=10, so since n > 0 is true the loop takes place.
n = n / 2; //n = 4
Then, the for (note that it just assigns the value 2 to i):
for (i = 2; i <= 4; i = i+2) //Since n = 4
Since n = 4, the only values that i can take are 2 and 4, then the prints are:
4 2 10
4 4 10
After that, j is incremented by one, making it j = 11. The condition for the while is met again because n = 4. n = n/2 makes n take the value 2, so it enters the while again. Let's take a look at the for again:
for (i = 2; i <= 2; i = i+2) //Since n = 2
This time, the only value that i can take is 2 (note that the value of i is reset again to 2 while starting the iteration), and that's the print you get.
2 2 11
Before iterating again, j++ makes j have the value 12.
On the final iteration, n = n/2 results in n = 1 since n is an int but this is done inside the while, so it enters again. Now that n = 1 the loop looks like this:
for (i = 2; i <= 1; i = i+2) //Since n = 1
i is set to 2 and the condition for the for is not met (2 <= 1 is false). Then there is no print this time, yet j is incremented to 13 at the end of the while.
In the next iteration you have n = 1, that means that the while's condition is not met so the iteration breaks. Finally you have n = 1, i = 2 and j = 13. That's the last print you get.
You start the while loop with n = 8, i = 1 and j = 10.
start while: (n=8 > 1) is true
n = 4
i = 2 (i <= 4, so do for loop, then change i to i+2=4)
print 4,2,10
i = 4 (i <= 4, so do for loop again, then i = i+2 = 6
print 4,4,10
i = 6 (i <= 4 is false, so exit for)
j++ so j becomes 11
next while:
n = n/2 = 2
i = 2 (i <= 2, so do for loop, then change i to i+2=4)
print 2,2,11
i = 4 (i <= 2 is false, so exit for)
j++ -> j = 12
next while:
n = n/2 = 1
i = 2 (i <= 1 is false, so exit loop)
j++ -> j = 13
exit while.
Final print= n = 1, i = 2 (value assigned in last for loop, loop doesn't get executed so i doesnt get incremented by 2), and j = 13
Hope this helps :)

Categories

Resources