How to change `List` to `List of tuple` in java

Catalina :

I am using the below function to converting the sublists of list to 0 and the rest elements to 1 however i am trying to change the data structure to list of tuple.

for example the function provide for the input [1,2,3,5,10] to [0,0,0,1,1]. how can i convert this data structure to get the following output like this: [(0,1),(0,2),(0,3),(1,5),(1,10)] ? Or maybe to another similar data-structure if possible? like list of two element arrays

public static void main(String[] args) {
    int[] arr = { 1, 8, 1, 9, 10 };

    // assume arr.length >= 2
    boolean asc = arr[1] - arr[0] == 1;
    for (int i = 1; i < arr.length - 1; i++) {
        if (arr[i + 1] - arr[i] == 1) {
            arr[i] = 0;
            asc = true;
        } else {
            if (asc) {
                asc = false;
                arr[i] = 0;
            }
            else {
                arr[i] = 1;
            }
        }
    }
    arr[arr.length - 1] = asc ? 0 : 1;

    for (int i = 0; i < arr.length; i++) {
        System.out.println(arr[i]);
    }
}
Joakim Danielson :

You can create a class Tuple to hold your values

public class Tuple {
    int first;
    boolean second;

    public Tuple(int first, boolean second) {
        this.first = first;
        this.second = second;
    }

    @Override
    public String toString() {
        return String.format("(%d, %b)", first, second);
    }
}

And then slightly change your code to use it

final int[] arr = { 1, 8, 1, 9, 10 };
Tuple[] result = new Tuple[arr.length];

boolean asc = arr[1] - arr[0] == 1;
result[0] = new Tuple(arr[0], asc);
for (int i = 1; i < arr.length - 1; i++) {
    if (arr[i + 1] - arr[i] == 1) {
        asc = true;
    } else {
        if (asc) {
            asc = false;
        }
    }
    result[i] = new Tuple(arr[i], asc);
}
result[arr.length - 1] = new Tuple(arr[arr.length - 1], asc);
for (int i = 0; i < arr.length; i++) {
    System.out.println(result[i]);
}

This outputs

(1, false)
(8, false)
(1, false)
(9, true)
(10, true)

Note that if/else inside the for loops probably can be improved but since it wasn't essential to the answer I haven't done so myself

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=317042&siteId=1