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 ++++++++++++++++++++++++++++++----- 1 file changed, 30 insertions(+), 5 deletions(-) (limited to 'src') 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; } + } -- cgit v1.2.3