From 741cb9da501b8c6e9e5fa006e5c2c9df0b4616f8 Mon Sep 17 00:00:00 2001 From: Pacien TRAN-GIRARD Date: Tue, 15 Mar 2016 11:51:31 +0100 Subject: Add List permutation function and its test --- src/ch/epfl/xblast/Lists.java | 35 ++++++++++++++++++++++++++++++----- test/ch/epfl/xblast/ListsTest.java | 15 +++++++++++++++ 2 files changed, 45 insertions(+), 5 deletions(-) diff --git a/src/ch/epfl/xblast/Lists.java b/src/ch/epfl/xblast/Lists.java index f541b37..4ea45c2 100644 --- a/src/ch/epfl/xblast/Lists.java +++ b/src/ch/epfl/xblast/Lists.java @@ -1,8 +1,6 @@ package ch.epfl.xblast; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; +import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -44,13 +42,40 @@ public final class Lists { .collect(Collectors.toList()); } + /** + * Returns a copy of the given list with element e inserted at index i. + * + * @param l the list + * @param i the insertion index + * @param e the element to insert + * @param the type of the list's elements + * @return a copy of the list with the element inserted + */ + public static List inserted(List l, int i, T e) { + List r = new LinkedList<>(l); + r.add(i, e); + return r; + } + /** * Returns all the permutations of the elements of the given list * - * @param l given list + * @param l given list + * @param the type of the list's elements * @return a list of all the permutations of the list + * @throws IllegalArgumentException if the given list is null */ public static List> permutations(List l) { - return null; + if (l == null) throw new IllegalArgumentException(); + if (l.size() <= 1) return Collections.singletonList(l); + if (l.size() == 2) return Arrays.asList(l, Lists.reversed(l)); + + List> p = new LinkedList<>(); + for (List sp : Lists.permutations(l.subList(1, l.size()))) + for (int i = 0; i <= sp.size(); ++i) + p.add(Lists.inserted(sp, i, l.get(0))); + + return p; } + } diff --git a/test/ch/epfl/xblast/ListsTest.java b/test/ch/epfl/xblast/ListsTest.java index b898399..b18b05e 100644 --- a/test/ch/epfl/xblast/ListsTest.java +++ b/test/ch/epfl/xblast/ListsTest.java @@ -4,6 +4,7 @@ import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; +import java.util.LinkedList; import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; @@ -48,4 +49,18 @@ public class ListsTest { assertEquals(mirrored.get(i), mirrored.get(mirrored.size() - 1 - i)); } + @Test + public void isListPermuted() { + List sampleList = Arrays.asList(1, 2, 3); + List> expected = new LinkedList<>(); + expected.add(Arrays.asList(1, 2, 3)); + expected.add(Arrays.asList(2, 1, 3)); + expected.add(Arrays.asList(2, 3, 1)); + expected.add(Arrays.asList(1, 3, 2)); + expected.add(Arrays.asList(3, 1, 2)); + expected.add(Arrays.asList(3, 2, 1)); + + assertEquals(expected, Lists.permutations(sampleList)); + } + } -- cgit v1.2.3