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
Related
my output is
4 4 8 7
3 3 3 5 6 3 3 4 5
when it should be
4 4 5
8 7 7
3 3 3 4
5 6 3 1
3 4 5 6
i need to use same method for all of arrays, summing up arrays of two matrices.
how can i do that when arrays are different length and how can i print output correctly?
public static void main(String[] args) {
int[][] m1 = { { 1, 2, 0 }, { 2, 3, 4 } };
int[][] m2 = { { 3, 2, 5 }, { 6, 4, 3 } };
int[][] m3 = { { 1, 1, 1, 1 }, { 3, 3, 2, 1 }, { 2, 2, 2, 2 } };
int[][] m4 = { { 2, 2, 2, 3 }, { 2, 3, 1, 0 }, { 1, 2, 3, 4 } };
printMatrixSum(m1, m2);
System.out.println();
printMatrixSum(m3, m4);
}
private static void printMatrixSum(int[][] x, int[][] y) {
int c[][] = new int[4][4];
for (int i=0; i < 2; ++i) {
for(int j=0;j<3;j++) {
c[i][j]=x[i][j]+y[i][j];
System.out.print(c[i][j]+" ");
}
}System.out.println();
}
}
Your code is close to working. I made some changes below, and it now produces this output:
4 4 5
8 7 7
3 3 3 4
5 6 3 1
3 4 5 6
Here's the code:
1. private static void printMatrixSum(int[][] x, int[][] y) {
2. int[][] c = new int[x.length][x[0].length];
3. for (int i = 0; i < x.length; i++) {
4. for (int j = 0; j < x[0].length; j++) {
5. c[i][j] = x[i][j] + y[i][j];
6. System.out.print(c[i][j] + " ");
7. }
8. System.out.println();
9. }
10. }
Here are the edits I made:
line 2: change int c[][] to int[][] c – this is minor, but follows Java style
line 2: change new int[4][4] to use actual values for array length. The first dimension is just x.length, and the second is x[0].length. This will work correctly with different array inputs vs. hard-coding to "4".
line 3: change i < 2 condition to use the length of one of the input arrays; I chose x but it could be y (and of course this code assumes that x and y are matching dimensions)
line 3: change ++i to i++ – not sure why you were using pre-increment, but in my opinion that makes it harder to reason about loop behavior, and also the second loop (line 4) was already doing post-increment (j++) so I edited this one to make it both clearer as well as consistent with the rest of your code.
line 4: change j < 3 to be dynamic, similar to edit on line 3
line 8: move the println() here, so that a newline is printed after each row of the array is printed
Instead of printing it with fixed sizes ( like i < 2 and j <3 ), use the dimension of the array to make your function more reusable.
ii) Secondly, the println() should be outside the inner loop but inside the outer loop .
private static void printMatrixSum(int[][] x, int[][] y) {
int c[][] = new int[4][4];
for (int i = 0; i < x.length; ++i) {
for (int j = 0; j < y[0].length; j++) {
c[i][j] = x[i][j] + y[i][j];
System.out.print(c[i][j] + " ");
}
System.out.println();
}
}
and this is the answer :
4 4 5
8 7 7
3 3 3 4
5 6 3 1
3 4 5 6
A couple suggestions.
Consider not writing a printMatrixSum method. Write a method to print a matrix. You may not always want to print a matrix after you compute the sum. Of course that means iterating over the matrix twice so it's ultimately going to be based on your requirements.
specify a width value to help nicely format the output.
And you don't need to index the matrix. Multi-dimensional arrays are simply arrays of other arrays. So you can use the enhanced forloop to first iterate the rows, and then the values in each row.
Here is an example.
int [][] data = {{203,2,3334,-22022, 23},{2,1,233, 42,33}};
matPrint(data, 7);
prints
203 2 3334 -22022 23
2 1 233 42 33
use the width to specify the largest value(including sign)
create a format for System.out.printf
then simply iterate the rows. and within each row, iterate the values.
public static void matPrint(int[][] m, int width) {
String fmt = "%" + width + "s";
for (int[] row : m) {
for (int col : row) {
System.out.printf(fmt, col);
}
System.out.println();
}
}
If you have a specific width that you want to use often you can overload the print method as follows. Then you can use the one argument version which invokes the two argument with the default width.
private static int DEFAULT_WIDTH = 4;
public static void matPrint(int[][] m) {
matPrint(m, DEFAULT_WIDTH);
}
And if you specify the field width as a negative value, it will left justify the output within each field.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I've been able to work out the bulk of the problem. But my output keeps throwing an exception. I'm sure it's something minor, but I can't seem to figure out how to make this work right. I'm including the exception, the task as originally worded to me, along with my code so far:
Using formula array[j][n - 1 - i] I get the following exception:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 4
at com.company.Main.main(Main.java:20)
If I use array[j][n - i] I get no exception, but it isn't the correct output order.
Been stuck on this for a week!
Given a rectangle array n×m in size. Rotate it by 90 degrees clockwise, by recording the result into the new array m×n in size.
Input data format:
Input the two numbers n and m, not exceeding 100, and then an array n×m in size.
Output data format:
Output the resulting array. Separate numbers by a single space in the output.
Sample Input 1:
3 4
11 12 13 14
21 22 23 24
31 32 33 34
Sample Output 1:
31 21 11
32 22 12
33 23 13
34 24 14
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int m = scanner.nextInt();
int[][] array = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
array[i][j] = scanner.nextInt();
}
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
System.out.print(array[j][n - 1 - i] + " ");
}
System.out.println("");
}
}
}
If you're only rotating it 90 degrees, you're just starting from the end of the row to the beginning while moving columns left and right. So your code should just be:
int n = 3;
int m = 4;
int[][] array = {
{11, 12, 13, 14},
{21, 22, 23, 24},
{31, 32, 33, 34}};
for (int col = 0; col < m; col++) {
for (int row = n - 1; row >= 0; row--) {
System.out.print(array[row][col] + " ");
}
System.out.println("");
}
I am developing a numerology application which has to provide a result which is similar to the following,
1 5 0 8 1 9 9 4
6 5 8 9 1 1 1
1 1 1 1 2 2
2 2 2 3 4
4 4 5 7
8 9 1
1 1
2
It has to add the consecutive digits and retain the first digit if the sum is of 2 digits.
I am missing something. Adding a while loop for the length of intList doesn't seem to work.
int date;
List<Integer> sumList = new ArrayList<Integer>();
Scanner s = new Scanner(System.in);
System.out.println("Enter the date");
date = s.nextInt();
int len = Integer.toString(date).length();
int[] convertarray = new int[len];
for (int index = 0; index < len; index++) {
convertarray[index] = date % 10;
date /= 10;
}
List<Integer> intList = new ArrayList<Integer>();
for (int i : convertarray) {
intList.add(i);
}
Collections.reverse(intList);
System.out.println(intList);
int sum = 0;
int size = intList.size();
for (int i = 0; i < intList.size() - 1; i++) {
sum = intList.get(i) + intList.get(i + 1);
int length = (int) (Math.log10(sum) + 1);
if (length > 1) {
int firstDigit = Integer.parseInt(Integer.toString(sum).substring(0, 1));
sum = firstDigit;
}
System.out.print(sum + " ");
sumList.add(sum);
}
System.out.println("\n");
intList.clear();
intList = sumList;
My output is something like,
1 5 0 8 1 9 9 4
6 5 8 9 1 1 1
A simple recursive solution:
public static void main(String[] args) throws Exception {
String birthday = "01091995";
int[] digits = Arrays.stream(birthday.split("")).mapToInt(Integer::parseInt).toArray();
recursiveFunction(digits);
}
private static void recursiveFunction(int[] digits) {
if(digits.length == 1) {
// Base Case
System.out.println(digits[0]);
} else {
// Recursive Case
System.out.println(Arrays.toString(digits));
int[] digitsProcessed = new int[digits.length -1];
for (int i = 0; i < digits.length - 1; i++) {
digitsProcessed[i] = digits[i] + digits[i+1]; // Logic
}
recursiveFunction(digitsProcessed);
}
}
This produces:
[0, 1, 0, 9, 1, 9, 9, 5] // 8 numbers
[1, 1, 9, 10, 10, 18, 14] // 7 numbers
[2, 10, 19, 20, 28, 32] // 6 numbers
[12, 29, 39, 48, 60] // 5 numbers
[41, 68, 87, 108] // 4 numbers
[109, 155, 195] // 3 numbers
[264, 350] // 2 numbers
614 // 1 number
Adding a while loop for the length of intList doesn't seem to work.
Well it can be done with loops, but it would be harder and messier.
An algorithm with recursion would be the following:
Init the array of integers.
Call the recursive function "F" with the array.
From now, the recursive function behaviour:
Check if the recieved array's length is 1.
If it is, print the element and terminate.
If it is not:
Print the recieved array.
Make a new array.
Put in this new array the result of processing the recieved one adding as intended.
Call the recursive function "F" with this new array.
This question already has answers here:
ArrayIndexOutOfBounds on enhanced for loop
(2 answers)
Closed 6 years ago.
I'm going through an example on Code Wars. Essentially, taking a number, finding the multiples of 3 and 5 and adding these together. Assuming the number is 10, we'll have 3,5,6,9.
I am at the point where I want to add the multiples together (the foreach loop at the bottom) but I keep getting an OutOfBoundsException. I don't understand how it is reaching index 5! Can someone please explain this to me?
I've seen a few examples of this error on here but can't checking through these I've not been able to resolve the issue, sorry.
package Test;
import java.util.ArrayList;
import java.util.List;
public class MultiplesOf3And5 {
public static void main(String[] args) {
int number = 10;
int total = 0;
List<Integer> multiples = new ArrayList<Integer>();
for (int i = 1; i < number; i++) {
if (i % 3 == 0) {
System.out.println(i + " is a multiple of 3");
multiples.add(i);
} else if (i % 5 == 0) {
System.out.println(i + " is a multiple of 5");
multiples.add(i);
}
}
for (int j : multiples){
System.out.println(multiples.get(j));
System.out.println(multiples.toString());
total += multiples.get(j);
}
System.out.println(total);
}
}
for-each loop iterates the values of your List multiples, you used each value of the List as index by accident. Fix it as below:
for (int j : multiples){
System.out.println(j);
System.out.println(multiples.toString());
total += j;
}
The output is:
3 is a multiple of 3
5 is a multiple of 5
6 is a multiple of 3
9 is a multiple of 3
3
[3, 5, 6, 9]
5
[3, 5, 6, 9]
6
[3, 5, 6, 9]
9
[3, 5, 6, 9]
23
System.out.println(j);
You are trying to get the jth object out of the list, but the you are iterating over the values not the index.
your ArrayList have = 3,6,9(factor of 3) & 5(factor of 5)
so total 4-value reside into ArrayList.
now you are trying to get value from ArrayList not based upon index like 0,1,2,3...
but you are fetching value from ArryList likewise, multiples.get(3), .get(6)... etc.
that's why you get error, like ArrayIndexOutOfBoundException.
Better to follow this way,
for (int j : multiples){
System.out.println(j);
System.out.println(multiples.toString()); // not required but you want then remain it is likewise... or else remove this line
total += j;
}
Your error is occurring because your for loop is assigning the actual values of your array list. Try this:
for(int j = 0, j < multiples.size(), j++) {
System.out.println(multiples.get(j))
}
The var j holds the current value of your iteration, not the current index of the iteration.
This should be enough :
for (int j : multiples) {
System.out.println(multiples.toString());
total += j;
}
So here is the link to problem statement : http://train.usaco.org/usacoprob2?a=ZSMwtXwq7ro&S=comboProblem Statement.
EDIT 1: So the problem is this :
There is a lock and there are 2 valid 3 digit combinations for the lock. One which is set by the user and other one is the master key set by the manufacturer. Also the lock has certain tolerance for errors, ie it will open even if the numbers on the dials are each within at most 2 positions of a valid combination.
For example , suppose user set key was 1, 2, 3 and the master key (manufacturer set) was 4, 5, 6. For these 2 keys 1, 3, 5 is a valid key since the difference between each digit(at same position) of this key and user set key is atmost 2 . But 1, 5, 6 is an invalid combo because the difference between digits of this key and user set key > 2 and same for master key.
Basically what I am doing is pretty naive, I am generating all possible lock combinations and checking for validity of each combination. Here is my code
import java.util.*;
public class combo {
public static void main(String[] args){
Scanner myScanner = new Scanner(System.in);
int N = myScanner.nextInt();
int[] keys = new int[3];
int[] masterKeys = new int[3];
for(int i = 0; i < 3; i++){
keys[i] = myScanner.nextInt();
}
for(int i = 0; i < 3; i++){
masterKeys[i] = myScanner.nextInt();
}
int cnt = 0;
int[] combo = new int[3];
for(int i = 1; i <= N; i++){
combo[0] = i;
for(int j = 1; j <= N; j++){
combo[1] = j;
for(int k = 1; k <=N; k++){
combo[2] = k;
if(validCombo(combo, keys, masterKeys)){
cnt += 1;
}
}
}
}
System.out.println(cnt);
}
// bug here
/*
Valid
combo : 1, 3, 5
key : 1, 2, 3
master 4, 5, 6
Invalid
1 5 6
*/
public static boolean validCombo(int[] combo, int[] keys, int[] masterKeys){
boolean checkKeys = true;
boolean checkMasterKeys = true;
for(int i = 0; i < 3; i++){
if(Math.abs((int)(combo[i]-keys[i])) > 2){
checkKeys = false;
}
if(Math.abs((int)(combo[i]-masterKeys[i])) > 2){
checkMasterKeys = false;
}
}
return checkKeys | checkMasterKeys;
}
}
So for inputs N = 50 , keys = 1, 2, 3 and masterKeys = 5, 6,7 , I get output 184 but the correct output is 249 (sample given test case). Can anyone please just give me a hint as to what is wrong with my logic
You aren't taking into account the fact that the numbers wrap around - i.e., when N = 50, then 50 is 1 away from 1, 2 away from 2, etc.
When trying to debug something like this, it might help if you printed out exactly what your program was counting as solutions, and then comparing to the output listed on the problem site, if they give you such details, or just using the extra information to validate your own thought process.
Instead of "trying" all combinations you could compute them
compute the number of overlapping numbers per dial
if distance between the key number and the master key number
is >= 5 --> you have 10 distinct values
is < 5 --> you have (5 - distance) overlapping numbers
examples:
key: 3 master key: 8 distinct numbers: 10 = 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
key: 3 master key: 6 distinct numbers: 8 = 1, 2, 3, 4, 5, 6, 7, 8
4 and 5 are the overlapping numbers for this dial
if at least for one dial there is no overlapping number then we have the maximum of 250 combinations
if all dials have at least one overlapping number we can compute the
number of overlapping combinations by multiplying the overlapping numbers
of all dials
unique combinations can be computed as max. number - overlapping combinations
example: key: 3, 4, 5 master key: 7, 8, 9
1 2 3 -+
2 3 4 |
3 4 5 |<-- the combinations close to the key
4 5 6 |
5 6 7 -+<-- the only overlapping number
6 7 8 |
7 8 9 |<-- the combinations close to the master key
9 10 11 |
10 11 12 -+
There are 249 valid combinations.
Here a short snippet for the computation.
int numbersPerDail = 50;
int dials = 3;
int[] keys = {2, 2, 3};
int[] masterKeys = {48, 5, 6};
int[] overlappingNumbers = new int[dials];
for (int i = 0; i < dials; i++) {
int distance = Math.max(keys[i], masterKeys[i]) - Math.min(keys[i], masterKeys[i]);
if (distance >= 46) { // the dial is circular
distance = numbersPerDail - distance;
}
overlappingNumbers[i] = 5 - distance;
}
int doubleCombos = 0;
if (overlappingNumbers[0] > 0 && overlappingNumbers[1] > 0 && overlappingNumbers[2] > 0) {
doubleCombos = overlappingNumbers[0] * overlappingNumbers[1] * overlappingNumbers[2];
}
System.out.println("valid combinations = " + (250 - doubleCombos));