Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Identifying repeating numbers in a array

Tags:

java

algorithm

enter image description here

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]);

        }

    }

}
like image 732
user1010101 Avatar asked Feb 12 '23 17:02

user1010101


2 Answers

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
like image 139
Rod_Algonquin Avatar answered Feb 15 '23 11:02

Rod_Algonquin


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.
like image 37
Elliott Frisch Avatar answered Feb 15 '23 10:02

Elliott Frisch