I've created a loop and random number generator that generates 100 numbers within the range of 1-100. I need to format these numbers so that it is 10 per line. I tried using printf and had a hard time. In addition, I have to find the average of all these numbers. The issue is I am unsure of how to do this because all the numbers are under the int variable 'randoms'. I can't add a single variable together and divide by 100.
public static void main(String[] args) {
Random rand = new Random();
int n = 100;
for (int i=1; i<=n; i++) {
int randoms = rand.nextInt(101);
}
}
You may print each number without a new line, and with spaces before to pad at 4-length string, and each 10 values, print a new line. For the average, use math : sum/count
Random rand = new Random();
int n = 100;
int total = 0;
for (int i = 1; i <= n; i++) {
int randoms = rand.nextInt(101);
total += randoms;
System.out.format("%4d", randoms);
if (i % 10 == 0) {
System.out.println();
}
}
System.out.println("AVG " + total / (double) n);
49 55 89 26 88 58 80 98 62 8
34 65 9 3 28 71 30 11 50 50
18 90 61 62 18 93 83 83 57 14
9 54 49 6 24 28 60 8 86 83
60 6 17 67 49 89 66 13 65 50
70 24 3 90 89 4 47 49 48 7
16 38 79 59 51 9 22 81 8 84
52 30 64 97 42 100 30 26 66 44
22 46 16 100 73 100 56 63 8 48
50 88 55 93 6 82 65 46 44 7
AVG 49.29
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
Both statements are valid:
char c1 = 'a';
char c2 = 97;
Now, if I add another char variable, lets say:
char c3 = 10;
And I sum c2 and c3 together like so:
int sum = c2 + c3
I do not get compile error and why is that?
And why would I need to ever sum two chars?
Thanks
Each character represented by the type 'char' in java is mapped to a number in the ASCII table. When you add the values you are adding the operands numeric equivalent (the char types are cast as int) so x (120 ascii val) - P(80 ascii val) would give integer value 40.
Dec Char Dec Char Dec Char Dec Char
--------- --------- --------- ----------
0 NUL (null) 32 SPACE 64 # 96 `
1 SOH (start of heading) 33 ! 65 A 97 a
2 STX (start of text) 34 " 66 B 98 b
3 ETX (end of text) 35 # 67 C 99 c
4 EOT (end of transmission) 36 $ 68 D 100 d
5 ENQ (enquiry) 37 % 69 E 101 e
6 ACK (acknowledge) 38 & 70 F 102 f
7 BEL (bell) 39 ' 71 G 103 g
8 BS (backspace) 40 ( 72 H 104 h
9 TAB (horizontal tab) 41 ) 73 I 105 i
10 LF (NL line feed, new line) 42 * 74 J 106 j
11 VT (vertical tab) 43 + 75 K 107 k
12 FF (NP form feed, new page) 44 , 76 L 108 l
13 CR (carriage return) 45 - 77 M 109 m
14 SO (shift out) 46 . 78 N 110 n
15 SI (shift in) 47 / 79 O 111 o
16 DLE (data link escape) 48 0 80 P 112 p
17 DC1 (device control 1) 49 1 81 Q 113 q
18 DC2 (device control 2) 50 2 82 R 114 r
19 DC3 (device control 3) 51 3 83 S 115 s
20 DC4 (device control 4) 52 4 84 T 116 t
21 NAK (negative acknowledge) 53 5 85 U 117 u
22 SYN (synchronous idle) 54 6 86 V 118 v
23 ETB (end of trans. block) 55 7 87 W 119 w
24 CAN (cancel) 56 8 88 X 120 x
25 EM (end of medium) 57 9 89 Y 121 y
26 SUB (substitute) 58 : 90 Z 122 z
27 ESC (escape) 59 ; 91 [ 123 {
28 FS (file separator) 60 < 92 \ 124 |
29 GS (group separator) 61 = 93 ] 125 }
30 RS (record separator) 62 > 94 ^ 126 ~
31 US (unit separator) 63 ? 95 _ 127 DEL
https://www.cs.cmu.edu/~pattis/15-1XX/common/handouts/ascii.html
This prints numbers 32-128 and the associated char:
for (int c=32; c<128; c++)
{
System.out.println("Ascii #: " + c + " Char" + ": " + (char)c);
}
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("");
}
Hy!
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException?
package studing;
public class Array {
public static void main(String[] args) {
int i;
int[] ar1 = new int[50];
for(i = 0; i < ar1.length; i++)
{
ar1[i] = i * 2 + 1;
System.out.print(ar1[i] + " ");
};
System.out.println();
for(i = ar1.length; i > -1; i--)
{
ar1[i] = i * 2 - 1;
System.out.print(ar1[i]);
};
}
}
After compiling the console displays:
1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49
51 53 55 57 59 61 63 65 67 69 71 73 75 77 79 81 83 85 87 89 91 93 95
97 99
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:
50 at studing.Array.main(Array.java:18)
I want the output console in the second row 99 97 95 93 ...
Thanks in advance!
You start at ar1.length in your second loop, which is out of bounds.
To get it to work, you need to start at ar1.length-1, which is the maximum index for your array.
This is because arrays are 0-based in Java, as noted in the comments by #Maroun Maroun.
The first time the second for loop runs, i = 50 (the initial value), which is beyond the end of the array. This value is used before the index update of i--, so ar1[50] is out of bounds (proper indexes are 0 to 49 for a 50 element array).