0

I've already written the code for this, but it didn't work. If it had worked, the run time complexity would have been very high.

for (int collumnInput=0; collumnInput < 3; collumnInput++)
        {
            for (int rowInput = 0; rowInput < 3; rowInput++)
            {
                try
                {
                    puzzleArray[collumnInput][rowInput] = scan.nextInt();

                    if ((puzzleArray[collumnInput][rowInput] > 8) || (puzzleArray[collumnInput][rowInput] < 0))
                    {
                        System.out.println("Invalid 8-puzzle entered!");
                        System.exit(0);
                    }
                    for (int collumnCheck = 0; collumnCheck < collumnInput; collumnCheck++)//code to check for duplicates starts here.
                    {
                        for (int rowCheck = 0; rowCheck < rowInput; rowCheck++)
                        {
                            if (puzzleArray[collumnCheck][rowCheck]==puzzleArray[collumnInput][rowInput])
                            {
                                System.out.println("Invalid 8-puzzle entered!");
                                System.exit(0);
                            }
                        }
                    }

                }
                catch (java.util.InputMismatchException exception)
                {
                    System.out.println("Invalid 8-puzzle entered!");
                    System.exit(0);
                }

            }
        }
        scan.close();

First of all, the code here runs, but doesn't detect duplicates in the array, so how do I fix that? The second thing is, is there a more resource efficient method of doing this? I have seen people use clone and copy methods, but I don't know if those are actually more resource efficient. Thanks.

cluemein
  • 884
  • 13
  • 27

1 Answers1

2

To answer the question in the title, I would do it in one line:

Integer[] array; // given this type of array
boolean hasRepeats = new HashSet<Integer>(Arrays.asList(array)).size() != array.length;
Bohemian
  • 412,405
  • 93
  • 575
  • 722
  • sorry did not you mean hashmap? – Kick Buttowski Sep 30 '14 at 02:43
  • 1
    @KickButtowski [HashSet](http://docs.oracle.com/javase/7/docs/api/java/util/HashSet.html) is correct – Pham Trung Sep 30 '14 at 02:43
  • 1
    @PhamTrung if you claim something, please provide some explanation if you are capable of :) – Kick Buttowski Sep 30 '14 at 02:44
  • @KickButtowski he just used a hashSet to count number of distinct elements, and if the number of distinct element equals length of array, so problem solved – Pham Trung Sep 30 '14 at 02:47
  • Using HashSet class will ensure that every element in the set is unique. If there are duplicated elements in the array, only one of them will be reserved. After that, obviously the length will be decreased. –  Sep 30 '14 at 02:49