0

I've been writing code to get all combinations of elements from array, but I couldn't figure out how to do it. Can you guys give me some advice?

This is what I'm trying to do...

            int[] num = {1, 2, 3, 4, 5};
            int n = num.length;
            int length = (n * (n - 1)) / 2;
            int[] list = new int[length];

            for (int j = 0; j < n - 1; j++) {
                for (int p = 4;p < n; p--) {
                    for (int i = 0; (I < length); i++) {
                        list[i] = Math.abs(num[j] - num[j + p]);
                    }
                    p++;        
                }
            }

My result list would look like this..

list = {1, 2, 3, 4, 1, 2, 3, 1, 2, 1};

Thank you in advance.

edit: I'm really sorry that I didn't post my question clearly. What I was trying to do is get the absolute value of subtracting each values from array. ex) 1-2 , 1-3, 1-4, 1-5, 2-3, 2-4, 2-5, 3-4, 3-5, 4,5

for (int v : list) {
    System.out.println(v);
}

output: 1 2 3 4 1 2 ...

loone96
  • 723
  • 2
  • 13
  • 21

2 Answers2

0

For any value n the following should work. The key is to base the termination point of the inner loop on the outer loop's termination point.

System.out.println(string);
int n = 5;
int[] num = {1, 2, 3, 4, 5};
int length = (n * (n - 1)) / 2;

int m = 0;
int[] list = new int[length];
for (int i = 1; i<n ; i++) {
    for (int k = 1; k <= n-i; k++) {
        list[m++] = num[k-1];
    }
}
System.out.println(Arrays.toString(list));

Prints

1 2 3 4 1 2 3 1 2 1 
WJS
  • 36,363
  • 4
  • 24
  • 39
0

Do it as follows:

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[] num = { 1, 2, 3, 4, 5 };
        int n = num.length;
        int length = (n * (n - 1)) / 2;
        int[] list = new int[length];

        // Index counter for list[]
        int c = 0;

        for (int i = n - 1; i >= 0; i--) {
            for (int j = 0; j < i; j++) {
                list[c++] = num[j];
            }
        }

        // Display
        System.out.println(Arrays.toString(list));
    }
}

Output:

[1, 2, 3, 4, 1, 2, 3, 1, 2, 1]
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
  • Thank you! I'll try it again, but I was trying to get the absolute value of subtracting value from array. Sorry that I didn't specify what I want clearly. – loone96 May 21 '20 at 01:34
  • Finally, I solved my problem based on your answer. THANK YOU! – loone96 May 21 '20 at 03:46