-2

Here's my code:

Scanner s = new Scanner(System.in);
int t = s.nextInt();
String [] pair_left = new String[t];
String [] pair_right = new String[t];

for (int i = 0; i < t; i++) {
    pair_left[i] = s.next();
    pair_right[i] = s.next();
}
HashSet hs1=new HashSet();
HashSet hs2=new HashSet();
int j=0;
for(int i=0;i<t;i++){
    if(hs1.add(pair_left[i])||hs2.add(pair_right[i])){
      j++;
      System.out.println(j);
    }
    else {      
       System.out.println(j);
    }
}

and the input is :

5
john tom
john mary
john tom
mary anna
mary anna

now when i=2 then hs1.add(pair_left[i]) returns false and then it goes to hs2.add(pair_right[i])which also return 'false'so hs1.add(pair_left[i])||hs2.add(pair_right[i]) should return 'false' but in my case it shows true. Why?

And when I replace logical OR with bitwise OR then it shows correct result. If there any better approach of doing this then give that also.

Jatin Bansal
  • 171
  • 2
  • 10

1 Answers1

1

You should be aware that || logical OR is short circuited, so if hs1.add(pair_left[i]) returns true, hs2.add(pair_right[i]) is not evaluated.

On the other hand, as you noticed, when you use |, which is non-short circuited logical OR (note that | is not only bitwise OR), both operands are always evaluated.

Eran
  • 387,369
  • 54
  • 702
  • 768
  • but if hs1.add(pair_left[i]) returns false then it evaluates hs2.add(pair_right[i]) which is also false then hs1.add(pair_left[i])||hs2.add(pair_right[i]) should return false but in my case it returns true why? – Jatin Bansal Jul 25 '16 at 12:12
  • @JatinBansal In the first iteration (i==0), `hs1.add(pair_left[i])` returns true (since the Set was empty), so `hs2.add(pair_right[i])` is not evaluated. Therefore when i==2, `hs1.add(pair_left[i])` returns false but `hs2.add(pair_right[i])` returns true (since tom wasn't added in the first iteration). – Eran Jul 25 '16 at 12:15
  • ok thanks i got it – Jatin Bansal Jul 25 '16 at 12:18