Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Q3d) When I solved the game of Life problem for labs, I used loops. Can someone post their code using streams for 3d and 3e ? #606

Open
DikshantDulal opened this issue Apr 27, 2022 · 2 comments

Comments

@DikshantDulal
Copy link

DikshantDulal commented Apr 27, 2022

No description provided.

@calvinseptyanto
Copy link

calvinseptyanto commented Apr 27, 2022

UnaryOperator<List> rule = x ->
IntStream.range(0, x.size())
.mapToObj(y -> x.get(y) == 0 ?
y == 0 ? x.get(y + 1)
: y == x.size() - 1 ? x.get(y - 1)
: x.get(y - 1) ^ x.get(y + 1)
: 0)
.collect(Collectors.toList());

static Stream conway(List list, UnaryOperator<List> rule, int n) {
return Stream.iterate(list, rule).limit(n)
.map(x -> x.stream().map(y -> y == 0 ? " " : "*").reduce("", (a, b) -> (a + b)));
}

hope this helps!!

@Lucas-Wee
Copy link

public static int cell_infect(int i, List x) {
if (i == 0 && x.get(i) == 0 && x.get(i + 1) == 1) {
i = 1; //First cell gets infected
} else if (i == 0 && x.get(i) == 0 && x.get(i + 1) == 0) {
i = 0;
} else if (i == 0 && x.get(i) == 1) {
i = 0; //First cell is infected but become ok
} else if (i == x.size() - 1 && x.get(i) == 0 && x.get(i - 1) == 1) {
i = 1; //Last cell gets infected
} else if (i == x.size() - 1 && x.get(i) == 0 && x.get(i - 1) == 0) {
i = 0;
} else if (i == x.size() - 1 && x.get(i) == 1) {
i = 0; //Last cell is infected but become ok
} else if (x.get(i) == 0 && x.get(i - 1) == 1 && x.get(i + 1) == 1) {
i = 0; //Has 2 alive neighbour
} else if (x.get(i) == 0 && (x.get(i - 1) == 1 | x.get(i + 1) == 1)) {
i = 1; //Has 1 alive only
} else {
i = 0; //Cell is infected but becomes ok
}
return i;
}

public static UnaryOperator<List<Integer>> generateRule() {
    return x -> IntStream.range(0, x.size())
                .map(i -> cell_infect(i, x))
                .boxed()
                .collect(Collectors.toList());
}

public static Stream<String> gameOfLife(List<Integer> list, 
                                        UnaryOperator<List<Integer>> rule, int n) {
    return Stream.<List<Integer>>iterate(list, rule).limit(n)
           .map(x -> x.stream().map(y -> y == 1 ? "*" : " ").reduce("", (a,b) -> a + b));
}

}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants