I am dealing with the following problem. I am not looking for anyone to provide me a solution i am looking for some guidance to solving this problem. Here is what i have come up with so far.
I have basically tried to first put a ( around values that repeat. However i am getting a out of bounds error. I would really appreciate it if someone can push me towards the right path for coding a small algorithm that would handle this problem.
My code (in progress)
import java.util.Random;
public class Test {
public static void main(String[] args) {
int[] values = { 1, 2, 5, 5, 3, 1, 2, 4, 3, 2, 2, 2, 2, 3, 6, 5, 5, 6,
3, 1 };
boolean inRun = false;
for (int i = 0; i < values.length; i++) {
if (values[i] == values[i + 1] && values[i + 1] < values.length) {
System.out.print("(");
}
System.out.print(values[i]);
}
}
}
You need to iterate to all the array and if it found a pair then you iterate it again in a while loop until it find the non pair.
sample:
int[] values = { 1, 2, 5, 5, 3, 1, 2, 4, 3, 2, 2, 2, 2, 3, 6, 5, 5, 6, 3, 1 };
boolean inRun = false;
for (int i = 0; i < values.length; i++) {
if (i + 1 < values.length && values[i] == values[i + 1] )
{
System.out.print("(");
while (i + 1 < values.length && values[i] == values[i + 1] )
{
System.out.print(values[i++]);
}
System.out.print(values[i++]);
System.out.print(")");
}
System.out.print(values[i]);
}
result:
12(55)31243(2222)36(55)631
Your error is here,
if (values[i] == values[i + 1] && values[i + 1] < values.length) {
Because i + 1
isn't being tested for less then, or in the correct order -
if (i + 1 < values.length && values[i] == values[i + 1]) {
Or you could use,
for (int i = 0; i < values.length - 1; i++) { // the length of values - 1 so we can
// get the next value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With