Java for loop with discrete values - java

I need a for loop that its limit could be exceeded after one ends(one of the limits), I like to declare the limit 9 and start traversing an array to index of 8 then start from 9 and take 9 more steps and so on,until I reach the end of the array, my tries reached to this point but I wonder if it works correctly:
int [] i={9,18,27,36,45,54,63,72,81};
for(int x:i){
for(int j=0;j<x;j++)
{}
}
does the nested for loop going to change the x value after each complete cycle of the inner for loop or not?

then start from 9 and take 9 more steps
Your code doesn't behave as you want, since the inner loop always starts at 0.
There's no need to declare the i array. You can do it like this :
int start = 0;
for (int i = 9; i <= 81; i+=9) {
for (int j = start; j < i; j++) {
}
start = i;
}
Or as phflack suggested :
for (int i = 9; i <= 81; i+=9) {
for (int j = i - 9; j < i; j++) {
}
}

you can use this code:
int start = 0;
for (int i = 9; i <= 81; i+=9) {
for (int j = start; j < i; j++) {
System.out.print(j+" ");
}
System.out.println();
start = i;
//System.out.print(start+" ");
}
}
and you see:
0 1 2 3 4 5 6 7 8
9 10 11 12 13 14 15 16 17
18 19 20 21 22 23 24 25 26
27 28 29 30 31 32 33 34 35
36 37 38 39 40 41 42 43 44
45 46 47 48 49 50 51 52 53
54 55 56 57 58 59 60 61 62
63 64 65 66 67 68 69 70 71
72 73 74 75 76 77 78 79 80
Another training for you:
int start = 0;
for (int i = 1; i <= 10; i++) {
for (int j = 1; j < i; j++) {
System.out.print(j + " ");
}
System.out.println();
}
and you can see:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
1 2 3 4 5 6 7
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8 9
You can use two loop to print like matrix.

Related

Fill Matrix by a part of another Matrix java

I have a Matrix with different line size , i read it from a text file
private int set_data[][];
I have created another copy
private int set_number=set_data.length;
private int[][] set_cluster = new int[set_number][];
What i want to do is to fill set_cluster from the third row of each line
For example we have :
line one 1 3 30 49 48
line two 2 3 22 36 11 40
line three 3 5 51 44 47 15 38 40
and my goal is to store in set_cluster these numbers
line one 30 49 48
line two 22 36 11 40
line three 51 44 47 15 38 40
I have tried this code
private void fill_id_cluster() {
for (int i = 0; i < set_data.length; i++) {
set_cluster[i] = new int[set_data[i].length - 2];
for (int j = 0; j < set_data[i].length - 2; j++) {
set_cluster[i][j] = set_data[i][j + 2] ;
System.out.print(set_cluster[i][j] + " ");
}
}
}
Thanks for your help!

Retrieving arrays put in HashMap

