HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Find the number of times that the difference of array values are equal to the number

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
numberthearrayareequaldifferencethatfindvaluestimes

Problem

I wrote the following code to answer this, but I am wondering if there is any better approach.

For example

If the following array is given:

{10,21,34,45,56}


we should find the differentiate of each number with other values of the array and in case it is equals to 11 should increment the counter.

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

List a = new ArrayList();
       a.add(10);
       a.add(21);
       a.add(34);
       a.add(45);
       a.add(56);
      int number = 11;
      int counter = 0;
       for(int i=0;i<a.size();i++){
           for(int j=0;j<a.size();j++){
               if(j!=i){
                   int t = a.get(i) - a.get(j);
                   if(t == number){
                       System.err.println(a.get(i) +"-"+ a.get(j) + "=" + t);
                       counter++;
                   }
               }
           }
       }
       System.err.println(counter);
    }


Output

The application is correctly showing the results but I am wondering if there is any other approach to the above solution.

21-10=11
45-34=11
56-45=11
3

Solution

I think you should look at the problem in a different way and come up with a simpler solution.

Try thinking at having a set of elements. What you want to know is if there is any pair of elements such that a - b = x.

You're given x, so for a given value of a in your set you should check whether it also contains x + a.

Your implementation should first move the content of the list to a Set. Then you have to iterate through the set and for each element a check if the set contains also x + a. If it is true then you should add (a,b) to your solution.

In your example, x = 11. If you consider a = 10 you'll check if it contains 11 + 10 = 21. It does so you can the pair (21,10) is a valid solution. Conversely, when you consider a = 21, you obtain b = 32, which is not part of the set and therefore you have to discard that pair.

int checkDifferences(Set numbers, int difference) {
    int occurrences = 0;
    for (Integer number : numbers) {
        if (numbers.contains(number + difference)) {
            occurrences++;
        }
    }
    return occurrences;
}

Code Snippets

int checkDifferences(Set<Integer> numbers, int difference) {
    int occurrences = 0;
    for (Integer number : numbers) {
        if (numbers.contains(number + difference)) {
            occurrences++;
        }
    }
    return occurrences;
}

Context

StackExchange Code Review Q#63083, answer score: 7

Revisions (0)

No revisions yet.