Set large array of numbers to designated length per line - java

int size = 50;
// Generates non-duplicated random numbers
int[] values = new int[51];
int[] list = new int[size];
for( int i = 0; i < 51; i++ )
values[i] = i;
Random rand = new Random();
int listSize = 0;
int myList = 0;
while( true )
{
int value = rand.nextInt(51);
if( values[ value ] == 0 )
continue; // number already used
list[ myList++ ] = value;
values[ value ] = 0;
if( myList == size || myList == 50 )
break;
}
// Displays non-duplicated random generated numbers
for(int element : list)
System.out.print(element + " ");
I would like to set a large array of numbers to a designated length per line to make all the numbers appear as though they're in a block with the left and right sides even like so:
> 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
How do I accomplish this using an enhanced for loop? Thanks for your help!

Add a new line after read 10 value
for(int i=0; i<list.length; i++){
System.out.printf(" %-2d",list[i]); //Format left justified
if ((i+1)%10==0){
System.out.println(); // Add a new line after 10
}
}

Related

How can I print out 1-50 even numbers only, but the it start a new line every multiples of 10. (JAVA)

I'm a newbie, but I'm willing to learn how to code.
I tried using this code:
int n = 50;
int counter = 0;
System.out.print("Even Numbers from 1 to "+n+" are: ");
for (int i = 1; i <= n; i++) {
counter++;
if (counter == 2) {
System.out.println(i + " ");
counter = 0;
%10== 0
to find all even numbers between 1 to 50 and make a new line at multiples of 10 just follow these steps -
Make one loop which will go 1 to 50
Check if the number is even by checking the remainder after diving it with 2, if YES print that number.
Check if the number is a multiple of 10 by checking the remainder after dividing it by 10, if YES make a new line
The code will look something like this -
int i = 1;
while(i<=50){
if(i%2 == 0) System.out.print(i + " ");
if(i%10 == 0) System.out.println();
i++;
}
Output -
2 4 6 8 10
12 14 16 18 20
22 24 26 28 30
32 34 36 38 40
42 44 46 48 50
It's up to you which looping method you want to use for me While loop looks cleaner.
I hope this solves all your queries.
PFB Snippet:
public class Main
{
public static void main(String[] args) {
for(int i=1;i<=50;i++){
if (i%2 == 0) //Check whether number is even
{
System.out.print(i+" ");
if (i%10 == 0) // Check if it is multiple of 10
{
System.out.print("\n");
}
}
}
}
}
Output:
2 4 6 8 10
12 14 16 18 20
22 24 26 28 30
32 34 36 38 40
42 44 46 48 50
"\n" is a Escape Sequence which means new line

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!

Printing a snake pattern using an array

I'm having trouble with an assignment where we are required to print out this array:
1 10 11 20 21
2 9 12 19 22
3 8 13 18 23
4 7 14 17 24
5 6 15 16 25
My code is somewhat correct but it is not printing 10 and 19 where it should be.
My output:
Choose a number for the rows from 0 to 16.
5
Choose a number for the columns from 0 to 16
5
1 0 10 0 19
2 9 11 18 20
3 8 12 17 21
4 7 13 16 22
5 6 14 15 23
My code:
//snake move with the number
import java.util.Scanner;
public class SnakeMove {
public static void main(String[] args) {
//create Scanner object
Scanner inScan = new Scanner(System.in);
//prompt the user to choose number for the Row from 0 to 16
System.out.println("Choose a number for the rows from 0 to 16.");
//take the input from user with nextInt() method
//use the variable int row
int row = inScan.nextInt();
//prompt the user to choose number for the Col from 0 to 16
System.out.println("Choose a number for the columns from 0 to 16");
//take the input from user with nextInt()
//use the variable int col
int col = inScan.nextInt();
if (row != col) {
System.out.println("Run the program again and choose the same number for Row and Col");
System.exit(0);
}
int[][] arr = move(row, col);
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr.length; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}//main method
static int[][] move(int row, int col) {
boolean flag = true;
int count = 1;
int[][] array = new int[row][col];
for (int j = 0; j < array[0].length; j++) {
if (flag) {
for (int i = 0; i < array.length; i++) {
//assign the increment value of count
// to specific array cells
array[i][j] = count;
count++;
}
flag = false;
} else {
//row decrement going up
for (int i = array.length - 1; i > 0; i--) {
//assign the increment value of count
// to specific array cells
array[i][j] = count;
count++;
}
flag = true;
}
}//column increment
return array;
}//move method
}//end SnakeMove class
Can anyone detect what is causing the error? Any help would be appreciated.
I believe this is a good alternative and easy to understand. Do comment if you have a simplified version of the same.
Code:
import java.util.Arrays;
import java.util.Scanner;
public class SnakePatternProblem {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in); // *INPUT*
int row = scanner.nextInt();
int col = scanner.nextInt();
int[][] array = new int[row][col];
// Initializing first row of the array with a generalized expression
for (int i = 0; i < col; i++) {
if (i % 2 != 0) array[0][i] = col * (i+1);
else array[0][i] = (col * i) + 1;
}
array[0][0] = 1; // this element is not covered in the above loop.
// Nested loop for incrementing and decrementing as per the first row of elements.
for (int i= 1; i< row; i++){
for (int j=0; j< col; j++){
if(j%2==0) array[i][j] = array[i-1][j] + 1;
else array[i][j] = array[i-1][j] - 1;
}
}
System.out.println(Arrays.deepToString(array)); // *OUTPUT
}
}
Explanation:
Consider first row of 5 x 5 matrix named "arr" with snake pattern:
1 10 11 20 21
The element in the odd column is equivalent to ((currentColumn + 1) * Total_No_Of_columns);
Example: arr[0][1] = (1 + 1)* 5 = 10
The element in the even column is equivalent to (currentColumn * Total_No_Of_columns) + 1;
Example: arra[0][2] = (2 * 5) + 1 = 11;
Important Note: element at first row, first column is Zero
arr[0][0] = 1 -> must be declared
Now, the remaining matrix is incrementing or decrementing loop from the first element in that column.
Elements with even column number gets incremented by 1 in each row from the first element of that column.
1 -> First element of column-0
2 -> (1 + 1)
3 -> (2 + 1).... so on
4
5
Elements with odd column number gets decremented by 1 in each row from the first element of that column.
10 -> First element of column - 1
9 -> (10 - 1)
8 -> (9 - 1).... so on
7
6
This will generate the "snaking" pattern you described.
It could be simplified with ternary but this makes it more readable I think
It would be interesting to find a more clever way about it though, if anyone finds a better way pls comment
public static int[][] genArray(int length) {
int[][] arr = new int[length][length];
int counter = 0;
for (int col = 0; col < arr.length; col++) {
if (col % 2 == 0) {
for (int row = 0; row < arr.length; row++) {
arr[row][col] = counter++;
}
} else {
for (int row = arr.length - 1; row >= 0; row--) {
System.out.println("row: " + row + ", col: " + col);
arr[row][col] = counter++;
}
}
}
}
return arr;
}
You can create such an array as follows:
int m = 5;
int n = 4;
int[][] snakeArr = IntStream.range(0, n)
.mapToObj(i -> IntStream.range(0, m)
// even row - straight order,
// odd row - reverse order
.map(j -> (i % 2 == 0 ? j : m - j - 1) + i * m + 1)
.toArray())
.toArray(int[][]::new);
// output
Arrays.stream(snakeArr)
.map(row -> Arrays.stream(row)
.mapToObj(e -> String.format("%2d", e))
.collect(Collectors.joining(" ")))
.forEach(System.out::println);
1 2 3 4 5
10 9 8 7 6
11 12 13 14 15
20 19 18 17 16
Transposing snake array:
int[][] transposedSA = new int[m][n];
IntStream.range(0, m).forEach(i ->
IntStream.range(0, n).forEach(j ->
transposedSA[i][j] = snakeArr[j][i]));
// output
Arrays.stream(transposedSA)
.map(row -> Arrays.stream(row)
.mapToObj(e -> String.format("%2d", e))
.collect(Collectors.joining(" ")))
.forEach(System.out::println);
1 10 11 20
2 9 12 19
3 8 13 18
4 7 14 17
5 6 15 16
An easy way to do it is to create a 2-D array as shown below and then print its transpose.
1 2 3 4 5
10 9 8 7 6
11 12 13 14 15
20 19 18 17 16
21 22 23 24 25
It is a 2-D array of the dimension, LEN x LEN, where LEN = 5.
The above pattern goes like this:
The pattern starts with a start value of 1.
When the main loop counter is an even number, the counter, which assigns a value to the array, starts with start value and increases by one, LEN times. Finally, it sets start for the next row to start with final_value_of_the_array_value_assignment_counter - 1 + LEN.
When the main loop counter is an odd number, the counter, which assigns a value to the array, starts with start value and decreases by one LEN times. Finally, it sets start for the next row to start with start + 1.
The transpose of the above matrix will look like:
1 10 11 20 21
2 9 12 19 22
3 8 13 18 23
4 7 14 17 24
5 6 15 16 25
In terms of code, we can write it as:
public class Main {
public static void main(String[] args) {
final int LEN = 5;
int[][] arr = new int[LEN][LEN];
int start = 1, j, k, col;
for (int i = 0; i < LEN; i++) {
if (i % 2 == 0) {
k = 1;
for (j = start, col = 0; k <= LEN; j++, k++, col++) {
arr[i][col] = j;
}
start = j - 1 + LEN;
} else {
k = 1;
for (j = start, col = 0; k <= LEN; j--, k++, col++) {
arr[i][col] = j;
}
start++;
}
}
// Print the transpose of the matrix
for (int r = 0; r < LEN; r++) {
for (int c = 0; c < LEN; c++) {
System.out.print(arr[c][r] + "\t");
}
System.out.println();
}
}
}
Output:
1 10 11 20 21
2 9 12 19 22
3 8 13 18 23
4 7 14 17 24
5 6 15 16 25
Change the value of LEN to 10 and you will get the following pattern:
1 20 21 40 41 60 61 80 81 100
2 19 22 39 42 59 62 79 82 99
3 18 23 38 43 58 63 78 83 98
4 17 24 37 44 57 64 77 84 97
5 16 25 36 45 56 65 76 85 96
6 15 26 35 46 55 66 75 86 95
7 14 27 34 47 54 67 74 87 94
8 13 28 33 48 53 68 73 88 93
9 12 29 32 49 52 69 72 89 92
10 11 30 31 50 51 70 71 90 91

Java for loop with discrete values

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.

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();
}

Categories