The code below is the answer I wrote for a question that asks to rotate an n x n 2D matrix by 90 degrees (clockwise), without creating a new 2D array. So for example,
Given input matrix =
[
[1,2,3],
[4,5,6],
[7,8,9]
],
rotate the input matrix:
[
[7,4,1],
[8,5,2],
[9,6,3]
]
I tried to do it row by row, but the problem I have to deal with is what to do if the pair of index if already altered. So if I try to assign index pair [1, 2] to [0, 1], but then [0,1] is already changed before. The solution I came up with is to use a HashMap, put the index pair in an array as key, and the original number as value.
Here is my code
public void rotate(int[][] matrix) {
int n = matrix.length;
HashMap<int[], Integer> map = new HashMap<>();
for(int i = 0; i < n; i++){
for (int j = 0; j < n; j++){
if(map.containsKey(new int[]{n-j,i})){
matrix[i][j] = map.get(new int[]{n-j, i});
}
else{
int temp = matrix[i][j];
matrix[i][j] = matrix[n-j][i];
map.put(new int[]{n-j,i}, temp);
}
}
}
}
However, the result shows that
if(map.containsKey(new int[]{n-j,i})){
matrix[i][j] = map.get(new int[]{n-j, i});
}
this line of code isn't searching for the array I put in before. I know that I am creating a new array every time, but how does it make containsKey not know if the array contains same numbers(the same array)? Can anyone help me understand why using an array here to mark the pair of index isn't working in a HashMap?
You don't need a Map to rotate a matrix. You only need one temp variable.
To rotate a 3x3:
1 2 3
4 5 6
7 8 9
temp = 1, copy corner values around, then save value to next corner:
1 2 3 7 2 3 7 2 3 7 2 3 7 2 1
4 5 6 → 4 5 6 → 4 5 6 → 4 5 6 → 4 5 6
7 8 9 7 8 9 9 8 9 9 8 3 9 8 3
repeat for border values, temp = 2:
7 2 1 7 4 1 7 4 1 7 4 1 7 4 1
4 5 6 → 4 5 6 → 8 5 6 → 8 5 6 → 8 5 2
9 8 3 9 8 3 9 8 3 9 6 3 9 6 3
And you're done, in-place rotation with only 1 value in temp storage, i.e. O(1) memory footprint.
Now I'll let you actually code that, for any size matrix.
UPDATE
For the fun of it, I decided to try writing it, so here it is, with test code. I'm not going to explain the logic though, that's for you to figure out yourself.
public static void main(String... args) {
for (int size : new int[] {2,3,4,5,10}) {
int[][] matrix = createMatrix(size);
printMatrix(matrix);
System.out.println();
rotateMatrix(matrix);
printMatrix(matrix);
printSeparatorLine(matrix);
}
}
private static int[][] createMatrix(int size) {
int[][] matrix = new int[size][size];
for (int y = 0, i = 0; y < size; y++)
for (int x = 0; x < size; x++)
matrix[y][x] = ++i;
return matrix;
}
private static void rotateMatrix(int[][] matrix) {
for (int y1 = 0; y1 < matrix.length / 2; y1++) {
for (int y2 = matrix.length - y1 - 1, x1 = y1; x1 < y2; x1++) {
int x2 = matrix.length - x1 - 1, temp = matrix[y1][x1];
matrix[y1][x1] = matrix[x2][y1];
matrix[x2][y1] = matrix[y2][x2];
matrix[y2][x2] = matrix[x1][y2];
matrix[x1][y2] = temp;
}
}
}
private static void printMatrix(int[][] matrix) {
int w = maxValueWidth(matrix);
for (int[] row : matrix) {
for (int i = 0; i < row.length; i++)
System.out.printf("%" + (w + (i == 0 ? 0 : 1)) + "d", row[i]);
System.out.println();
}
}
private static void printSeparatorLine(int[][] matrix) {
char[] buf = new char[(maxValueWidth(matrix) + 1) * matrix.length - 1];
Arrays.fill(buf, '-');
System.out.println(new String(buf));
}
private static int maxValueWidth(int[][] matrix) {
return Arrays.stream(matrix).flatMapToInt(Arrays::stream).map(i -> String.valueOf(i).length()).max().getAsInt();
}
Output
1 2
3 4
3 1
4 2
---
1 2 3
4 5 6
7 8 9
7 4 1
8 5 2
9 6 3
-----
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
13 9 5 1
14 10 6 2
15 11 7 3
16 12 8 4
-----------
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
21 16 11 6 1
22 17 12 7 2
23 18 13 8 3
24 19 14 9 4
25 20 15 10 5
--------------
1 2 3 4 5 6 7 8 9 10
11 12 13 14 15 16 17 18 19 20
21 22 23 24 25 26 27 28 29 30
31 32 33 34 35 36 37 38 39 40
41 42 43 44 45 46 47 48 49 50
51 52 53 54 55 56 57 58 59 60
61 62 63 64 65 66 67 68 69 70
71 72 73 74 75 76 77 78 79 80
81 82 83 84 85 86 87 88 89 90
91 92 93 94 95 96 97 98 99 100
91 81 71 61 51 41 31 21 11 1
92 82 72 62 52 42 32 22 12 2
93 83 73 63 53 43 33 23 13 3
94 84 74 64 54 44 34 24 14 4
95 85 75 65 55 45 35 25 15 5
96 86 76 66 56 46 36 26 16 6
97 87 77 67 57 47 37 27 17 7
98 88 78 68 58 48 38 28 18 8
99 89 79 69 59 49 39 29 19 9
100 90 80 70 60 50 40 30 20 10
---------------------------------------
You said "this line of code isn't searching for the array I put in before". But you also acknowledge that you were creating a new object each time. That won't work:
Since arrays extend Object, but don't override hashCode() or equals(), you get the default implementations defined by Object. These require that the array is actually the exact same one as is being compared to - so it can't just be 'equivalent'. That is, another array of the same type, with the same elements in the same order, won't work.
Source: https://coderanch.com/t/399422/java/array-HashMap-Key
Instead, you should use a Pair object to store your coordinates. You can write your own implementation or use a pre-existing one, such as javafx.util.Pair

How to print numbers in right-aligned manner? [duplicate]

