I want to write a program that reads a matrix of positive int with the format txt (the matrix can be of any size). (I read the matrix from the console).
The program looks for a location in the matrix such that if a knight is positioned at that location, all possible moves will land the knight on elements which have the same value and it must have at least 2 options. The program prints the result. for example, the black places are where the knight can move to.
This is the code I wrote. the problem is that i'm getting: "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at Knights.main(Knights.java:23)", I know it has a problem with the first row (there is no backwards value in the start of the matrix) but I don't know how can I fix it.
public static void main (String[] args) {
String size = StdIn.readLine();
int counter = 0;
int matrixSize = Integer.parseInt(size);
int [][] matrix = new int [matrixSize+1][matrixSize+1];
for (int i=0; i <= matrixSize-1; i++) {
for (int j=0; j <= matrixSize-1; j++) {
if ((matrix[i][j]) > 0)
matrix[i][j] = StdIn.readInt();
}
}
for (int k=0; k <= matrixSize-2; k++) {
for (int l=0; l <= matrixSize-2; l++) {
if (matrix[k-1][l+2] == matrix[k+1][l+2]) {
counter +=1;
StdOut.println(counter); }
else if (matrix[k-1][l+2] == matrix[k+1][l-2]) {
counter +=1;
StdOut.println(counter); }
if (counter>=2)
StdOut.println("location "+ matrix[k][l] + "is surrounded by the number " +matrix[k+1][l-2]);
}
}
if (counter < 2)
StdOut.println("no surrender by any number");
}
}
I would add an extra test here to check if k-1 is greater than 0.
As && is a short-circuit operator, the second expression is not tested if the first is false and can not throw an exception.
Solution
if (k - 1 > 0 && matrix[k - 1][l + 2] == matrix[k + 1][l + 2]) {
counter += 1;
StdOut.println(counter);
} else if (k - 1 > 0 && matrix[k - 1][l + 2] == matrix[k + 1][l - 2]) {
counter += 1;
StdOut.println(counter);
}
Related
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 3 years ago.
I have to check if a sequence of any numbers are equals. The user will submit a sequence, and if, the numbers repeat in sequence, he won some points.
And the sequence to win the points it's a sequence of three. For example:
1 3 4 4 4 5
He won the points because he inputted a sequence of 3 numbers 4.
The sequence of numbers it's on a Vector. The size of the vector, It's given by the user too.
for (int i = 0; i < M.length; i++) {
if (M[i] == M[i + 1] && M[i + 1] == M[i+2]) {
if (L[i] == L[i + 1] && L[i + 1] == L[i + 2]) {
ValuePoint = 0;
} else {
PExtraM = i;
ValuePoint = 30;
}
Scanner sc1 = new Scanner(System.in);
R = sc1.nextInt();
int M[] = new int[R];
int L[] = new int[R];
for (int i = 0; i < M.length; i++) {
M[i] = sc1.nextInt();
}
for (int i = 0; i < L.length; i++) {
L[i] = sc1.nextInt();
}
//The problem It's here ************************************
for (int i = 0; i < M.length; i++) {
if (M[i] == M[i + 1] && M[i + 1] == M[i+2]) {
if (L[i] == L[i + 1] && L[i + 1] == L[i + 2]) {
ValuePoint = 0;
} else {
PExtraM = i;
ValuePoint = 30;
}
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at maratona.Maratona2.main(Maratona2.java:37)
Java Result: 1
i < M.length
Now let's assume the length of the Vector you are saying is 5 ok?
Now my loop will run till i is less than 5, right?
Now go to your next code :
if (M[i] == M[i + 1] && M[i + 1] == M[i+2])
Let's take the value of i as
4 (suppose)
which is in fact less than 5 and the loop condition satisfies.
But see the next code, it becomes
M[4]==M[5]&& ==M[6]
Obviously since the length of the given Vector is 5, my last element's index will be 4.
So after that **5 & 6 ** will show null only.
That's why it's saying ArrayIndexOutOfBounds Exception error at 5.
Hope this helps!
your loop variable i must stop at m.length-3
(i <m. length-2)
to have i+1=m.length-2 and i+2=m.length-1
but in your case you are trying to access i+1=m.length and i+2= m.length+1 both are out of bounds on the last two iterations
As the others already said, u r overshooting the boundaries of your array. You need to stop the loop 2 earlier to prevent.
You possably want to use something like that:
int sequenceLength = 3;
for (int i = 0; i <= M.length - sequenceLength; i++) {
boolean correct = true;
for (int j = 0; j < sequenceLength && (correct = (M[i] == M[j+i])); j++);
if (correct){
ValuePoint = 0;
} else {
PExtraM = i;
ValuePoint = 30;
break;
}
}
In this case, I want to add two numbers in this array in to obtain a specific sum when added, let’s say, 4. I also want to output what indices are being added in order to obtain that specific sum, just to see the inner workings of my code. What am I doing wrong?
public static int addingNumbers(int[] a) {
int i1 = 0, i2 = 0;
for(int i = 0, j = i + 1; i < a.length && j < a.length; i++, j++) {
if(a[i] + a[j] == 4) { // index 0 and index 2 when added gives you a sum 4
i1 = i;
i2 = j;
}
}
System.out.println("The indices are " + i1 + " and " + i2);
return i1;
}
public static void main(String args[]) {
int[] a = {1, 2, 3, 4, 5, 6};
System.out.println(addingNumbers(a));
}
The error you are making is using only one loop that iterates over the array once:
for(int i = 0, j = i + 1; i < a.length && j < a.length; i++, j++) {
In your loop you are setting i to 0 and j to 1, then you increment them with every step. So you are only comparing adjacent places in your array:
iteration: a[0] + a[1]
iteration: a[1] + a[2]
iteration: a[2] + a[3]
etc. pp
Since your array doesn't have two adjacent elements that sum up to 4 your if(a[i] + a[j] == 4) will never be entered and i1, i2 will still be 0 when the loop is finished.
To compare every array element with each other you should use 2 nested loops:
public static int addingNumbers(int[] a) {
int i1 = -1, i2 = -1;
for(int i = 0; i < a.length ; i++) {
for(int j = i+1; j < a.length ; j++) {
if(a[i] + a[j] == 4) { // index 0 and index 2 when added gives you a sum 4
i1 = i;
i2 = j;
}
}
}
if(i1>=0 && i2 >=0) {
System.out.println("The indices are " + i1 + " and " + i2);
}
return i1;
}
Note that this will only print out the last detected 2 indices that add up to 4. If you want to be able to detect multiple possible solutions and print them out could for example move the System.out.println into the if block.
It can never be == 4 because 1+2=3 then 2+3=5. So it does nothing.
There is a logic error in your code. The sum you are checking in your code is never for.
I added some debug output for easy checking:
public static int addingNumbers(int[] a) {
int i1 = 0, i2 = 0;
for(int i = 0, j = i + 1; i < a.length && j < a.length; i++, j++) {
int sum = a[i] + a[j];
System.out.println(sum);
if(sum == 4) { // index 0 and index 2 when added gives you a sum 4
i1 = i;
i2 = j;
}
}
System.out.println("The indices are " + i1 + " and " + i2);
return i1;
}
Output is: 3
5
7
9
11
The indices are 0 and 0
0
this algorithm will never be able to add a[0] to a[2], be cause when you put j=i+1 it will always be 0+1 then 1+2 ... The sum of tow adjacent numbers is never pair.
An other matter is the condition to stop your loop must be j < a.length-1
try to explain more of what you want from your algorithm.
Are you over complicating this on purpose?
Trying to figure out your intention for this task.
Why don't you just do (this is pseudo):
for length of i {
if (a[i] + a[i+1] == 4) {
System.out.println("The indices are " + a[i] + " and " + a[i+1]);
}
}
I am trying to find the counts for negative numbers in a 2d-array ( square- matix). In matrix if you go from up to down and left to write number increases. Logic here is to start from last column and proceed to the left. If you find the neg num then increase the row index and proceed the same way till the last row. I am getting the error in java code but not in python.
public class O_n
{
public static void main(String[] args)
{
int firstarray[][] = {{-2,-1,0},{-1,0,1},{0,1,2}};
int secondarray[][] = {{-4,-3,-2},{-3,-2,-1},{-2,-1,0}};
System.out.print ("First array has"+count_neg(firstarray));
System.out.println("negative numbers");
System.out.print ("Second array has"+count_neg(secondarray));
System.out.println("negative numbers");
}
public static int count_neg(int x[][]){
int count = 0;
int i = 0; //rows
int j = x.length - 1; //columns
System.out.println("max column index is: "+j);
while ( i >=0 && j<x.length){
if (x[i][j] < 0){ // negative number
count += (j + 1);// since j is an index...so j + 1
i += 1;
}
else { // positive number
j -= 1;
}
}
return (count);
}
}
I am getting this output
max column index is: 2
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at O_n.count_neg(O_n.java:22)
at O_n.main(O_n.java:9)
/home/eos/.cache/netbeans/8.1/executor-snippets/run.xml:53: Java
returned: 1
BUILD FAILED (total time: 0 seconds)
What is wrong with this code? the same thing worked in python...
def count_neg(array):
count = 0
i = 0 # row
j = len(array) -1 # col
# since we are starting from right side
while j >= 0 and i < len(array):
if array[i][j] < 0:
count += (j + 1)
i += 1
else:
j -= 1
return count
print(count_neg([[-4,-3,-1,1],[-2,-2,1,2],[-1,1,2,3],[1,2,4,5]]))
I would write the method like this, just go through the 2d array and increase count each time a negative number is found
public static int count_neg(int x[][]){
int count = 0;
for(int i = 0; i < x.length; i++){
for(int j = 0; j < x[i].length; j++){
if(x[i][j] < 0){
count++;
}
}
}
return (count);
}
Your indexes are reversed from the python version:
while j >= 0 and i < len(array)
To the Java version:
while (i >= 0 && j < x.length)
// Change to
while (j >= 0 && i < x.length)
Output:
max column index is: 2
3
If you are using Java8, you can use streams to implement count_neg:
public static int countNeg(int x[][]) {
long count = Stream.of(x)
.flatMapToInt(arr -> IntStream.of(arr))
.filter(i -> i < 0)
.count();
return Math.toIntExact(count);
}
First of all your algorithm don't find the count of negative numbers.
Here are the results of the python code:
print(count_neg([[1, 1, -1],[1, 1, -1],[1, 1, -1]])) result - 9
print(count_neg([[1, 1, -1],[1, 1, 1],[1, 1, 1]])) result - 3
So the provided code finds sum of column indexes + 1 for some negative numbers, not all. And for your test arrays it's return pseudo correct counts.
To find the count of negative numbers in a two-dimentional array you just have to get each number, check if the one is less than zero and increase the counter by one if it's true. So it's impossible to get the correct result with complexity better than O(n2).
Here the correct code in Java of doing that:
public static int count_neg(int x[][]){
int count = 0;
for(int i = 0; i < x.length; i++){
for(int j = 0; j < x[i].length; j++){
if(x[i][j] < 0) count++;
}
}
return count;
}
Here a small change in the algorithms to produce correct result with columns which don't contain negative numbers:
while j >= 0 and i < len(array):
if array[i][j] < 0:
count += (j + 1)
i += 1
else:
j -= 1
if j < 0:
i += 1
j = len(array) - 1
You can test it with the following array [[1,2,4,5],[-2,-2,1,2],[-1,1,2,3],[1,2,4,5]]
Problem: Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.
Do not allocate extra space for another array, you must do this in place with constant memory.
Example
Given input array A = [1,1,2],
Your function should return length = 2, and A is now [1,2].
My solution:
public int removeDuplicates(int[] nums) {
if(nums.length == 0) {
return 0;
}
int size = 0;
for(int i = 0; i < nums.length; i++) {
if((i + 1) <= nums.length && (nums[i] != nums[i + 1])) {
nums[size] = nums[i];
size++;
}
}
}
The problem that I am running into is a ArrayIndexOutOfBoundsException in the second if statement:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5 at Solution.removeDuplicates(Solution.java:15) at Main.main(Main.java:10)
I do not understand why because I am checking if i+1 <= the length of the array, which should prevent the overflow error.
You should change the "i + 1 <= nums.length" to "i + 1 < nums.length". When your variable (i) is at the end of loop (i + 1) will be out of array. For example A = [1,1,2] and the length is 3. In the for loop i will be 2 and i+1 will be 3 so nums[3] wil be out of bound.
for(int i = 0; i < nums.length; i++) {
if((i + 1) < nums.length && (nums[i] != nums[i + 1])) {
nums[size] = nums[i];
size++;
}
else if(i + 1 == nums.length)
num[size] = nums[i];
}
I just created an array with 100 initialized values and I want to print out 10 elements on each line so it would be somthing like this
0 1 2 3 4 5 6 7 8 9
10 11 12 13 14 15 16
...26
this is the code I used and I managed to do it for the first 10 elements but I couldn't figure out how to do it for the rest
public static void main(String[] args) {
int[] numbers = { 0,1,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17};
int i, count = 0;
for (i = 0; i < numbers.length; i++) {
System.out.print(numbers[i] + " ");
count++;
if (count == 9)
for (i = 9; i < numbers.length; i++)
System.out.println(numbers[i] + " ");
}
}
int[] numbers = new int[100];
for (int i = 0; i < numbers.length; i++) {
if (i % 10 == 0 && i > 0) {
System.out.println();
}
System.out.print(numbers[i] + " ");
}
This prints a newline before printing numbers[i] where i % 10 == 0 and i > 0. % is the mod operator; it returns the remainder if i / 10. So i % 10 == 0 when i = 0, 10, 20, ....
As for your original code, you can make it work with a little modification as follows:
int count = 0;
for (int i = 0; i < numbers.length; i++) {
System.out.print(numbers[i] + " ");
count++;
if (count == 10) {
System.out.println();
count = 0;
}
}
Basically, count is how many numbers you've printed in this line. Once it reaches 10, you print the newline, and then reset it back to 0, because you're starting a new line, and for that line, you haven't printed any numbers (yet).
Note that in above two solutions, an extra space is printed at the end of each line. Here's a more flexible implementation that only uses separators (horizontal and vertical) when necessary. It's only slightly more complicated.
static void print(int[] arr, int W, String hSep, String vSep) {
for (int i = 0; i < arr.length; i++) {
String sep =
(i % W != 0) ? hSep :
(i > 0) ? vSep :
"";
System.out.print(sep + arr[i]);
}
System.out.println(vSep);
}
If you call this say, as print(new int[25], 5, ",", ".\n");, then it will print 25 zeroes, 5 on each line. There's a period (.) at the end of each line, and a comma (,) between zeroes on a line.
Why do you use 2 nested loops where you only need to remember at which places you need to output a linebreak? Also using the same variable i for both loops will not do what you expect.
How about:
for (i = 0; i < numbers.length; i++) {
System.out.print(numbers[i] + " ");
count++;
if (count == 10)
System.out.print("\n");
count = 0;
}
}
All you are going to have to do is to print out a newline after every ten numbers.
for (i = 0; i < numbers.length; ++i)
{
System.out.print(number[i]);
if (i % 10 == 9)
{
System.out.println();
}
else
{
System.out.print(" ");
}
}
I know this is an old question, but I just wanted to answer. In java 8 you can do this in one line. Arrays.stream(arr).forEach(s->System.out.print(s%10 > 0 ? s+" ":"\n"));