1
\$\begingroup\$

This question is follow-up to this question.

Sample Calculation

10-21=-11
10-34=-24
10-45=-35
10-56=-46
21-10=11     <
21-34=-13
21-45=-24
21-56=-35
34-10=24
34-21=13
34-45=-11
34-56=-22
45-10=35
45-21=24
45-34=11   <<
45-56=-11
56-10=46
56-21=35
56-34=22
56-45=11   <<<

Code

Set<Integer> tchars = new HashSet<>();
        tchars.add(10);
        tchars.add(21);
        tchars.add(34);
        tchars.add(45);
        tchars.add(56);
        int number = 11;
        int counter = 0;

        Iterator it = tchars.iterator();
        while (it.hasNext()) {
            Integer inte = (Integer) it.next();
            if (tchars.contains(inte + number)) {
                System.err.println(inte + " " + number);
                counter++;
            }
        }
        System.err.println(counter);
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

Using a Set is problematic.

First, as pointed out on the original question in @Vogel612's comment, it restricts duplicate values. Second, it also makes your code a lot messier, as you're now grabbing an Iterator, calling .hasNext(), and testing in a while loop instead of using more concise syntax.

I'd just use a List<Integer>, get rid of all the casts, and use a for-each style syntax instead of using the Iterator. Finally, number and counter aren't very meaningful as variable names in the context of this snippet. If they are meaningful in the wider context of wherever this came from so-be-it, but I find something more along the lines of difference and result much clearer.

Something more like this:

List<Integer> tchars = Arrays.asList(10, 21, 34, 45, 56);
int difference = 11;
int result = 0;

for (int test : tchars) {
    if (tchars.contains(test + difference)) {
        System.err.println(test + " " + difference);
        result++;
    }
}

System.err.println(result);

Dead simple, and you can see immediately what it is doing.

\$\endgroup\$
5
  • 1
    \$\begingroup\$ What is a complexity of tchars.contains()? \$\endgroup\$
    – vnp
    Sep 17, 2014 at 5:58
  • \$\begingroup\$ This code doesn't work, try it on 10, 10, 21, 34, 45, 56 for example. \$\endgroup\$
    – mjolka
    Sep 17, 2014 at 10:39
  • \$\begingroup\$ @mjolka Good catch on the sign, fixed. \$\endgroup\$
    – Comintern
    Sep 17, 2014 at 12:26
  • \$\begingroup\$ @vnp - Time complexity is linear, "roughly speaking". \$\endgroup\$
    – Comintern
    Sep 17, 2014 at 12:31
  • 2
    \$\begingroup\$ Using List.contains is not a very good suggestion for performance. The overall complexity of this code is O(n^2). It is possible to do a O(n) solution. \$\endgroup\$ Sep 17, 2014 at 17:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.