I am trying to make a number grid using a Java for-loop
but I have difficulty making it aligned and following the pattern.
The output that I want to see is:
5 4 3 2 1
6 7 8 9 10
15 14 13 12 11
16 17 18 19 20
25 24 23 22 21
I've been watching youtube tutorials and articles about Java for-loops
but I can't find any idea to solve this. I am currently stuck with this code:
int j=5;
int up1=14, up2=6;
for(int u=1; u<=5; u++)
{
for(int s=1; s<=5; s++)
{
System.out.print(j+"\t");
j--;
}
System.out.println("");
if(u%2==0){
j+=up1;
}else{
j+=up2;
}
}
Its output is:
5 4 3 2 1
6 5 4 3 2
15 14 13 12 11
16 15 14 13 12
25 24 23 22 21
I have heard about int update
but I have no idea how to apply it in my code.
You forgot to invert the increment(-1/+1) every line.
Then you need only to adjust up1 and you're fine
int j = 5;
int inc = -1;
int up1 = 4, up2 = 6;
for (int u = 1; u <= 5; u++) {
for (int s = 1; s <= 5; s++) {
System.out.print(j + "\t");
j += inc;
}
System.out.println("");
inc = -inc;
if (u % 2 == 0) {
j += up1;
} else {
j += up2;
}
}
Output:
5 4 3 2 1
6 7 8 9 10
15 14 13 12 11
16 17 18 19 20
25 24 23 22 21
Your problem with the alignment might be that you want leading spaces for the single digits, then use this for the print:
System.out.print(String.format("%2d\t", j));
Output
5 4 3 2 1
6 7 8 9 10
15 14 13 12 11
16 17 18 19 20
25 24 23 22 21
Easy way to say your pattern is correct. Now, you remove "tab" or spacing on output.
Look you wrote \t which means give me a spacing of "tab" size.
System.out.print(j+"\t");
You just have to remove \t. Than, give it a single space.
System.out.println(j+" ");
Done!
int k = 1;
for (int i = 1; i <= 5; i++) {
String accending = "",descending="";
for (int j = k; j < k+5; j++) {
accending+=j+"\t";
descending=j+"\t"+descending;
}
if (i % 2 != 0) {
System.out.println(descending);
k=Integer.parseInt(descending.split("\t")[0])+1;
}else{
System.out.println(accending);
k=Integer.parseInt(accending.split("\t")[4])+1;
}
}
I think it is easy to understand with this code.Simply turn ending digit in each line to a number.
Solution
Even Rows
The pattern for the even rows is that it increases always by 10, you can simply take your j indice and multiply it by factor 5 times the row number.
Important note Here in the example I started counting rows at zero 0 - 4, because first row is odd
Row || Column
1. 2. 3.
0. 5 + (5*0) -> 5 4 + (5*0) -> 4 3 + (5*0) -> 3
2. 5 + (5*2) -> 15 4 + (5*2) -> 14 3 + (5*2) -> 13 ....
4. 5 + (5*4) -> 25 4 + (5*4) -> 24 3 + (5*4) -> 23
Odd Rows
For the odd rows the pattern is more difficult
It increases the last column by ten and then go "backwards" the j value.
Here I defined an counter variable which I increment in every odd iteration.
Row || Column
1. 2.
1. 10*1 - 5 + 1 -> 6 10*1 - 4 + 1 -> 7
3. 10*2 - 5 + 1 -> 16 10*2 - 4 + 1 -> 17
5. 10*3 - 5 + 1 -> 26 10*3 - 4 + 1 -> 27 // this it how it would continue
Here the Full Solution
public static void main(String[] args) {
int counter = 1;
for(int i = 0; i < 5; i++) {
for(int j = 5; j > 0; j--){
if(i % 2 == 0) {
System.out.print(j+(5*i)+ " ");
}else {
System.out.print(10*counter -j+1 + " ");
}
}
if(i%2!=0) {
counter ++;
}
System.out.println();
}
Output is
5 4 3 2 1
6 7 8 9 10
15 14 13 12 11
16 17 18 19 20
25 24 23 22 21
The given pattern goes like this:
The pattern starts with a number e.g. X = 5.
When the main loop counter is an odd number, the print counter starts with start value and decreases by one X times. Finally, it sets start for the next row to start with the final value of the print counter - 1 + X.
When the main loop counter is an even number, the print counter starts with start value and increases by one X times. Finally, it sets start for the next row to start with start + 1.
Based on this property of the pattern, you can write it as
public class Main {
public static void main(String[] args) {
final int X = 5;
int start = X, j, k;
for (int i = 1; i <= X; i++) {
if (i % 2 == 0) {
k = 1;
for (j = start; k <= X; j++, k++) {
System.out.print(j + "\t");
}
start = j - 1 + X;
} else {
k = 1;
for (j = start; k <= X; j--, k++) {
System.out.print(j + "\t");
}
start++;
}
System.out.println();
}
}
}
Output:
5 4 3 2 1
6 7 8 9 10
15 14 13 12 11
16 17 18 19 20
25 24 23 22 21
Change the value of X to 10 and you will get the following pattern:
10 9 8 7 6 5 4 3 2 1
11 12 13 14 15 16 17 18 19 20
30 29 28 27 26 25 24 23 22 21
31 32 33 34 35 36 37 38 39 40
50 49 48 47 46 45 44 43 42 41
51 52 53 54 55 56 57 58 59 60
70 69 68 67 66 65 64 63 62 61
71 72 73 74 75 76 77 78 79 80
90 89 88 87 86 85 84 83 82 81
91 92 93 94 95 96 97 98 99 100
int j=5;
int up1=14, up2=6;
for(int u=1; u<=5; u++)
{
for(int s=1; s<=5; s++)
{
System.out.printf("%5d",j);
j--;
}
System.out.println("");
if(u%2==0) {
j+=up1;
} else {
j+=up2;
}
}
What do you think about this code?
Related
I was wondering how I could align this code properly? So that it could look more like a table. In the output, the numbers start shifted to the right and I do not know how to fix it
public class MultiplicationTable {
int[][] arr = new int[13][13];
public void initializeBoard()
{
for(int i = 1; i < 13; i ++)
{
for(int j = 1; j < 13; j++)
{
arr[i][j] = i * j;
}
}
}
public void printBoard()
{
for(int i = 1; i < 13; i ++)
{
for(int j = 1; j < 13; j++)
{
System.out.print(arr[i][j] +" ");
}
System.out.println();
}
}
}
Use the Scanner#printf() method to display formatted text within the Console window, for example:
public void printBoard() {
for (int i = 1; i < 13; i++) {
for (int j = 1; j < 13; j++) {
System.out.printf("%-6s", arr[i][j]);
}
System.out.println();
}
}
The Console should display:
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 have done it almost correctly. I believe with a smaller change in your printBoard() method like this should make the out put correctly
public static void printBoard()
{
for(int i = 1; i < 13; i ++)
{
for(int j = 1; j < 13; j++)
{
if(arr[i][j] >= 100){
System.out.print(arr[i][j] +" ");
} else if(arr[i][j] >= 10){
System.out.print(arr[i][j] +" ");
} else {
System.out.print(arr[i][j] +" ");
}
}
System.out.println();
}
}
And I got the output like this
I hope this helps.
I need to get this result :
input I wanted to have
I am very close but the final step is killing me:
public static void printMultiplicationTable(int size) {
System.out.print("\t");
for (int i = 0; i <= size; i++) {
for (int j = 0; j <= size; j++) {
if (j == 0) System.out.print( i );
else if (i == 0) System.out.print("\t" + j);
else System.out.print("\t" + i * j);
}
System.out.println();
}
}
How do I get empty space at first line and start from 1 instead of 0 ?
You were indeed close. your first System.out.print("\t"); was causing extra tab. Also, I have added the output for the condition when i==0 && j==0. Given below is the program that prints the desired result:
public class TestMyClass {
public static void main(String[] args) {
printMultiplicationTable(4);
}
public static void printMultiplicationTable(int size) {
for (int i = 0; i <= size; i++) {
for (int j = 0; j <= size; j++) {
if (i==0 && j==0)
System.out.print("");
else if (j == 0)
System.out.print(i);
else if (i == 0)
System.out.print("\t" + j);
else
System.out.print("\t" + i * j);
}
System.out.println();
}
}
}
Output:
1 2 3 4
1 1 2 3 4
2 2 4 6 8
3 3 6 9 12
4 4 8 12 16
Your "one loop to rule them all" is making this more difficult for you.
Break it down into simpler concepts.
Print the header row first.
Print the rows and check for the first index to print the left-side
Pre-calculate the width of the max value (for formatting)
public class MathTutor {
public static void main(String[] args) {
printMultiplicationTable(3);
printMultiplicationTable(6);
printMultiplicationTable(12);
}
public static void printMultiplicationTable(int size) {
String numberFormat = String.format("%%%dd", maxDigits(size));
for (int col = 0; col < size; col++) {
System.out.print("\t");
System.out.printf(numberFormat, col + 1);
}
System.out.println();
for (int row = 1; row <= size; row++) {
System.out.printf(numberFormat, row);
for (int col = 1; col <= size; col++) {
System.out.print("\t");
System.out.printf(numberFormat, row * col);
}
System.out.println();
}
}
public static int maxDigits(int size) {
return (int) Math.floor(Math.log10(Math.pow(size, 2))) + 1;
}
}
Multiplication table for 3
1 2 3
1 1 2 3
2 2 4 6
3 3 6 9
Multiplication table for 6
1 2 3 4 5 6
1 1 2 3 4 5 6
2 2 4 6 8 10 12
3 3 6 9 12 15 18
4 4 8 12 16 20 24
5 5 10 15 20 25 30
6 6 12 18 24 30 36
Multiplication table for 12
1 2 3 4 5 6 7 8 9 10 11 12
1 1 2 3 4 5 6 7 8 9 10 11 12
2 2 4 6 8 10 12 14 16 18 20 22 24
3 3 6 9 12 15 18 21 24 27 30 33 36
4 4 8 12 16 20 24 28 32 36 40 44 48
5 5 10 15 20 25 30 35 40 45 50 55 60
6 6 12 18 24 30 36 42 48 54 60 66 72
7 7 14 21 28 35 42 49 56 63 70 77 84
8 8 16 24 32 40 48 56 64 72 80 88 96
9 9 18 27 36 45 54 63 72 81 90 99 108
10 10 20 30 40 50 60 70 80 90 100 110 120
11 11 22 33 44 55 66 77 88 99 110 121 132
12 12 24 36 48 60 72 84 96 108 120 132 144
I have a program which generates rows of 6 numbers (int arrays).
I am passing the output to another program that sorts it with the BubbleSort algorithm and writes it into a textfile.
If the first program is used without passing it works fine, no repeated numbers no zeroes. but when sorted there are repeated numbers and even i have seen zeroes, the case of the zeroes i could not reproduce atm, but the double occuring numbers. Could it have something to do with multithreading/parallel processing or the environment in whicht it is executed and which consist of a amd multicore win 10 host and deb jessie guest.
java LottoArray | java BubbleSort>test2.txt //terminal
test2.txt
2 13 16 20 27 40
9 14 17 21 25 41
6 11 11 19 27 44
4 10 25 34 39 47
11 12 17 36 44 48
1 15 23 31 39 40
3 22 22 23 33 45
1 25 26 26 35 49
11 14 24 25 41 49
6 6 14 17 38 46
4 19 19 28 35 39
As you can see the sixs in the row before the last row are double and the 22s and the 11s.
public class LottoArray{
public static void main (String [] args){
for(int o=0;o<=10;o++){
int Reihe [] = new int [6];
int zahl;
int j=0;
int i= 0;
while(j<Reihe.length){
zahl = (int) (Math.random()*50);
boolean schonda = false;
while ( i<j){
if(Reihe[i]== zahl)
schonda=true;
i++;
}
if(schonda==false && zahl !=0){
Reihe[j]=zahl;
j++;}
}
for(int z=0;z<6;z++){
System.out.print(Reihe[z]+" ");
}
System.out.println();
}
}
}
public class BubbleSort {
public static void main(String args[]) {
int arr[]= new int[6];
while(!StdIn.isEmpty()){
for(int i=0;i<6;i++)
arr[i]= StdIn.readInt();
boolean getauscht;
do {
getauscht= false;
for (int i=0; i<arr.length-1; i++) {
if ( arr[i] > arr[i+1]) {
int tmp = arr[i];
arr[i] = arr[i+1];
arr[i+1] = tmp;
getauscht = true;
}
}
}while(getauscht);
for (int i=0; i<arr.length; i++)
System.out.print(arr[i]+" " );
System.out.println();
}
}
}
if i use the code without the bubbleSort and stream the output into a textfile, there are no repeated numbers and no zeroes, as it should be not possible because i coded the condition if(schonda==false && zahl !=0)
15 2 20 5 26 34
13 6 15 33 12 37
44 17 16 23 40 25
25 47 10 43 40 44
25 29 3 30 10 41
32 1 23 35 43 28
9 34 28 32 33 25
5 46 31 16 25 9
9 13 16 18 40 5
29 15 16 2 16 15
34 33 44 13 43 48
has someone experiences with that kind of occurring numbers that should not ?
You problem is in this block of LottoArray:
int j=0;
int i= 0;
while(j<Reihe.length){
zahl = (int) (Math.random()*50);
boolean schonda = false;
while ( i<j){
if(Reihe[i]== zahl)
schonda=true;
i++;
}
if(schonda==false && zahl !=0){
Reihe[j]=zahl;
j++;
}
}
The first time you enter in the while (i<j){ loop from above (for the first element), both i and j are 0, so the loop is not executed.
The second time (checking the second number), i is 0 and j is 1, so the loop is executed and i is increased.
The third time (checking the third number), i is 1 and j is 2.
Same for the rest, i is always j-1.
This is a bug, as you are not starting the check on the first element. I suppose you are only getting duplicates using the BubbleSort out of luck, as the error is not there.
To fix this, initialize i inside the first while, in the same place as the schonda var, not above with j.
I have a task to do and I am a little stuck.
I have to order some arrays from a file with 'selection sort' method and write the solution to the end of the file.
For example:
file.txt
9 3 1 12 8 6
22 3 1 8
78 61 19 5 99
is given. After sorting I should have something like that:
file.txt
9 3 1 12 8 6
22 3 1 8
78 61 19 5 99
----sorted----
1 3 6 8 9 12
1 3 8 22
5 19 61 78 99
I have to mention that I have to do it in PHP, Java, C# and Python.
I started coding it in PHP but I'm a little stuck. My code looks like this:
<?php
function selectionSort(array $array) {
$length = count($array);
for($i = 0; $i < $length; $i ++) {
$min = $i;
for($j = $i + 1; $j < $length; $j ++) {
if ($array[$j] < $array[$min]) {
$min = $j;
}
}
$tmp = $array[$min];
$array[$min] = $array[$i];
$array[$i] = $tmp;
}
return $array;
}
//CREATE ARRAYS FROM FILE LINES:
$file_handle = fopen("fisier.txt", "r+");
while (!feof($file_handle) ) {
$line_of_text = fgets($file_handle);
$parts = explode(' ', $line_of_text);
$parts_sorted = selectionSort($parts);
for ($n=0; $n<count($parts_sorted); $n++){
echo $parts_sorted[$n]." ";
}
echo "<br>";
}
fclose($file_handle);
The problem here is that it doesn't sort well, I mean my txt file is
9 12 5 4 13 8
3 7 12 44 22 4 13
70 1 12 55 34
22 13 7 50 3 1 9 14 27 77
56 2 9 45 35 12 7 63
and the result from the php code is
4 5 8 9 12 13
13 3 4 7 12 22 44
1 12 34 55 70
1 3 7 77 9 13 14 22 27 50
2 7 9 12 35 45 56 63
which is not a good sort. Can you tell why?
Do you know what should I do next to write the sorted arrays to the end of the file?
And a little help for java,c# and python would be great. Sorry for the long post but I am a noob here. Thank you!
fgets() returns the linefeed/carriage-return character that ends the line
So you're not comparing 13 to something but 13\r\n or 13\n or ....
You can either do something like
$line_of_text = trim(fgets($file_handle));
to get rid of any leading/trailing whitespace of the line read from the file and/or
$parts = array_map('intval', explode(' ', $line_of_text));
to convert every element to an integer.
(In case all elements are within the value range of a php integer, I advise using the array_map/intval thingy as the comparision of numers as number is apparently what you want. Otherwise you might be interested in strnatcmp() as your comparision function instead of the < operator)
Here is a short Java snippet.
What it does
read the file file.txt line by line
convert the values of a line into integer values
sort the integer values using method selectionSort(int[])
write the sorted values back to file file_sorted.txt
.
// equal to your PHP implementation
static void selectionSort(int[] ints) {
for (int i = 0; i < ints.length - 1; i++) {
int min = i;
for (int j = i + 1; j < ints.length; j++) {
if (ints[j] < ints[min]) {
min = j;
}
}
int temp = ints[min];
ints[min] = ints[i];
ints[i] = temp;
}
}
...
Path fileIn = Paths.get("file.txt");
Path fileOut = Paths.get("file_sorted.txt");
try (BufferedReader br = Files.newBufferedReader(fileIn);
BufferedWriter bw = Files.newBufferedWriter(fileOut,
StandardOpenOption.CREATE_NEW)) {
for (String l = br.readLine(); l != null; l = br.readLine()) {
String[] fields = l.split(" +");
int[] ints = Arrays.asList(fields) // convert to List
// convert the List into a Stream
.stream()
// map the entries to their integer values
.mapToInt(f -> Integer.valueOf(f))
// convert the stream to an array
.toArray();
selectionSort(ints);
for (int i = 0; i < ints.length; i++) {
bw.append(Integer.toString(ints[i]));
if (i < ints.length - 1) {
bw.append(' ');
}
}
bw.newLine();
}
}
input file.txt
9 12 5 4 13 8
3 7 12 44 22 4 13
70 1 12 55 34
22 13 7 50 3 1 9 14 27 77
56 2 9 45 35 12 7 63
output file_sorted.txt
4 5 8 9 12 13
3 4 7 12 13 22 44
1 12 34 55 70
1 3 7 9 13 14 22 27 50 77
2 7 9 12 35 45 56 63
I have to print out the table in a matrix like fashion, each number formatted to a width of 4 (The numbers are right-aligned and strip out leading/trailing spaces on each line). The first 3 line will look like:
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
This is my code:
public static void main (String[] args) {
int i,j;
for(i=1;i<=3;i++){
for(j=1;j<=12;j++){
System.out.format("%4d",i*j);
}
System.out.println();
}
}
In the output the first integer gets shifted by 3 spaces.How to strip out the leading/trailing spaces on each line?
Assuming you'll want to get rid of all useless whitespaces in between, why not avoid them in the first place?
public static void main(String[] args) {
int rows = 3, columns = 12;
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= columns; j++) {
// figure out the max # of digits needed
int necessaryDigits;
if (rows * j < 10) {
necessaryDigits = 1;
} else if (rows * j < 100) {
necessaryDigits = 2;
} else if (rows * j < 1000) {
necessaryDigits = 3;
} else {
necessaryDigits = 4;
}
// print them accordingly with one extra space to distinguish
// the numbers and avoid the leading one in 1st column
System.out.format("%" + (necessaryDigits + (j == 1 ? 0 : 1))
+ "d", i * j);
}
System.out.println();
}
}
output:
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
output or for 10 rows:
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
Try printing the first number same as i out of your second loop and start your second loop from second i.e. 2 like:
for(i=1;i<=3;i++){
System.out.print(i);
for(j=2;j<=12;j++){
System.out.format("%4d",i*j);
}
System.out.println();
}
if allowed to put the condition you have like this
int i, j;
for (i = 1; i <= 3; i++)
{
for (j = 1; j <= 12; j++)
{
if (j == 1)
{
System.out.format("%d", i * j);
}
else
{
System.out.format("%4d", i * j);
}
}
System.out.println();
}