dimanche 3 juin 2018

Why is hashset showing strange behavior?

I am trying to code a simple problem. Just for the clarification its, not an ongoing contest. Here is the code

    package Algorithms;

import java.util.HashSet;
import java.util.Scanner;

public class shino {
    public static void main(String args[]){
        Scanner sc = new Scanner(System.in);
        int a = sc.nextInt();
        int seq[]= new int[a];
        int count=0;
        for(int j=0;j<a;j++){
            seq[j] = sc.nextInt();
        }
        HashSet<HashSet> hashSets = new HashSet<>();


            for(int y=0;y<seq.length;y++){

                for(int u=0;u<seq.length;u++){

                    HashSet<Integer> hash = new HashSet<>();
                    int q =Math.abs(y-u);
                    if(y!=u && q==1 ) {

                        hash.add(seq[y]);
                        hash.add(seq[u]);
                    }
                    if(hashSets.add(hash)){
                        System.out.println(seq[y]+" "+seq[u]);
                        count++;
                    }
                }
            }
            System.out.println(count);

    }
}

Now as you can see there is a condition of y!=u but still when i give the input as

5
1 2 3 4 5

The output it yealds

1 1
1 2
2 3
3 4
4 5
5

Why is there a double 1 1 at top? I am not really getting what i am doing wrong here? To be honest, i do have some programming exp, but i really can't figure out why is this happening?

Aucun commentaire:

Enregistrer un commentaire