I am not sure why I am returning false for the first test run as shown in the test table attachment. This was one of my assignments last semester and I never figured out how to solve it:/ My assignment was to:
Write the definition of a method , oddsMatchEvens, whose two parameters are arrays of integers of equal size. The size of each array is an even number. The method returns true if and only if the even-indexed elements of the first array equal the odd-indexed elements of the second, in sequence. That is if w is the first array and q the second array , w[0] equals q[1], and w[2] equals q[3], and so on.
Test table
My code was:
public boolean oddsMatchEvens(int[] w, int[] q) {
int count = 0;
for (int i = 0; i < w.length; i++) {
if (w[i] == q[i + 1])
count++;
if (count == (w.length - 1))
return true;
}
return false;
}
if (count == (w.length - 1))
return true;
This is wrong, since you have only w.length/2 indices which you have to compare.
You should just return false, if w[i] != q[i+1].
And you should increase i by 2, not by 1.
There are two problems with the code:
Firstly, it is clearly mentioned the two input arrays are of equal length and you have to compare them even index to odd index. So the corner case occurs when you are checking last item of first array with last+1 item of second array(which doesn't exist as arrays are of equal length.
Secondly, you have to check first array even with second array odd so increment should be i+=2 and not i++.
Correct code with optimization(if one check fails you can come out of loop):
public boolean oddsMatchEvens(int[] w, int[] q) {
for (int i = 0; i < w.length-1; i+=2) {
if (w[i] != q[i + 1])
return false;
else
continue;
}
return true;
}
public boolean oddsMatchEvens (int []w, int []q) {
for (int j = 0; j < w.length-1; j+=2) {
if (w [j] != q [j+1])
return false;
continue;
}
return true;
}
Related
So I am having trouble trying to find duplicates in an array where a user enters the numbers. I want to display a dialog when they enter a number that is already in the array. It sounds simple but is confused on how to go on about this.
//Convert the string into an int
num = Integer.parseInt(inputField.getText());
// Add it to the an index
array[index] = num;
// Increment the index variable
index++;
// If the the duplicate exists
for(int i = 0; i < array.length;i++){
if(array[index] == num){
if(array[i - 1] == num){
JOptionPane.showMessageDialog(null,"Array may not contain duplicates ","Array Duplicate",JOptionPane.ERROR_MESSAGE );
break;
}
}
}
Trying to fix your code here
//Convert the string into an int
num = Integer.parseInt(inputField.getText());
boolean exsist = false;
// If the the duplicate exists
for(int i = 0; i < array.length;i++){
if(array[i] == num){
exsist = true;
JOptionPane.showMessageDialog(null,"Array may not contain duplicates ","Array Duplicate",JOptionPane.ERROR_MESSAGE );
break;
}
}
if(!exsist)
{
// Add it to the an index
array[index] = num;
// Increment the index variable
index++;
}
something like this should work
The reasoning is
not using the variable i from the for loop, this results in checking the same value all the time
the checks in the if statements are broken, the checks simply don't make sense, try to use the ior other variables that change each loop to check multiple values
there is no need to add the value before testing if it exsist, if you do so you will have to remove it after, doing it after therefore result in a faster code (even if only very very little) and a safer code since you can't fail to delete the value
After some thinking and some suggestion. I managed to solve it.
// Set orginal to true
boolean orginal = true;
//Convert the string into an int
num = Integer.parseInt(inputField.getText());
// Loop to find the duplicate
for(int i = 0; i < array.length; i++){
// Check if there's a duplicate
for(int j = 0; j < array.length; j++){
// Check if the num is equal to any of the numbers in the array
if(array[j] == num){
// Set orginal to false
orginal = false;
// Throw the duplicate exception
throw new DuplicateValueException(result);
}
}
// If there is no duplicates
if(orginal){
// Add the number to the array
array[index] = num;
// Break out the loop
break;
}
}
// Print the message
System.out.println("array["+index+"] = "+ num);
// Increment the index variable
index++;
for(int i = 0; i < array.length-1;i++){
if(array[i] == num){
JOptionPane.showMessageDialog(null,"Array may not contain duplicates ","Array Duplicate",JOptionPane.ERROR_MESSAGE );
break;
}
}
Try this!
But your code will add that number to array anyway as you are adding it before checking it.
This code makes no sense :
// Add it to the an index
array[index] = num;
// Increment the index variable
index++;
for(int i = 0; i < array.length;i++){
if(array[index] == num){
You add the num int at the index index of the array and then in the loop you want to check if index+1 == num.
In your logic you should rather check if index == num.
And anyway it is useless, you have done : array[index] = num;.
So if(array[index] == num) can be only true.
I want to display a dialog when they enter a number that is already in
the array
You should rather do the check of duplication number before adding it in the array.
The general idea would be iterating the array and if during the iteration, a element of the array is equals to num, you have not add num.
In the contrary case, if no element is equals to num, you have to add it.
It seems to be a school working, so I will not detail further the solution.
I think this will work for sure even for the case of [5->5]
index++;
// If the the duplicate exists
if (index > 0) {
for (int i = 0; i < array.length; i++) {
if (array[i] == num) {
JOptionPane.showMessageDialog(null, "Array may not contain duplicates ", "Array Duplicate", JOptionPane.ERROR_MESSAGE);
break;
}
}
}
I'm doing a problem on codingbat.com and am confused with why this solution to the problem does not give an index out of bounds error. Wouldn't the first for loop search for an index that is beyond the length of the passed array?
Here's the problem:
We'll say that a value is "everywhere" in an array if for every pair of adjacent elements in the array, at least one of the pair is that value. Return true if the given value is everywhere in the array.
Here's my working solution:
public boolean isEverywhere(int[] nums, int val) {
boolean flag1 = true;
boolean flag2 = true;
for (int i = 0; i < nums.length; i += 2) {
if (nums[i] != val) flag1 = false;
}
for (int i = 0; i < nums.length - 1; i += 2) {
if (nums[i + 1] != val) flag2 = false;
}
return flag1 || flag2;
}
Thanks!
No. The test happens after i is incremented. So, once i is not less than the length of the nums array the loop stops. The second loop uses i + 1 at if (nums[i + 1] != val) which is why it needs to test that i is less than the length minus one.
Also you can make the method static (since it uses no instance state).
It wouldn't because while i += 2 is written after i < nums.length, the loop still checks that i is less than the given length(nums.length) before going onto the body of the loop even after 2 has been added on.
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");
In the second if statement when I'm comparing values[i] and values[secondIdx], why doesn't this cause an error seeing as secondIdx is equal to -1?
public static int getSecondMinIndex(int[] values) {
int secondIdx = -1;
int minIdx = getMinIndex(values);
for (int i = 0; i < values.length; i++) {
if (i == minIdx)
continue;
if (values[i] < values[secondIdx] || secondIdx == -1)
secondIdx = i;
}
return secondIdx;
}
The only ways this would not throw an error at runtime is if you passed an empty array as a method argument, in which case the for loop would not execute. Also, as Bhesh suggests, if the array has one element and the minIdx is that first element at index 0, the loop will execute once, enter the first if and continue. It will stop looping right after that. That would also not cause the exception.
Write Java code for a loop that sets boolean variable isOrdered to true if the elements of a given array of ints called are in non-decreasing order, otherwise it sets isOrdered to false.
int i[] = { 1, 2, 3, 4, 5 };
int b = 0;
boolean isOrdered = false;
while (b < i.length) {
if (i[0] <= i[b]) {
isOrdered = true;
}
b++;
}
out.println(isOrdered);
Am I doing this correctly?
Let's see what is wrong.
if (i[0] <= i[b])
This is the main area which troubles me with your code. How are you checking if the next value you is lower/higher then i[b] you are only comparing values at index zero to index b!
Essentially your code would look like this in a loop.
/w int i[] = { 1, 2, 3, 4, 5 };
i[0] i[b]
1 1
1 2
1 3
...
you get the picture right? What you really need is to check the next value after b.
so the code would look like i[b] > i[b+1]
Honestly, you could probably make it work on how you initialized the order of isOrdered to true and false. I would first initialize it to true. Then the idea is to break out of whatever process you are doing if you find a fallacy in the question with a false. Please look at my examples for further references.
iterative
boolean isOrdered = true;
while(isOrdered && array.length - 1 > b){
if(array[b] > array[b+1]) isOrdered = false;
b++;
}
recursive
boolean isOrdered(int[] array, index){
if(index == array.length - 1) return true;
if(array[index] > array[index + 1]) return false;
return isOrdered(array, index + 1);
}
The recursive method for this is waaaaaaaaaay cooler.
No; you are only checking whether the first element of the array is smaller than or equal to at least one of the elements - including the first element itself, which will always be equal to itself, setting isOrdered to true no matter what the remaining elements are.
Hint #1: you should be comparing every element except the first one with the element immediately before it.
Hint #2: you should be optimistic and assume that the array is ordered, then search for a counter-example. As soon as you found a pair of elements that violate the ordering, set isOrdered to false and break out of the loop.
do a for loop on the size of the array to check if the next item is less then the current:
int arr[] = { 1, 2, 3, 4, 5 };
int b = 0;
boolean isOrdered = true;
for (int i = 0; i< arr.length - 1 ; i ++) {
if (arr[i] > arr[i+1])
{
isOrdered = false;
break;
}
b++;
}
out.println(isOrdered);