Get startedGet started for free

Implementing a social network

You're developing a social networking application that needs to analyze potential connections between users. You need to implement a method that generates all possible pairs of users from a list.

This exercise is part of the course

Optimizing Code in Java

View Course

Exercise instructions

  • For each index i, assign the ith user in elements as the first element of the pair.
  • For each index j, assign the jth user in elements as the second element of the pair.
  • Return the result with all your pairs.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

public class Main {
    public static void main(String[] args) {
        ConnectionAnalyzer analyzer = new ConnectionAnalyzer();
        
        String[] users = {"Alice", "Bob", "Charlie", "Diana"};
        
        String[][] allPairs = analyzer.generateAllPairs(users);        
        System.out.println("All possible connections:");
        for (String[] pair : allPairs) {
            System.out.println(pair[0] + " - " + pair[1]);
        }
    }
}

class ConnectionAnalyzer {
    public String[][] generateAllPairs(String[] elements) {
        int n = elements.length;
        
        int numPairs = n * (n - 1) / 2;
        String[][] pairs = new String[numPairs][2];
        
        int pairIndex = 0;
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
                // Add the first user to our pair
                pairs[pairIndex][0] = ____;
                // Add the second user to our pair
                pairs[pairIndex][1] = ____;
                pairIndex++;
            }
        }
        
        // Return the result
        return ____;
    }
}
Edit and Run Code