I'm writing an algorithm that compares a number n with elements n+1 and n-1.
This means that the first and last check fail because array.length + 1 would be out of bounds and so would array[0-1]. I'm trying to find a way to stop the program from throwing the array index out of bounds exceptions but I am not sure how to do this. My initial plan was to check that array[0-1] and length+1 are always null like so:
numbers[x-1] == null
But this doesn't work because of a mismatch from int to null. Any ideas on how to remedy this would be very appreciated.
Iteration starts with index 1 and ends with index array.length - 1.
for(int i=1;i<array.length-1;i++){
int prev = array[i-1];
int current = array[i];
int next = array[i+1];
}
I'd just a checks for the edges of the array :
int prev = -1;
int next = -1;
for (int i=0; i<array.length; i++) {
if (i>0)
prev = array[i-1];
if (i < array.length - 1)
next = array[i+1];
else
next = -1;
// now do whatever you wish to do with array[i], prev and next
}
In that case I chose -1 to represent a "null" value. You can use something else, depending on the range of the values that can be in your array.
You should use "if" statements to check that your index is within the bounds:
if (x >= 0 && x < numbers.length)
numbers[x] = someNumber
Besides the length checks the other answers suggest, you also could create the array one element bigger, so that the last element n+1 is still a valid array position but marks the end of the array. This way you can forget all the length checks which would improve the speed of your algorithm - if this is important. Otherwise I would implement a length check.
Something you could use to compare arrays with last and next element:
for(int index=1;index<array.length-1;index++){
if (number > numbers[index - 1] && number < numbers[index + 1]) {
System.out.println("Number is between " + (index - 1) + " and " + (index + 1));
}
}
Related
Is there anyway I can use some boolean expression to see if what I want to access is out of bounds?
The correct boolean expression to check if an index is out of bounds for array array is:
index < 0 || index >= array.length
As in:
if (index < 0 || index >= array.length) {
System.out.println("Index is out of bounds");
}
if you have array like this(int[] a = new in[10]) you can test it like
if(index < a.length)
or if you have ArrayList<Integer> b = new ArrayList<Integer>(); you can test it like
if( index < b.size())
Use array.length to find the length of the array and then compare your index with array.length (it should be less than length of array and greater or equal to 0).
As the index surpasses length java gives you exception(ArrayIndexOutOfBounds Exception).
//let i be the index
if(i >= array.length || i<0)
//you will get an error
You can always check if the index you are trying to use can be accessed by doing this:
if(index >= 0 and index <= array.length−1) //This checks to see if the index you are going to use is greater or equal to 0 (since you cant access a negative index) and make sure it is less than the maximum size of the whole array)
The purpose of this method is to return the position (subscript index) of the largest element in the array (not its value, but its position). If the same maximum value appears more than once in the array, then it should return the position of the first or earliest on. If the array has no elements it should just return -1.
The solution:
public static int maxPos(int[] arr) {
int pos = 0;
if(arr.length > 0 ) {
for(int i = 0; i < arr.length; i++) {
if(arr[i] > arr[pos]) {
pos = i;
} else {
pos = - 1;
}
}
return pos;
}
I understand setting up a dummy variable "pos" to represent the index position of the maximum value of the array. And having the check point with if(arr.length > 0) then proceed. And the for-loop to sift through the entire array checking one-by-one which index has the greatest number value and after each iteration either re-assigning dummy variable or carrying onward.
The part where I get lost is when using things within the array [ ]'s, it throws me off. I don't think anywhere else in java there is such notation. For example with arrayList wouldn't that just be nameOfAL . get();
So the equivalent of that for an array is using the []'s?
I am a bit confused by arr[i] > arr[pos].
Is this to say when we are at the i'th index in the for-loop, we can then use arr[] and put something within that box, and when we do it outputs the value of that index. So anytime we put something within that array box it's always going to output an index position? is that the purpose of putting things inside the [] box? it will output the value of whatever is put inside it's brackets.
the next part that confuses me is why pos = i?
I understand if the if-statement fails then the else is - 1. but why return pos; after each iteration?
Thank you
Your posted code contains a few bugs, you should start with pos at -1 (instead of resetting it when a given value isn't greater then the current max). Also, I would check for null. Then you can start your loop with the second element. Something like,
public static int maxPos(int[] arr) {
int pos = -1; // <-- indicates no elements.
if (arr != null && arr.length > 0) {
pos = 0; // <-- there is at least one element.
for (int i = 1; i < arr.length; i++) {
if (arr[i] > arr[pos]) {
pos = i; // <-- update the max position
}
}
}
return pos;
}
First, so what you're putting in the square braces are variables named i and pos that hold the values of the numerical positions you're accessing in the array. It's like the get method of the arrayList class like that.
It's not returning pos until it finishes the for loop. In general it's returning pos because that's the index of the largest number, which is the point of the program. I think you're just missing a bracket somewhere, you have 5 {'s and 4 }'s.
I am trying to iterate through a randomly generated 2d array of 0s, and 1s. In this method which I am stuck on I am trying to see if the subdiagonal has all the same numbers, all 1s, all 0s, or different numbers.
sub diagonal meaning:
110
101
011
The 0s are the subdiagonal.
this is the code I have as of now. I am trying to iterate starting at the last row and counting up to the first row diagonally.
int firstValue= matrix[matrix.length-1][0];
int result = -1;
for(int row = matrix.length-1; row > 0; row--)
{
int column = row;
if(firstValue == matrix[row][column])
{
result = firstValue;
continue;
}
else
{
result = -1;
break;
}
}
if(result== 1)
{
System.out.println("All " + firstValue + "s on the subdiagonal");
}
else if (result == 0)
{
System.out.println("All " + firstValue + "s on the subdiagonal");
}
else
{
System.out.println("Numbers on subdiagonal are different");
}
}
I'm almost certain my issue is with the firstValue and/or the for loop counting up the diagonal.
Any help would be appreciated, thanks much
Your issue seems to be at the following line,
for(int row = matrix.length-1; row > 0; row++) {
...
}
you are doing a
row = matrix.length-1; // row = array length - 1
row++ //this will increase the row's value beyond your array length
Then you will be accessing a index that does not exist causing a ArrayIndexOutOfBoundsException
Edit
what you'd want to do is,
for(int row = matrix.length-1; row >= 0; row--) {
....
}
This way you'd be able to iterate though your array from largest index to the smallest (0).
Edit 2
Let's say Staring array called arr has 4 elements. It'll be structured as below,
arr[0] = "test1";
arr[1] = "test2";
arr[2] = "test3";
arr[3] = "test4";
Array indexes always starts from 0, so the highest index in the above array is 3.
So if you want to iterate from smallest index to the largest, you'd do
for(int i = 0; i < arr.length; i++) {
//i's initial value is 0 and itll increment each time the loop runs
//loop will terminate when i is no longer < 4
System.out.println(arr[i]);
}
and to iterate through the array in reverse order you'd do,
for(int i = (arr.length - 1); i <= 0; i--) {
//i's initial value is (4 - 1) and it'll decrement each time the loop runs
//loop will terminate when i smaller or equal to 0
System.out.println(arr[i]);
}
So we want to check if all of the values in the subdiagonal are the same value, and if they are then we want to print the value that is the same. First we set aside a comparison to check the other indices
int checkValue = arr[0][arr[0].length-1];
This is the last value in the first row. Then we set a flag to catch whenever our index that we are checking matches our first value. We'll set it to false because we'll assume that the values don't match.
boolean flag = false;
Now that we have that, we need to iterate through each row in our array. We will start with the second row (arr[1]) and then we need to check the value one down and one over compared to the last value we checked (arr[1][arr.length - 1 - i]). If our first value (we assigned it's value to checkValue) and the value we are checking are the same, change the flag to true.
for (int i = 1; i < arr.length; i++)
if (arr[i][arr.length - 1 - i] != checkValue)
flag = true;
That'll run through all of the rows in the array. Now we have to check the state of our flag and print out the appropriate response. If the flag is true, print out that the values on the row are the same. Else we will say that the subdiagonal does not match all the way through.
if (!flag)//remember our flag is set to false, double negative equals true.
System.out.println("All of the values on the subdiagonal are the same");
else
System.out.println("All of the values on the subdiagonal are not the same");
I'm fairly new to java so I would like to keep it simple, and I figure I would have to take the first value of the array then compare it to each following value and if the value is larger smaller than the first, replace the value with it, but I don't know how to get index from that.
For an unstructured, unsorted array the best you can do, assuming you are only going to find the minimum value once, is a simple iteration over all elements (O(n) complexity), like so:
public int findMinIdx(int[] numbers) {
if (numbers == null || numbers.length == 0) return -1; // Saves time for empty array
// As pointed out by ZouZou, you can save an iteration by assuming the first index is the smallest
int minVal = numbers[0] // Keeps a running count of the smallest value so far
int minIdx = 0; // Will store the index of minVal
for(int idx=1; idx<numbers.length; idx++) {
if(numbers[idx] < minVal) {
minVal = numbers[idx];
minIdx = idx;
}
}
return minIdx;
}
Also, in the case of a tie for minimum value, this method will return the index of the first case of that value it found. If you want it to be the last case, simply change numbers[idx] < minVal to numbers[idx] <= minVal.
Here is with Java 8
public static int findMinIdx(int[] numbers) {
OptionalInt minimun = IntStream.of(numbers).min();
return IntStream.of(numbers).boxed().collect(toList()).indexOf(minimun.getAsInt());
}
Never cared about run time optimization, was just looking for a solution!, this worked and this would help you too, finding the index of the lowest values in an array.
// array[] -> Received the array in question as an parameter
// index -> stores the index of the lowest value
// in for loop, i is important to complete all the comparison in the function
// When it finds a lower value between the two, it does not change the index
// When it finds a lower value it changes it's index to that index
// If array has same value more than once, it will provide index to that values last occurrence
// Correct me if you find anything not working in this example...
//...
private static int index_of_minimum_value(int[] array) {
int index = 0;
for (int i = 1; i < array.length; i++) {
if ((array[i - 1] < array[i]) && ([index] > array[i - 1])) index = i - 1;
else if (array[index] > array[i]) index = i;
}
return index;
}
I ve got an issue with the ArrayIndexOutofBound error when trying to determine whether data is heap following the 2i + 1/2 formula child-parent relationship. Do you know how can I resolve the issue?
for (int i = 0; i < array.length; i++)
{
if ((array[i] < array[2*i + 1]) || (array[i] < array[2*i + 2]))
{
bool = false;
....
}
}
I would suggest checking for the boundaries of the array first, and if it contains enough elements, then you can compare them:
if ((array.length >= 2*i + 2)
&& ((array[i] < array[2*i + 1]) || (array[i] < array[2*i + 2])))
{
bool = false;
....
}
Your for-loop guard allows i == array.length -1. But inside the loop, you look for element 2 * i + 2. That's 2 * array.length. That's way beyond the end of the array, and will always throw an excpetion (except when i == 0).
Change your for-loop guard to i < ((array.length / 2) - 1), so that the maximal value of 2 * i + 2 is array.length - 1. Also, ensure you test this both for arrays of even and odd length; I think the logic will work in only one case.