3
public class Pascal {

    public static void main(String[] args){
    int array[] = {1,2,3,3,4,5,6,6,7,8,8,10,10,11,12,13};


    for (int i = 0; i < array.length; i++) {
            for (int j = 0; j < array.length; j++) {
                if (i == j){
                    System.out.println(i);
                } else {
                    System.out.println("Nothing");
                }
            }
        }
    }
}

It does't work properly. I tried to use foreach loop, but it didn't work as well. I think it's almost done and i missed something insignificant.

sodaluv
  • 449
  • 2
  • 9
  • 22
123qwe
  • 284
  • 4
  • 11

9 Answers9

2

Your problems

  • You are comparing i instead of array[i].
  • You are parsing the array twice hence every value gets displayed at least once, even if it is not a duplicate.

This would work but it still prints several times duplicate values:

int array[] = {1,2,3,3,4,5,6,6,7,8,8,10,10,11,12,13,13};

for (int i = 0; i < array.length; i++) {
  for (int j = 0; j < array.length; j++) {
    if (array[i] == array[j] && i != j){
      System.out.println(array[i]);
    }
  }
}

Now, I show you different styles to solve this problem.

A better solution in imperative style.

You are parsing the array n times which is useless. Provided that the array is sorted (you can sort it anyway), you can compare an element to the next one like in this solution :

int array[] = {1,2,3,3,4,5,6,6,7,8,8,10,10,11,12,13};

//Optionally
Arrays.sort(array);

Integer last = null;
for(int i = 0; i < array.length -1 ; i++) {
  if(array[i] == array[i+1] && (last == null || !last.equals(array[i]))) {
    System.out.println(array[i]);
    last = array[i];
  }
}

I think that this is the most efficient solution but not the most readable.

Another solution with a foreach loop

Unless you explicitly need to access the index of the current element, using a plain old for loop is evil because it introduces the unecessary variable i which pollutes the readability of the code.

You can prefer using a foreach statement :

int array[] = {1,2,3,3,3,4,5,6,6,7,8,8,10,10,11,12,13,13};

Set<Integer> uniqueValues = new HashSet<>();
Set<Integer> alreadyDisplayed = new HashSet<>();
for(Integer value : array) {
  if(uniqueValues.contains(value) && !alreadyDisplayed.contains(value)) {
    System.out.println(value);
    alreadyDisplayed.add(value);
  }
  uniqueValues.add(value);
}

A better solution in functional style.

This solution which is more Java8-friendly :

int array[] = {1,2,3,3,4,5,6,6,7,8,8,10,10,11,12,13};

//Count occurrences of each number
Map<Integer, Integer> map = new HashMap<>();
Arrays.stream(array).forEach(value -> {
  Integer occurrences = map.get(value);
  map.put(value, occurrences == null ? 1 : occurrences +1);
});

//Display number of occurrences when nbOccurrences > 1
map.entrySet()
    .stream()
    .filter(entry -> entry.getValue() > 1)
    .forEach(entry -> System.out.println(entry.getKey() + " : "+entry.getValue()));

Note that it also gives the number of occurrences for each value. If you don't need them, you can shorten the code like in previous solutions.

A funnier solution in logical style.

Integer array[] = {1,2,3,3,4,5,6,6,7,8,8,10,10,11,12,13};

//Convert the array to a list.
List<Integer> list = Arrays.stream(array).collect(Collectors.toList());

//Use a Set in order to build the collection of unique values.
Set<Integer> uniqueValues = new HashSet<>(list);

//Remove each unique value once from the original list.
uniqueValues.stream().forEach(list::remove);

//Re-compute unique values of the resulting list and display them.
new HashSet<>(list).forEach(System.out::println);
Arnaud Denoyelle
  • 29,980
  • 16
  • 92
  • 148
1

Replace "if (i == j)" with "if (array[i] == array[j])"

Jithu
  • 111
  • 3
  • 11
1
  • First of all, you should be comparing array[i] to array[j], not i to j.

  • Second of all, if i == j, you shouldn't compare an element to itself.

