I am new to programming and having trouble solving one task. I have several input example. First line contains two numbers m (number of digits on paper, 1<m<1000) and h (limit on the number of operations, 1<h<1000). I have the opportunity, no more than h times, to take any number from a piece of paper (means m), then paint over one of the old digits, and write a new arbitrary digit in its place. By what maximum value can I be able to increase the sum of all the numbers on the piece of paper?
First example:
Input:
5 2 //m and h
1 3 1 4 5 //m = 5, so I can add 5 arbitrary numbers and h=2, so I can change 2 numbers
Output:
16 // cause I changed 1 and 1 to 9 and 9, so the difference 8 and 8 and the sum is 16
Second example:
Input:
3 1
99 5 85
Output:
10 //85 to 95, so the difference is 10
Third example:
Input:
1 10
9999
Output:
0 // nothing to be change
What I have for now:
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number: ");
int m = sc.nextInt();
int h = sc.nextInt();
System.out.println("Entered: " + m);
System.out.println("Entered: " + h);
int[] numbers = new int[m];
for(int i = 0; i < m; ++i) {
numbers[i] = sc.nextInt();
}
Arrays.sort(numbers);
//here is my logic: I am changing 1 to 9
for (int i = 0; i < h; i++) {
if (numbers[i] < 10) {
numbers[i] = 9;
}
else if (numbers[i] > 9 and numbers[i] < 100) {
numbers[i] = 99;
}
}
sc.close();
My logic can work for the first example, but for the second example it won't work. Can you assist me if I am using right logic or is there any easier way to solve this? Thanks in advance.
I quickly came up with below solution
public static void calculateMax(int m,int h, int[] arr){
int sum = 0;
ArrayList<Integer> al = new ArrayList<>();
for(int i=0;i<arr.length;i++){
String stringNum = Integer.toString(arr[i]);
int num = Integer.parseInt(stringNum.substring(0, 1));
if(num!=9){
al.add(Integer.parseInt(("9"+stringNum.substring(1)))-arr[i]);
continue;
}
al.add(0);
}
Collections.sort(al);
int j = al.size()-1;
for(int i=0;i<h && j>0;i++){
sum+=al.get(j--);
}
System.out.println(sum);
}
Here what I am doing is basically, calculating for each number what we can get as maximum by removing one digit and replacing by 9. And I am storing them in a list. Then we can sort that list and get 'h' largest numbers from stored list, and essentially getting the sum of them and printing it.
Break each input number into its digits times the appropriate power of 10. Sort these by powers of 10 descending, digits ascending. Apply your operation in this order.
E.g., 876, 12, 42 -> 800, 70, 6, 10, 2, 40, 2 -> 800, 10, 40, 70, 2, 2, 6.
Im having trouble to find out if a specific amount of numbers is in another array.The first array generates 10 random numbers and in the second array the user guesses 5 numbers.Im trying to find out if the user guessed any sequences.I used for loops to find out if numbers of user input is in any of the numbers from 1-5 in the array of 10 , if not it will check numbers 2-6 and so on.
For example, if the program had the following winning numbers:
23 56 67 06 43 22 59 24 90 66 and user entered: 01 06 43 22 89.
I keep getting index out of bounds.How do I fix this ?
// to check if user guessed a sequence
boolean guessed = false;
int counter = 0;
int i , j = 0;
for (i = 4; i < numbers.length; i++) { // users numbers
for ( j = 4; j < lottery.length; j++) { // first 5 numbers from array
if ( lottery[i] == numbers[j]) {
break;
}
if ( j == i) {
guessed = true;
}
}
}
It seems that a method similar to String::indexOf should be implemented in this task for the arrays trying to find an index of a subarray int indexOf(int[] search, int[] input).
Also, it might be needed to look for all possible subarrays of the search subarray (lottery). Thus, the mentioned method should be extended to look for a subrange of the search argument: int indexOf(int[] search, int[] input)
Straightforward implementation would be:
static int indexOf(int search[], int from, int to, int[] input) {
if (null == search || null == input || search.length > input.length) {
return -1;
}
for (int i = 0, n = input.length - (to - from); i <= n; i++) {
boolean found = true;
for (int j = from; found && j < to; j++) {
if (input[i + j - from] != search[j]) {
found = false;
}
}
if (found) {
return i;
}
}
return -1;
}
The widths and appropriate indexes from / to of the search subranges can be generated as follows (from the entire length of lottery to 2):
int[] numbers = {23, 56, 67, 06, 43, 22, 59, 24, 90, 66};
int[] lottery = {01, 06, 43, 22, 89};
for (int n = lottery.length; n > 1; n--) {
for (int m = 0; m <= lottery.length - n; m++) {
int ix = indexOf(lottery, m, m + n, numbers);
if (ix > -1) {
System.out.printf("Found subarray %s, width=%d from: %d to %d ",
Arrays.toString(Arrays.copyOfRange(lottery, m, m + n)), n, m, m + n - 1);
System.out.printf("at index: %d%n", ix);
}
}
}
Output
Found subarray [6, 43, 22], width=3 from: 1 to 3 at index: 3
Found subarray [6, 43], width=2 from: 1 to 2 at index: 3
Found subarray [43, 22], width=2 from: 2 to 3 at index: 4
A more efficient implementation would use Knuth - Morris - Pratt algorithm to bypass recurrent checks of the same values in the input array.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I have a question. I have two-dimensional arrays with 4x4 as a multiplication table and I have to make a space between columns such that the gap between m and m is equal to the length of the last number in the given column +1.
In the code which I send, as the comments are given the ways that I tried to solve it but I did not succeed
https://gist.github.com/Isbena-4/7e3a628c55d6d9d26f428b9e268e132e
It's must look that
1 2 3 4
2 4 6 8
3 6 9 12
4 8 12 16
You can iterate over the array and find the element with the most digits in each column. Than use %<LEN>d format string to display it with the right length:
int[][] input = {
{1, 2, 3, 4},
{2, 4, -6666, 8},
{3, 6, 9, 12},
{4, 8, 12, 16}
};
int n = input.length;
int[] colLengths = new int[n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
int l = String.valueOf(input[j][i]).length();
if (l > colLengths[i]) {
colLengths[i] = l;
}
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.printf("%" + colLengths[j] + "d ", input[i][j]);
}
System.out.println();
}
will print a well formatted grid while also handling the negative numbers:
1 2 3 4
2 4 -6666 8
3 6 9 12
4 8 12 16
im trying to create a matrix from a file, the file is like this:
Where my first line has the size of the matrix= 10 x 9
And in the other lines, we have 15 values distributed aleatory.
3 5
4 5 6
12 34 12 12 8
34 23
12 34 34 10 89
With the info size i will define my matriz. I use this method for read:
public static void read(){
String line= "";
int i = 0;
try {
while((line = bf.readLine()) != null){
if (i == 0){
//Call method that get the size and create my global matriz
}else{
String[] list = line.split(" ");
//I need help here, for insert correctly in the array
}
i++;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
How i can do for insert orderly in the matrix? My matrix should be like:
4 5 6 12 34
12 12 8 34 23
12 34 34 10 89
Any idea?
This is one way to do it:
String input = "3 5\n" +
"4 5 6\n" +
"12 34 12 12 8\n" +
"34 23\n" +
"12 34 34 10 89\n";
Scanner in = new Scanner(input);
final int rows = in.nextInt();
final int cols = in.nextInt();
int[][] matrix = new int[rows][cols];
int row = 0, col = 0;
for (int i = 0; i < rows * cols; i++) {
matrix[row][col] = in.nextInt();
if (++col == cols) {
row++;
col = 0;
}
}
System.out.println(Arrays.deepToString(matrix));
Output:
[[4, 5, 6, 12, 34], [12, 12, 8, 34, 23], [12, 34, 34, 10, 89]]
It is not necessarily the best way to do it, but I wanted to show the manual increment logic of col and row, where row is incremented when col rolls over.
Using answer by sebenalern, it'd work like this:
int[][] matrix = new int[rows][cols];
for (int row = 0; row < rows; row++)
for (int col = 0; col < cols; col++)
matrix[row][col] = in.nextInt();
Using answer by Paul, it'd work like this:
int[][] matrix = new int[rows][cols];
for (int i = 0; i < rows * cols; i++)
matrix[i / 5][i % 5] = in.nextInt();
All 3 versions rely on the Scanner to simply provide all the values in a sequence, regardless of how they were put together on lines.
If you don't want to use Scanner (e.g. because it is slow), and read the input line-by-line, then values on a line, the 1st version would be easier to use. Otherwise the 3rd is the shortest, and the 2nd version is the most straightforward.
Just a hint - I'll leave your homework to you - :
In this case it would be pretty simple to maintain a counter of all values that have been read so far, and map each of these counter-values to a matrix-value like this:
0 = (0 , 0)
1 = (1 , 0)
...
5 = (0 , 1)
6 = (1 , 1)
...
Using something like this:
int row = counter / rowLength;
int col = counter % rowLength;
In your case:
matrix[counter/5][counter%5] = someValue;
I'm having a problem with two dimensional array. I'm having a display like this:
1 2 3 4 5 6 7 9 10 11 12 13 14 15 16 . . . etc
What basically I want is to display to display it as:
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20
21 22 23 24 ... etc
Here is my code:
int twoDm[][]= new int[7][5];
int i,j,k=1;
for(i=0;i<7;i++){
for(j=0;j<5;j++) {
twoDm[i][j]=k;
k++;}
}
for(i=0;i<7;i++){
for(j=0;j<5;j++) {
System.out.print(twoDm[i][j]+" ");
System.out.print("");}
}
If you don't mind the commas and the brackets you can simply use:
System.out.println(Arrays.deepToString(twoDm).replace("], ", "]\n"));
public class FormattedTablePrint {
public static void printRow(int[] row) {
for (int i : row) {
System.out.print(i);
System.out.print("\t");
}
System.out.println();
}
public static void main(String[] args) {
int twoDm[][]= new int[7][5];
int i,j,k=1;
for(i=0;i<7;i++) {
for(j=0;j<5;j++) {
twoDm[i][j]=k;
k++;
}
}
for(int[] row : twoDm) {
printRow(row);
}
}
}
Output
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
Of course, you might swap the 7 & 5 as mentioned in other answers, to get 7 per row.
You need to print a new line after each row... System.out.print("\n"), or use println, etc. As it stands you are just printing nothing - System.out.print(""), replace print with println or "" with "\n".
You could write a method to print a 2d array like this:
//Displays a 2d array in the console, one line per row.
static void printMatrix(int[][] grid) {
for(int r=0; r<grid.length; r++) {
for(int c=0; c<grid[r].length; c++)
System.out.print(grid[r][c] + " ");
System.out.println();
}
}
A part from #djechlin answer, you should change the rows and columns. Since you are taken as 7 rows and 5 columns, but actually you want is 7 columns and 5 rows.
Do this way:-
int twoDm[][]= new int[5][7];
for(i=0;i<5;i++){
for(j=0;j<7;j++) {
System.out.print(twoDm[i][j]+" ");
}
System.out.println("");
}
I'll post a solution with a bit more elaboration, in addition to code, as the initial mistake and the subsequent ones that have been demonstrated in comments are common errors in this sort of string concatenation problem.
From the initial question, as has been adequately explained by #djechlin, we see that there is the need to print a new line after each line of your table has been completed. So, we need this statement:
System.out.println();
However, printing that immediately after the first print statement gives erroneous results. What gives?
1
2
...
n
This is a problem of scope. Notice that there are two loops for a reason -- one loop handles rows, while the other handles columns. Your inner loop, the "j" loop, iterates through each array element "j" for a given "i." Therefore, at the end of the j loop, you should have a single row. You can think of each iterate of this "j" loop as building the "columns" of your table. Since the inner loop builds our columns, we don't want to print our line there -- it would make a new line for each element!
Once you are out of the j loop, you need to terminate that row before moving on to the next "i" iterate. This is the correct place to handle a new line, because it is the "scope" of your table's rows, instead of your table's columns.
for(i=0;i<7;i++){
for(j=0;j<5;j++) {
System.out.print(twoDm[i][j]+" ");
}
System.out.println();
}
And you can see that this new line will hold true, even if you change the dimensions of your table by changing the end values of your "i" and "j" loops.
Just for the records, Java 8 provides a better alternative.
int[][] table = new int[][]{{2,4,5},{6,34,7},{23,57,2}};
System.out.println(Stream.of(table)
.map(rowParts -> Stream.of(rowParts
.map(element -> ((Integer)element).toString())
.collect(Collectors.joining("\t")))
.collect(Collectors.joining("\n")));
More efficient and easy way to print the 2D array in a formatted way:
Try this:
public static void print(int[][] puzzle) {
for (int[] row : puzzle) {
for (int elem : row) {
System.out.printf("%4d", elem);
}
System.out.println();
}
System.out.println();
}
Sample Output:
0 1 2 3
4 5 6 7
8 9 10 11
12 13 14 15
You can creat a method that prints the matrix as a table :
Note: That does not work well on matrices with numbers with many digits and
non-square matrices.
public static void printMatrix(int size,int row,int[][] matrix){
for(int i = 0;i < 7 * size ;i++){
System.out.print("-");
}
System.out.println("-");
for(int i = 1;i <= matrix[row].length;i++){
System.out.printf("| %4d ",matrix[row][i - 1]);
}
System.out.println("|");
if(row == size - 1){
// when we reach the last row,
// print bottom line "---------"
for(int i = 0;i < 7 * size ;i++){
System.out.print("-");
}
System.out.println("-");
}
}
public static void main(String[] args){
int[][] matrix = {
{1,2,3,4},
{5,6,7,8},
{9,10,11,12},
{13,14,15,16}
};
// print the elements of each row:
int rowsLength = matrix.length;
for(int k = 0; k < rowsLength; k++){
printMatrix(rowsLength,k,matrix);
}
}
Output :
---------------------
| 1 | 2 | 3 | 4 |
---------------------
| 5 | 6 | 7 | 8 |
---------------------
| 9 | 10 | 11 | 12 |
---------------------
| 13 | 14 | 15 | 16 |
---------------------
I created this method while practicing loops and arrays, I'd rather use:
System.out.println(Arrays.deepToString(matrix).replace("], ", "]\n")));
Iliya,
Sorry for that.
you code is work. but its had some problem with Array row and columns
here i correct your code this work correctly, you can try this ..
public static void printMatrix(int size, int row, int[][] matrix) {
for (int i = 0; i < 7 * matrix[row].length; i++) {
System.out.print("-");
}
System.out.println("-");
for (int i = 1; i <= matrix[row].length; i++) {
System.out.printf("| %4d ", matrix[row][i - 1]);
}
System.out.println("|");
if (row == size - 1) {
// when we reach the last row,
// print bottom line "---------"
for (int i = 0; i < 7 * matrix[row].length; i++) {
System.out.print("-");
}
System.out.println("-");
}
}
public static void length(int[][] matrix) {
int rowsLength = matrix.length;
for (int k = 0; k < rowsLength; k++) {
printMatrix(rowsLength, k, matrix);
}
}
public static void main(String[] args) {
int[][] matrix = { { 1, 2, 5 }, { 3, 4, 6 }, { 7, 8, 9 }
};
length(matrix);
}
and out put look like
----------------------
| 1 | 2 | 5 |
----------------------
| 3 | 4 | 6 |
----------------------
| 7 | 8 | 9 |
----------------------
Declared a 7 by 5 array which is similar to yours, with some dummy data. Below should do.
int[][] array = {{21, 12, 32, 14, 52}, {43, 43, 55, 66, 72}, {57, 64, 52, 57, 88},{52, 33, 54, 37, 82},{55, 62, 35, 17, 28},{55, 66, 58, 72, 28}};
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
System.out.print(array[i][j] + " ");
}
System.out.println(); // the trick is here, print a new line after iterating first row.
}
public class class1 {
public static void main(String[] args){
int[][] a={{1, 2, 3}, {4, 5, 6}};
for (int i = 0; i< a.length; i++){
System.out.print("Row" + (i + 1) + ": ");
for (int j = 0; j < a[i].length; j++){
System.out.print(a[i][j] + " ");
}
System.out.println();
}
}
}
result:
Row1: 1 2 3
Row2: 4 5 6
This might be late however this method does what you ask in a perfect manner, it even shows the elements in ' table - like ' style, which is brilliant for beginners to really understand how an Multidimensional Array looks.
public static void display(int x[][]) // So we allow the method to take as input Multidimensional arrays
{
//Here we use 2 loops, the first one is for the rows and the second one inside of the rows is for the columns
for(int rreshti = 0; rreshti < x.length; rreshti++) // Loop for the rows
{
for(int kolona = 0; kolona < x[rreshti].length;kolona++) // Loop for the columns
{
System.out.print(x[rreshti][kolona] + "\t"); // the \t simply spaces out the elements for a clear view
}
System.out.println(); // And this empty outputprint, simply makes sure each row (the groups we wrote in the beggining in seperate {}), is written in a new line, to make it much clear and give it a table-like look
}
}
After you complete creating this method, you simply put this into your main method:
display(*arrayName*); // So we call the method by its name, which can be anything, does not matter, and give that method an input (the Array's name)
NOTE. Since we made the method so that it requires Multidimensional Array as a input it wont work for 1 dimensional arrays (which would make no sense anyways)
Source: enter link description here
PS. It might be confusing a little bit since I used my language to name the elements / variables, however CBA to translate them, sorry.
For traversing through a 2D array, I think the following for loop can be used.
for(int a[]: twoDm)
{
System.out.println(Arrays.toString(a));
}
if you don't want the commas you can string replace
if you want this to be performant you should loop through a[] and then print it.
public static void main(String[] args) {
int[][] matrix = {
{ 1, 2, 5 },
{ 3, 4, 6 },
{ 7, 8, 9 }
};
System.out.println(" ** Matrix ** ");
for (int rows = 0; rows < 3; rows++) {
System.out.println("\n");
for (int columns = 0; columns < matrix[rows].length; columns++) {
System.out.print(matrix[rows][columns] + "\t");
}
}
}
This works,add a new line in for loop of the row. When the first row will be done printing the code will jump in new line.
ALL OF YOU PLEASE LOOT AT IT I Am amazed it need little IQ
just get length by arr[0].length and problem solved
for (int i = 0; i < test.length; i++) {
for (int j = 0; j < test[0].length; j++) {
System.out.print(test[i][j]);
}
System.out.println();
}