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.
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 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;
}
I want to loop infinitely using a for loop if a number equals 0, and loop until that number number if the number is greater than 0. Here's the code to help visual what I'm getting at.
for (int i = 0; i < this.getNumRounds(); i++) {
// 30 some lines of code
}
or
for ( ; ; ) {
// 30 some lines of code
}
if getNumRounds() is greater than 0, do the first loop, if it equals 0, do the second. I would prefer to do this without copying and pasting my 30 some lines of code twice and using an if statement seeing as the code is redundant, though I could use a function to take out that redundancy, but I'm looking to see if there's another option.
Use the powerful ternary operator:
for (int i = 0; this.getNumRounds() == 0 ? true : i < this.getNumRounds(); i++) {
// 30 some lines of code
}
As noted in the comments by yshavit, there is a shorter, cleaner way of expressing this:
for (int i = 0; this.getNumRounds() == 0 || i < this.getNumRounds(); i++) {
// 30 some lines of code
}
Have you thought about using a while loop instead?
int i = 0;
while(i < this.getNumRounds() || this.getNumRounds() == 0) {
//some 30 lines code
i++
}
So you want something like this:
int num = //whatever your number equals
if (num == 0) {
boolean running = true;
while (running) {
doLoop();
}
} else {
for (int i = 0; i < num; i++) {
doLoop();
}
}
private void doLoop() {
//some 30 lines of code
}
This code puts the contents of the loop in a separate method and checks if the number is equal to 0. If it is, the program runs the doLoop() method forever. Otherwise, it runs until i equals the number.
While it would be better to just create a method and use an if-statement you could add an if statement inside the for-loop to decrease i every iteration. It would look like:
for (int i = 0; i <= this.getNumRounds(); i++) {
if(this.getNumRounds() == 0){
i--;
}
// 30 some lines of code
}
Notice I changed i < this.getNumRounds() to i <= this.getNumRounds. This way if the number of rounds is zero then the loop will be called.
You could do the following.
for (int i = 0; i < this.getNumRounds() || i == 0; ++i) {
do {
// 30 lines of code
} while (this.getNumRounds() == 0);
}
If getNumRounds is non-trivial to compute, consider pulling it out of the loop and calling it only once.
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;
}