2

For this Algorithm assignment in class I have to find all the unique values in a 1000x250 2D array.

The data is between 2000000 to 2200000. All the data is stored in a 2D int array called data.

The problem I am having is that it takes a bit of time to run this and my prof said we can't use other data sets and also we need to optimize our code so it runs at a good speed.

    int[] uniqueValues = new int[200000];
    boolean isUnique = true;
    int uniqueCounter = 0;

     for (int i = 0; i < data.length; i++) {

         for (int j = 0; j < data[i].length; j++) {

            for (int x = 0; x < uniqueCounter; x++) {

                if (data[i][j] != uniqueValues[x]) {
                    isUnique = true;
                } else {
                    isUnique = false;
                    break;
                }

            }

            if (isUnique) {
                uniqueValues[uniqueCounter] = data[i][j];
                uniqueCounter++;
            }

        }
}
4
  • 1
    This question should go to code review: codereview.stackexchange.com Commented Sep 20, 2015 at 0:28
  • 3
    "my prof said we can't use other data sets" - That doesn't make sense. Probably you have mistranslated it. What did he actually say? Commented Sep 20, 2015 at 0:37
  • You should use a Set. If you are not allowed to use the pre-defined Set implementation, then you should create your own Set data structure. Commented Sep 20, 2015 at 0:40
  • Also, did your "prof" say that you have to optimize it? 'Cos his (apparent) instructions to not create a separate data structure makes the obvious efficient solutions impossible. I suspect that he wants you to learn about arrays and loops in this exercise ... and this "make it go fast" is a non-requirement that you shouldn't be wasting your time one. Commented Sep 20, 2015 at 0:41

1 Answer 1

1

Well if you allocate 200000 ints for the result anyway, you can use them as counters for each value, then collect the ones that only occur once:

for (int i = 0; i < data.length; i++) {
  for (int j = 0; j < data[i].length; j++) {
    uniqueValues[data[i][j] - 2000000]++;
  }
}        

int uniqueCounter = 0; 
for (int i = 0; i < uniqueValue.length; i++) {
  if (uniqueValues[i] == 1) {
    uniqueValues[uniqueCounter++] = i + 2000000;
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

@rsutormin in that case, the value wouldn't be unique....
Right! I understood the task wrong.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.