For example :

for (int i = 0; i < array.length; i++) {
    for (int j = i + 1; j < array.length; j++) {
        if (array[i] == array[j]) {
            System.out.println(array[i]);
        }
    }
}

This will print the duplicate values.

Eran
  • 387,369
  • 54
  • 702
  • 768
1

You should compare elements inside the array, not array indexes. Also when indexes are the same then the number is not repeated, it's just the same number.

for (int i = 0; i < array.length; i++) {
    for (int j = 0; j < array.length; j++) {
        if ((array[i] == array[j]) && (i != j)) {
            System.out.println(array[i]);
        }
    }
}
Keammoort
  • 3,075
  • 15
  • 20
1

If you want use more space for creating a Set object

Set<Integer> set = new HashSet<Integer>;
for (int i = 0; i < array.length; i++) {
    boolean wasAdded = set.add(i);
    if(!wasAdded){
    System.out.println(array[i]);
    }
}
Than
  • 2,759
  • 1
  • 20
  • 41
  • 1
    Why not using a Java 7's foreach? Having to manage `i` manually is unecessary. And btw, I think that it introduced a bug in the code because you need to do `set.add(array[i])`, not `set.add(i)`. – Arnaud Denoyelle Dec 14 '15 at 13:49
  • Well, I've copied that line from question. – Than Dec 14 '15 at 13:54
0

You are using brute method to do that.

for (int i = 0; i < array.length; i++) {
        for (int j = i+1; j < array.length; j++) {
            if (array[i] == array[j]){
                System.out.println(i);
            } else {
                System.out.println("Nothing");
            }
        }
    }
}
Kulbhushan Singh
  • 627
  • 4
  • 20
0

another possibility is to use a Map to count all entries exactly:

public class Pascal {

  public static void main(String[] args) {
    int array[] = { 1, 2, 3, 3, 4, 5, 6, 6, 7, 8, 8, 10, 10, 11, 12, 13 };

    Map<Integer, Integer> lAllDoubleEntries = new HashMap<Integer, Integer>();

    for (int i = 0; i < array.length; i++) {
      Integer count = lAllDoubleEntries.get(array[i]);
      if (null == count) {
        lAllDoubleEntries.put(array[i], 1);
      } else {
        lAllDoubleEntries.put(array[i], ++count);
      }
    }
    for (int lKey : lAllDoubleEntries.keySet()) {
     if (lAllDoubleEntries.get(lKey)>1) {
       System.out.println("Value "+lKey+" exists in list "+lAllDoubleEntries.get(lKey)+" times");
     }
    }

  }
}

Output:

Value 3 exists in list 2 times

Value 6 exists in list 2 times

Value 8 exists in list 2 times

Value 10 exists in list 2 times

nano_nano
  • 12,351
  • 8
  • 55
  • 83
  • If you you want to use `Map` to map `Integer` to `Object` consider using `SparseArray` to improve performance. – Than Dec 14 '15 at 13:43
0

Solution using Set.

A collection that contains no duplicate elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element.

    int[] myArr =  {1,2,3,3,4,5,6,6,7,8,8,10,10,11,12,13};
    Set<Integer> mySet = new HashSet<>();

    for (int i = 0; i < myArr.length; i++) {
        if (!mySet.add(myArr[i])) {
            System.out.println(myArr[i]);
        }
    }
0

Algo Explained duplicate-entries-with-4kb-constraint-bit-array-is-the-solution
public static void main(String args[]){ int input[] = new int[ /* pick a size / ]; input[0] = / fill the array */ int[] isDuplicate = new int[32000 >> 5]; // divide by 32 int wordNumber, mask;

    for(int i = 0; i < input.length; i++ ){
            mask = 1 << (input[i]%32);
            wordNumber = input[i]/32;
            if((mask & isDuplicate[wordNumber]) != 0){
                    System.out.println(input[i]);
            }else{
                    isDuplicate[wordNumber] |= mask;
            }
        }
   }
T-Bag
  • 10,916
  • 3
  • 54
  • 118