Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 6 additions & 7 deletions src/main/java/iterator/Extra.java
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ private Extra() {
* @implNote try implement it with only one line of code !
*/
public static int sumAges(RichIterator<Person> itr) {
throw new NotImplementedException();
return itr.foldLeft(0, (sum, person) -> sum + person.age);
}

/**
Expand All @@ -22,7 +22,7 @@ public static int sumAges(RichIterator<Person> itr) {
* @implNote try implement it with only one line of code !
*/
public static Optional<Integer> avgAge(RichIterator<Person> itr) {
throw new NotImplementedException();
return Optional.of(itr.foldLeft(Pair.apply(0, 0), (acc, p) -> Pair.apply(acc._1 + p.age, acc._2 + 1))).filter(acc -> acc._2 > 0).map(acc -> acc._1 / acc._2);
}

/**
Expand All @@ -40,8 +40,7 @@ public static Optional<Integer> avgAge(RichIterator<Person> itr) {
* @implNote try implement it with only one line of code !
*/
public static <A, B> RichIterator<Pair<A, B>> product(Iterable<A> a, Iterable<B> b) {
// TODO: implement this method
throw new NotImplementedException();
return RichIterator.from(a).flatMap(x -> RichIterator.from(b).map(y -> Pair.apply(x, y)));
}

/**
Expand All @@ -50,7 +49,8 @@ public static <A, B> RichIterator<Pair<A, B>> product(Iterable<A> a, Iterable<B>
* @implNote try implement it with only 2 lines of code !
*/
public static RichIterator<Integer> multiplicationBoard() {
throw new NotImplementedException();
Iterable<Integer> range = () -> RichIterator.iterate(1, i -> i + 1).take(10);
return product(range, range).map(p -> p._1 * p._2);
}

/**
Expand All @@ -62,8 +62,7 @@ public static RichIterator<Integer> multiplicationBoard() {
* @implNote try implement it with only one line of code !
*/
public static RichIterator<Integer> factorial() {
// TODO: implement this method
throw new NotImplementedException();
return RichIterator.iterate(1, x -> x + 1).scanLeft(1, (acc, n) -> acc * n);
}

public static class Person {
Expand Down
Loading
Loading