This question already has answers here:
Align printf output in Java
(5 answers)
Closed 8 years ago.
So I am trying once of the codeeval's easy problems for multiplication tables
One of the requirement is
(The numbers are right-aligned and strip out leading/trailing spaces
on each line)
I am not sure about how to do that, my current code looks like
private static void printTable(final int numberOfTables, final int numberOfTimes) {
for (int i = 1; i <= NUMBER_OF_TABLES; i++) {
final StringBuilder sb = new StringBuilder();
for (int j = 1; j <= NUMBER_OF_TIMES; j++) {
sb.append(i * j).append(" ");
}
System.out.println(sb.substring(0, sb.length() - 4));
}
}
and what I get back is
1 2 3 4 5 6 7 8 9 10 11 12
2 4 6 8 10 12 14 16 18 20 22 24
3 6 9 12 15 18 21 24 27 30 33 36
4 8 12 16 20 24 28 32 36 40 44 48
5 10 15 20 25 30 35 40 45 50 55 60
6 12 18 24 30 36 42 48 54 60 66 72
7 14 21 28 35 42 49 56 63 70 77 84
8 16 24 32 40 48 56 64 72 80 88 96
9 18 27 36 45 54 63 72 81 90 99 108
10 20 30 40 50 60 70 80 90 100 110 120
11 22 33 44 55 66 77 88 99 110 121 132
12 24 36 48 60 72 84 96 108 120 132 144
How do I right-align numbers?
As you said in your question title, you use printf(). Something like,
for (int i = 1; i <= NUMBER_OF_TABLES; i++) {
for (int j = 1; j <= NUMBER_OF_TIMES; j++) {
System.out.printf("%6d", i * j);
}
System.out.println();
}
Where 6 is the width and the Javadoc for Formatter describes width as
Width
The width is the minimum number of characters to be written to the output. For the line separator conversion, width is not applicable; if it is provided, an exception will be thrown.
And
'd' ... Formats the argument as a decimal integer.
To print a number as right aligned you could use
System.out.printf("%nd", x);
where n is minimum width and x is the integer to be print.
Now for your questions answer you could use below code
for(int i=1; i<= NUMBER_OF_TABLES; i++)
{
int j=1;
System.out.print(i*j++);
for(; j<= NUMBER_OF_TIMES; j++)
{
System.out.printf("%4d",j*i);
}
System.out.println("");
}

for increment java issue

I'm new to Java. I am trying to create a multiplication table with 12 on each side of the table, so 12 going to the right and 12 going down. On each line, we will see the two values multiple. So my plan is to use 12 very similar for statements to print each of the twelve lines. One value will increment within a loop. The issue is, the first line isn't increment my y value. So it just prints out spaced out 1s.
If you have any suggestions on my latter part of the assignment, it'd be helpful. Once I get the first line to print 12 digits, I can make 11 other for statements. But I feel like there may be a simpler way to get the rest of the statements.
public class Sixthree
{
public static void main (String[] args)
{
int x = 1;
int y = 1;
System.out.print(" ");
for ( int c= x*y; y<= 12; y++)
{
System.out.print(c + " ");
}
}
}
I want the out put to look like this to start off with.:
1 2 3 4 5 6 7 8 9 10 11 12
But the current output looks like this:
1 1 1 1 1 1 1 1 1 1 1 1 1
But I want it to eventually like this: http://math.about.com/blgrid.htm
But without the blue lines.
You are getting all 1s because the loop initialization statement int c= x*y will be executed only once for a for loop. That is it is executed the first time when x=1 and y=1 and since, it is given as the loop initialisation statement and not in the loop body, it is never reevaluated. The for loop works as :
The loop initialisation statement is executed only once at the beginning of the loop. After each iteration the loop update expression is executed and the loop condition is reevaluated. for(loop_initialisation;loop_condition;loop_update) { ... }
So you should update c inside the loop, something like :
for ( int c= x*y; y<= 12; y++)
{
c = x*y;
System.out.print(c + " ");
}
for (int i = 1; i <= 12; i++) {
for (int j = 1; j <= 12; j++){
System.out.printf ("%3d ", j * i);
}
System.out.print ("\n");
}
The above code will give you output similar to what is shown below:
1 2 3 4 5 6 7 8 9 10 11 12
2 4 6 8 10 12 14 16 18 20 22 24
3 6 9 12 15 18 21 24 27 30 33 36
4 8 12 16 20 24 28 32 36 40 44 48
5 10 15 20 25 30 35 40 45 50 55 60
6 12 18 24 30 36 42 48 54 60 66 72
7 14 21 28 35 42 49 56 63 70 77 84
8 16 24 32 40 48 56 64 72 80 88 96
9 18 27 36 45 54 63 72 81 90 99 108
10 20 30 40 50 60 70 80 90 100 110 120
11 22 33 44 55 66 77 88 99 110 121 132
12 24 36 48 60 72 84 96 108 120 132 144
You should be using two nested for loops, one to iterate over the values of x, another to iterate over the values of y with each inner loop printing the value of x * y and each outer loop printing a new line character for formatting.
// Pseudo-code //
for(each x) {
for(each y) {
print(product);
}
print(newline);
}
Why it just prints out spaced out 1s ?
It is because you just assign c only once in for-loop. for ( int c= x*y; y<= 12; y++)
When value y is incvreasing, value c is not changing. The values is 1*1=1 (x=1, y=1).
As a result, you see it just prints out spaced out 1s.
You can use nested for loop to implement it.
public class Sixteen {
public static void main(String[] args) {
int x = 12;
int y = 12;
for (int i = 1; i <= x; i++) {
for (int j = 1; j <= y; j++) {
System.out.printf("%d ", i * j);
}
System.out.println();
}
}
}
for (int x = 1; x <= 12; x++)
{
for (int y = 1; y <= 12; y++)
{
int multiply = x * y;
System.out.print(multiply + "\t");
}
System.out.println();
}

Method prints table incorrectly

I was wondering if someone could help me with a small problem I'm having.
I am trying to print out an array of 100 items, every row needs 10 items, after which it starts a new row. I have done this successfully, however, every row in every column displays the same number. For example. My output would be:
1 1 1 1 1 1 1 1 1 1
2 2 2 2 2 2 2 2 2 2
When it should be appearing as something along the lines of:
1 2 3 4 5 6 7 8 9 10
11 12 13 14 15 16 17 18 19 20
Here is the following method I am using to print the table:
public static void printTable(int[] emirps) {
for (int i = 0; i < 100; i++) {
for (int j = 0; j < 10; j++) {
// After 10 go to a new line
System.out.printf("%d\t", emirps[i]);
}
System.out.println("");
}
}
If anyone can help me pinpoint where I have goofed I'd greatly appreciate it.
You are printing the same emirps[i] each time through the inner loop. There are a couple of ways around this. Here's one:
public static void printTable(int[] emirps) {
for (int i = 0; i < 100; i += 10) {
for (int j = 0; j < 10; j++) {
// After 10 go to a new line
System.out.printf("%d\t", emirps[i + j]);
}
System.out.println();
}
}
Here's another (not very elegant):
public static void printTable(int[] emirps) {
for (int i = 0; i < 100; ++i) {
System.out.printf("%d\t", emirps[i]);
if (i % 10 == 9) {
System.out.println();
}
}
}
This looks like homework, so instead of giving you the answer, here's a hint:
For the first iteration of the first loop, i = 0. When this is the case, you increment j from 0 to 9. Note that i stays the same throughout. This is when you print your first line.
Once you're through with the second for loop, i increases by 1 to, and now i = 1. Again, you increment j from 0 to 9, and i stays at 1. This is when you print your second line.
This repeats 100 times, as i goes from 0 to 99.
There are 2 ways of approaching this:
Use one for loop, and figure out when to print an end-of-line character.
Use two for loops, each going up to 10. Figure out your index by simple multiplication and addition.
You should try and implement both methods. It'll help you understand loops better.
You are not using the j index anywhere in this code.
Here is how you should print:
System.out.printf("%d\t", emirps[i+j]);
Notice how in the print statement you are now using both the i and j indices.
Also, to get your row offset working correctly, you should be incrementing i by 10 at each step of the loop.
Alternatively, declare emirps as a 2-dimensional array. Then the signature of printTable() would be:
public static void printTable(int[][] emirps)
In that setup, here is how you would print:
System.out.printf("%d\t", emirps[i][j]);
So in the first setup, i+j together index into a 1-D array. In the second setup, i is the row and j is the column, indexing together into a 2-D array. It looks like you're doing a 1-D array but this other example is for your future reference.
Use the modulo operator. Every time your number can be divided by 10 without a remainder, you can make a new line because you have filled up the row. You obtain the remainder using the 'modulo operator' which is the percent (%) sign. It can be used like /, except that rather than the quotient being the result, the remainder of the division operation is the result.
public static void main(String[] args)
{
StringBuilder builder = new StringBuilder();
for (int i = 0; i < 100; i++)
{
if (i != 0 && i % 10 == 0)
{
builder.append('\n');
}
builder.append(i + " ");
}
System.out.println(builder.toString());
}
Prints out:
0 1 2 3 4 5 6 7 8 9
10 11 12 13 14 15 16 17 18 19
20 21 22 23 24 25 26 27 28 29
30 31 32 33 34 35 36 37 38 39
40 41 42 43 44 45 46 47 48 49
50 51 52 53 54 55 56 57 58 59
60 61 62 63 64 65 66 67 68 69
70 71 72 73 74 75 76 77 78 79
80 81 82 83 84 85 86 87 88 89
90 91 92 93 94 95 96 97 98 99

Categories