Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find all possible pairs in an array

Tags:

java

recursion

Its when I try to do stuff like this I realise I really need to go to university!

Anyway I have an array of strings (275) I need to loop through them and create strings of all the possible pairs, in Java.

I've been learning about recursion but I cant find the answer for this.

like image 474
user169743 Avatar asked Mar 06 '10 13:03

user169743


People also ask

How do you find all possible pairs of an array?

In order to find all the possible pairs from the array, we need to traverse the array and select the first element of the pair. Then we need to pair this element with all the elements in the array from index 0 to N-1.

How do you find all pairs of elements in an array whose sum is equal to a given number?

Follow the steps below to solve the given problem: Initialize the count variable with 0 which stores the result. Iterate arr and if the sum of ith and jth [i + 1…..n – 1] element is equal to sum i.e. arr[i] + arr[j] == sum, then increment the count variable. Return the count.

How many pairs does an array have?

There can be a total of n(n - 1)/2 number of total pairs from the given array of numbers.


1 Answers

In case pairs ab and ba are different, do:

for i=0 to array.length
  for j=0 to array.length
    if i == j skip
    else construct pair array[i], array[j] 

and if not, do something like this:

for i=0 to array.length-1
  for j=i+1 to array.length
    construct pair array[i], array[j] 

Note that I am assuming the array holds unique strings!

like image 78
Bart Kiers Avatar answered Nov 03 '22 00:11

Bart Kiers