Related
I've seen several other questions similiar to this one but I haven't really been able to find anything that resolves my problem.
My use case is this: user has a list of items initially (listA). They reorder the items and want to persist that order (listB), however, due to restrictions I'm unable persist the order on the backend so I have to sort listA after I retrieve it.
So basically, I have 2 ArrayLists (listA and listB). One with the specific order the lists should be in (listB) and the other has the list of items (listA). I want to sort listA based on listB.
Using Java 8:
Collections.sort(listToSort,
Comparator.comparing(item -> listWithOrder.indexOf(item)));
or better:
listToSort.sort(Comparator.comparingInt(listWithOrder::indexOf));
Collections.sort(listB, new Comparator<Item>() {
public int compare(Item left, Item right) {
return Integer.compare(listA.indexOf(left), listA.indexOf(right));
}
});
This is quite inefficient, though, and you should probably create a Map<Item, Integer> from listA to lookup the positions of the items faster.
Guava has a ready-to-use comparator for doing that: Ordering.explicit()
Let's say you have a listB list that defines the order in which you want to sort listA. This is just an example, but it demonstrates an order that is defined by a list, and not the natural order of the datatype:
List<String> listB = Arrays.asList("Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday");
Now, let's say that listA needs to be sorted according to this ordering. It's a List<Item>, and Item has a public String getWeekday() method.
Create a Map<String, Integer> that maps the values of everything in listB to something that can be sorted easily, such as the index, i.e. "Sunday" => 0, ..., "Saturday" => 6. This will provide a quick and easy lookup.
Map<String, Integer> weekdayOrder = new HashMap<String, Integer>();
for (int i = 0; i < listB.size(); i++)
{
String weekday = listB.get(i);
weekdayOrder.put(weekday, i);
}
Then you can create your custom Comparator<Item> that uses the Map to create an order:
public class ItemWeekdayComparator implements Comparator<Item>
{
private Map<String, Integer> sortOrder;
public ItemWeekdayComparator(Map<String, Integer> sortOrder)
{
this.sortOrder = sortOrder;
}
#Override
public int compare(Item i1, Item i2)
{
Integer weekdayPos1 = sortOrder.get(i1.getWeekday());
if (weekdayPos1 == null)
{
throw new IllegalArgumentException("Bad weekday encountered: " +
i1.getWeekday());
}
Integer weekdayPos2 = sortOrder.get(i2.getWeekday());
if (weekdayPos2 == null)
{
throw new IllegalArgumentException("Bad weekday encountered: " +
i2.getWeekday());
}
return weekdayPos1.compareTo(weekdayPos2);
}
}
Then you can sort listA using your custom Comparator.
Collections.sort(listA, new ItemWeekdayComparator(weekdayOrder));
Speed improvement on JB Nizet's answer (from the suggestion he made himself). With this method:
Sorting a 1000 items list 100 times improves speed 10 times on my
unit tests.
Sorting a 10000 items list 100 times improves speed 140 times (265 ms for the whole batch instead of 37 seconds) on my
unit tests.
This method will also work when both lists are not identical:
/**
* Sorts list objectsToOrder based on the order of orderedObjects.
*
* Make sure these objects have good equals() and hashCode() methods or
* that they reference the same objects.
*/
public static void sortList(List<?> objectsToOrder, List<?> orderedObjects) {
HashMap<Object, Integer> indexMap = new HashMap<>();
int index = 0;
for (Object object : orderedObjects) {
indexMap.put(object, index);
index++;
}
Collections.sort(objectsToOrder, new Comparator<Object>() {
public int compare(Object left, Object right) {
Integer leftIndex = indexMap.get(left);
Integer rightIndex = indexMap.get(right);
if (leftIndex == null) {
return -1;
}
if (rightIndex == null) {
return 1;
}
return Integer.compare(leftIndex, rightIndex);
}
});
}
Problem : sorting a list of Pojo on the basis of one of the field's all possible values present in another list.
Take a look at this solution, may be this is what you are trying to achieve:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Test {
public static void main(String[] args) {
List<Employee> listToSort = new ArrayList<>();
listToSort.add(new Employee("a", "age11"));
listToSort.add(new Employee("c", "age33"));
listToSort.add(new Employee("b", "age22"));
listToSort.add(new Employee("a", "age111"));
listToSort.add(new Employee("c", "age3"));
listToSort.add(new Employee("b", "age2"));
listToSort.add(new Employee("a", "age1"));
List<String> listWithOrder = new ArrayList<>();
listWithOrder.add("a");
listWithOrder.add("b");
listWithOrder.add("c");
Collections.sort(listToSort, Comparator.comparing(item ->
listWithOrder.indexOf(item.getName())));
System.out.println(listToSort);
}
}
class Employee {
String name;
String age;
public Employee(String name, String age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public String getAge() {
return age;
}
#Override
public String toString() {
return "[name=" + name + ", age=" + age + "]";
}
}
O U T P U T
[[name=a, age=age11], [name=a, age=age111], [name=a, age=age1], [name=b, age=age22], [name=b, age=age2], [name=c, age=age33], [name=c, age=age3]]
Here is a solution that increases the time complexity by 2n, but accomplishes what you want. It also doesn't care if the List R you want to sort contains Comparable elements so long as the other List L you use to sort them by is uniformly Comparable.
public class HeavyPair<L extends Comparable<L>, R> implements Comparable<HeavyPair<L, ?>> {
public final L left;
public final R right;
public HeavyPair(L left, R right) {
this.left = left;
this.right = right;
}
public compareTo(HeavyPair<L, ?> o) {
return this.left.compareTo(o.left);
}
public static <L extends Comparable<L>, R> List<R> sort(List<L> weights, List<R> toSort) {
assert(weights.size() == toSort.size());
List<R> output = new ArrayList<>(toSort.size());
List<HeavyPair<L, R>> workHorse = new ArrayList<>(toSort.size());
for(int i = 0; i < toSort.size(); i++) {
workHorse.add(new HeavyPair(weights.get(i), toSort.get(i)))
}
Collections.sort(workHorse);
for(int i = 0; i < workHorse.size(); i++) {
output.add(workHorse.get(i).right);
}
return output;
}
}
Excuse any terrible practices I used while writing this code, though. I was in a rush.
Just call HeavyPair.sort(listB, listA);
Edit: Fixed this line return this.left.compareTo(o.left);. Now it actually works.
Here is an example of how to sort a list and then make the changes in another list according to the changes exactly made to first array list. This trick will never fails and ensures the mapping between the items in list. The size of both list must be same to use this trick.
ArrayList<String> listA = new ArrayList<String>();
ArrayList<String> listB = new ArrayList<String>();
int j = 0;
// list of returns of the compare method which will be used to manipulate
// the another comparator according to the sorting of previous listA
ArrayList<Integer> sortingMethodReturns = new ArrayList<Integer>();
public void addItemstoLists() {
listA.add("Value of Z");
listA.add("Value of C");
listA.add("Value of F");
listA.add("Value of A");
listA.add("Value of Y");
listB.add("this is the value of Z");
listB.add("this is the value off C");
listB.add("this is the value off F");
listB.add("this is the value off A");
listB.add("this is the value off Y");
Collections.sort(listA, new Comparator<String>() {
#Override
public int compare(String lhs, String rhs) {
// TODO Auto-generated method stub
int returning = lhs.compareTo(rhs);
sortingMethodReturns.add(returning);
return returning;
}
});
// now sort the list B according to the changes made with the order of
// items in listA
Collections.sort(listB, new Comparator<String>() {
#Override
public int compare(String lhs, String rhs) {
// TODO Auto-generated method stub
// comparator method will sort the second list also according to
// the changes made with list a
int returning = sortingMethodReturns.get(j);
j++;
return returning;
}
});
}
try this for java 8:
listB.sort((left, right) -> Integer.compare(list.indexOf(left), list.indexOf(right)));
or
listB.sort(Comparator.comparingInt(item -> list.indexOf(item)));
import java.util.Comparator;
import java.util.List;
public class ListComparator implements Comparator<String> {
private final List<String> orderedList;
private boolean appendFirst;
public ListComparator(List<String> orderedList, boolean appendFirst) {
this.orderedList = orderedList;
this.appendFirst = appendFirst;
}
#Override
public int compare(String o1, String o2) {
if (orderedList.contains(o1) && orderedList.contains(o2))
return orderedList.indexOf(o1) - orderedList.indexOf(o2);
else if (orderedList.contains(o1))
return (appendFirst) ? 1 : -1;
else if (orderedList.contains(o2))
return (appendFirst) ? -1 : 1;
return 0;
}
}
You can use this generic comparator to sort list based on the the other list.
For example, when appendFirst is false below will be the output.
Ordered list: [a, b]
Un-ordered List: [d, a, b, c, e]
Output:
[a, b, d, c, e]
One way of doing this is looping through listB and adding the items to a temporary list if listA contains them:
List<?> tempList = new ArrayList<?>();
for(Object o : listB) {
if(listA.contains(o)) {
tempList.add(o);
}
}
listA.removeAll(listB);
tempList.addAll(listA);
return tempList;
Not completely clear what you want, but if this is the situation:
A:[c,b,a]
B:[2,1,0]
And you want to load them both and then produce:
C:[a,b,c]
Then maybe this?
List c = new ArrayList(b.size());
for(int i=0;i<b.size();i++) {
c.set(b.get(i),a.get(i));
}
that requires an extra copy, but I think to to it in place is a lot less efficient, and all kinds of not clear:
for(int i=0;i<b.size();i++){
int from = b.get(i);
if(from == i) continue;
T tmp = a.get(i);
a.set(i,a.get(from));
a.set(from,tmp);
b.set(b.lastIndexOf(i),from);
}
Note I didn't test either, maybe got a sign flipped.
Another solution that may work depending on your setting is not storing instances in listB but instead indices from listA. This could be done by wrapping listA inside a custom sorted list like so:
public static class SortedDependingList<E> extends AbstractList<E> implements List<E>{
private final List<E> dependingList;
private final List<Integer> indices;
public SortedDependingList(List<E> dependingList) {
super();
this.dependingList = dependingList;
indices = new ArrayList<>();
}
#Override
public boolean add(E e) {
int index = dependingList.indexOf(e);
if (index != -1) {
return addSorted(index);
}
return false;
}
/**
* Adds to this list the element of the depending list at the given
* original index.
* #param index The index of the element to add.
*
*/
public boolean addByIndex(int index){
if (index < 0 || index >= this.dependingList.size()) {
throw new IllegalArgumentException();
}
return addSorted(index);
}
/**
* Returns true if this list contains the element at the
* index of the depending list.
*/
public boolean containsIndex(int index){
int i = Collections.binarySearch(indices, index);
return i >= 0;
}
private boolean addSorted(int index){
int insertIndex = Collections.binarySearch(indices, index);
if (insertIndex < 0){
insertIndex = -insertIndex-1;
this.indices.add(insertIndex, index);
return true;
}
return false;
}
#Override
public E get(int index) {
return dependingList.get(indices.get(index));
}
#Override
public int size() {
return indices.size();
}
}
Then you can use this custom list as follows:
public static void main(String[] args) {
class SomeClass{
int index;
public SomeClass(int index) {
super();
this.index = index;
}
#Override
public String toString() {
return ""+index;
}
}
List<SomeClass> listA = new ArrayList<>();
for (int i = 0; i < 100; i++) {
listA.add(new SomeClass(i));
}
SortedDependingList<SomeClass> listB = new SortedDependingList<>(listA);
Random rand = new Random();
// add elements by index:
for (int i = 0; i < 5; i++) {
int index = rand.nextInt(listA.size());
listB.addByIndex(index);
}
System.out.println(listB);
// add elements by identity:
for (int i = 0; i < 5; i++) {
int index = rand.nextInt(listA.size());
SomeClass o = listA.get(index);
listB.add(o);
}
System.out.println(listB);
}
Of course, this custom list will only be valid as long as the elements in the original list do not change. If changes are possible, you would need to somehow listen for changes to the original list and update the indices inside the custom list.
Note also, that the SortedDependingList does currently not allow to add an element from listA a second time - in this respect it actually works like a set of elements from listA because this is usually what you want in such a setting.
The preferred way to add something to SortedDependingList is by already knowing the index of an element and adding it by calling sortedList.addByIndex(index);
If the two lists are guaranteed to contain the same elements, just in a different order, you can use List<T> listA = new ArrayList<>(listB) and this will be O(n) time complexity. Otherwise, I see a lot of answers here using Collections.sort(), however there is an alternative method which is guaranteed O(2n) runtime, which should theoretically be faster than sort's worst time complexity of O(nlog(n)), at the cost of 2n storage
Set<T> validItems = new HashSet<>(listB);
listA.clear();
listB.forEach(item -> {
if(validItems.contains(item)) {
listA.add(item);
}
});
List<String> listA;
Comparator<B> comparator = Comparator.comparing(e -> listA.indexOf(e.getValue()));
//call your comparator inside your list to be sorted
listB.stream().sorted(comparator)..
Like Tim Herold wrote, if the object references should be the same, you can just copy listB to listA, either:
listA = new ArrayList(listB);
Or this if you don't want to change the List that listA refers to:
listA.clear();
listA.addAll(listB);
If the references are not the same but there is some equivalence relationship between objects in listA and listB, you could sort listA using a custom Comparator that finds the object in listB and uses its index in listB as the sort key. The naive implementation that brute force searches listB would not be the best performance-wise, but would be functionally sufficient.
IMO, you need to persist something else. May be not the full listB, but something. May be just the indexes of the items that the user changed.
Try this. The code below is general purpose for a scenario where listA is a list of Objects since you did not indicate a particular type.
Object[] orderedArray = new Object[listA.size()];
for(int index = 0; index < listB.size(); index ++){
int position = listB.get(index); //this may have to be cast as an int
orderedArray[position] = listA.get(index);
}
//if you receive UnsupportedOperationException when running listA.clear()
//you should replace the line with listA = new List<Object>()
//using your actual implementation of the List interface
listA.clear();
listA.addAll(orderedArray);
Just encountered the same problem.
I have a list of ordered keys, and I need to order the objects in a list according to the order of the keys.
My lists are long enough to make the solutions with time complexity of N^2 unusable.
My solution:
<K, T> List<T> sortByOrder(List<K> orderedKeys, List<T> objectsToOrder, Function<T, K> keyExtractor) {
AtomicInteger ind = new AtomicInteger(0);
Map<K, Integer> keyToIndex = orderedKeys.stream().collect(Collectors.toMap(k -> k, k -> ind.getAndIncrement(), (oldK, newK) -> oldK));
SortedMap<Integer, T> indexToObj = new TreeMap<>();
objectsToOrder.forEach(obj -> indexToObj.put(keyToIndex.get(keyExtractor.apply(obj)), obj));
return new ArrayList<>(indexToObj.values());
}
The time complexity is O(N * Log(N)).
The solution assumes that all the objects in the list to sort have distinct keys. If not then just replace SortedMap<Integer, T> indexToObj by SortedMap<Integer, List<T>> indexToObjList.
To avoid having a very inefficient look up, you should index the items in listB and then sort listA based on it.
Map<Item, Integer> index = IntStream.range(0, listB.size()).boxed()
.collect(Collectors.toMap(listB::get, x -> x));
listA.sort((e1, e2) -> Integer.compare(index.get(c1), index.get(c2));
So for me the requirement was to sort originalList with orderedList. originalList always contains all element from orderedList, but not vice versa. No new elements.
fun <T> List<T>.sort(orderedList: List<T>): List<T> {
return if (size == orderedList.size) {
orderedList
} else {
var keepIndexCount = 0
mapIndexed { index, item ->
if (orderedList.contains(item)) {
orderedList[index - keepIndexCount]
} else {
keepIndexCount++
item
}
}
}}
P.S. my case was that I have list that user can sort by drag and drop, but some items might be filtered out, so we preserve hidden items position.
If you want to do it manually. Solution based on bubble sort (same length required):
public void sortAbasedOnB(String[] listA, double[] listB) {
for (int i = 0; i < listB.length - 1; i++) {
for (int j = listB.length - 1; j > i; j--) {
if (listB[j] < listB[j - 1]){
double tempD = listB[j - 1];
listB[j - 1] = listB[j];
listB[j] = tempD;
String tempS = listA[j - 1];
listA[j - 1] = listA[j];
listA[j] = tempS;
}
}
}
}
If the object references should be the same, you can initialize listA new.
listA = new ArrayList(listB)
In Java there are set of classes which can be useful to sort lists or arrays. Most of the following examples will use lists but the same concept can be applied for arrays. A example will show this.
We can use this by creating a list of Integers and sort these using the Collections.sort(). The Collections (Java Doc) class (part of the Java Collection Framework) provides a list of static methods which we can use when working with collections such as list, set and the like. So in a nutshell, we can sort a list by simply calling: java.util.Collections.sort(the list) as shown in the following example:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class example {
public static void main(String[] args) {
List<Integer> ints = new ArrayList<Integer>();
ints.add(4);
ints.add(3);
ints.add(7);
ints.add(5);
Collections.sort(ints);
System.out.println(ints);
}
}
The above class creates a list of four integers and, using the collection sort method, sorts this list (in one line of code) without us having to worry about the sorting algorithm.
This is my situation: I have list A of values. I also have list B which contains a hierarchy of ranks. The first being of the highest, last being of the lowest. List A will contain one, some, or all of the values from list B. I want to see which value from list A is of the highest degree (or lowest index) on list B. How would I do this best?
Just in case its still unclear, this is an example:
List A: Merchant, Peasant, Queen
List B: King, Queen, Knight, Merchant, Peasant
I'd want the method to spit out Queen in this case
Assuming List B is already sorted from Top Rank -> Bottom rank, one arbitary way you could solve it is with
public static void main (String[] args) throws Exception {
String[] firstList = { "Merchant", "Peasant", "Queen" };
String[] secondList = { "King", "Queen", "Knight", "Merchant", "Peasant" };
for (String highRank : secondList) {
for (String lowRank : firstList) {
if (highRank.equalsIgnoreCase(lowRank)) {
System.out.println(highRank);
return;
}
}
}
}
What you are describing is called a "partial ordering", and the proper way to implement the behavior you're looking for in Java is with a Comparator that defines the ordering; something like:
public class PartialOrdering<T> implements Comparator<T> {
private final Map<T, Integer> listPositions = new HashMap<>();
public PartialOrdering(List<T> elements) {
for (int i = 0; i < elements.size(); i++) {
listPositions.put(elements.get(i), i);
}
}
public int compare(T a, T b) {
Integer aPos = listPositions.get(a);
Integer bPos = listPositions.get(b);
if (aPos == null || bPos == null) {
throw new IllegalArgumentException(
"PartialOrdering can only compare elements it's aware of.");
}
return Integer.compare(aPos, bPos);
}
}
You can then simply call Collections.max() to find the largest value in your first list.
This is much more efficient than either of the other answers, which are both O(n^2) and don't handle unknown elements coherently (they assume we have a total ordering).
Even better than implementing your own PartialOrdering, however, is to use Guava's Ordering class, which provides an efficient partial ordering and a number of other useful tools. With Guava all you need to do is:
// Or store the result of Ordering.explicit() if you need to reuse it
Ordering.explicit(listB).max(listA);
I think this might work give it a Try:
function int getHighest(List<String> listA, List<String> listB)
{
int index = 0;
int max = 100;
int tmpMax = 0;
for(String test:lista)
{
for(int i =0;i<listb.size();++i)
{
if(list.get(i).equals(test))
{
tmpMax = index;
}
}
if(tmpMax < max) max = tmpMax;
++index;
}
return max;
}
I am trying to figure out how could I get the top 10 values from the HashMap. I was initially trying to use the TreeMap and have it sort by value and then take the first 10 values however it seems that that is not the option, as TreeMap sorts by key.
I want to still be able to know which keys have the highest values, the K, V of the map are String, Integer.
Maybe you should implement the Comparable Interface to your value objects stored in the hashmap.
Then you can create a array list of all values:
List<YourValueType> l = new ArrayList<YourValueType>(hashmap.values());
Collection.sort(l);
l = l.subList(0,10);
Regards
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
public class Testing {
public static void main(String[] args) {
HashMap<String,Double> map = new HashMap<String,Double>();
ValueComparator bvc = new ValueComparator(map);
TreeMap<String,Double> sorted_map = new TreeMap<String,Double>(bvc);
map.put("A",99.5);
map.put("B",67.4);
map.put("C",67.4);
map.put("D",67.3);
System.out.println("unsorted map: "+map);
sorted_map.putAll(map);
System.out.println("results: "+sorted_map);
}
}
class ValueComparator implements Comparator<String> {
Map<String, Double> base;
public ValueComparator(Map<String, Double> base) {
this.base = base;
}
// Note: this comparator imposes orderings that are inconsistent with equals.
public int compare(String a, String b) {
if (base.get(a) >= base.get(b)) {
return -1;
} else {
return 1;
} // returning 0 would merge keys
}
}
I am afraid you'll have to iterate over the entire map. Heap is a commonly-used data structure for finding top K elements, as explained in this book.
If you are trying to get the 10 highest values of the map (assuming the values are numeric or at least implementing Comparable) then try this:
List list = new ArrayList(hashMap.values());
Collections.sort(list);
for(int i=0; i<10; i++) {
// Deal with your value
}
Let's assume you have a Map, but this example can work for any type of
Map<String, String> m = yourMethodToGetYourMap();
List<String> c = new ArrayList<String>(m.values());
Collections.sort(c);
for(int i=0 ; i< 10; ++i) {
System.out.println(i + " rank is " + c.get(i));
}
I base my answer in this one from sk2212
First you need to implement a descending comparator:
class EntryComparator implements Comparator<Entry<String,Integer>> {
/**
* Implements descending order.
*/
#Override
public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
if (o1.getValue() < o2.getValue()) {
return 1;
} else if (o1.getValue() > o2.getValue()) {
return -1;
}
return 0;
}
}
Then you can use it in a method such as this one for the attribute "hashmap":
public List<Entry<String,Integer>> getTopKeysWithOccurences(int top) {
List<Entry<String,Integer>> results = new ArrayList<>(hashmap.entrySet());
Collections.sort(results, new EntryComparator());
return results.subList(0, top);
}
public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<String, Integer>();
// Initialize map
System.out.println(getTopKeysWithOccurences(map, 10));
}
public static List<Entry<String,Integer>> getTopKeysWithOccurences(Map mp, int top) {
List<Entry<String,Double>> results = new ArrayList<>(mp.entrySet());
Collections.sort(results, (e1,e2) -> e2.getValue() - e1.getValue());
//Ascending order - e1.getValue() - e2.getValue()
//Descending order - e2.getValue() - e1.getValue()
return results.subList(0, top);
}
I am trying to make a url from a different combinations of string separated by comma so that I can use those url to execute them and get the data back.
I have simplified something like this, I have a HashSet that will contain all my strings, not A,B,C in real. I just modified it here to make it simple.
Set<String> data = new HashSet<String>();
h.add("A");
h.add("B");
h.add("C");
for (int i = 1; i < 1000; i++) {
String pattern = generateString(data);
String url = "http://localhost:8080/service/USERID=101556000/"+pattern;
System.out.println(url);
}
/**
* Below is the method to generate Strings.
/
private String generateString(HashSet<String> data) {
//not sure what logic I am supposed to use here?
}
So the output should be something like this-
http://localhost:8080/service/USERID=101556000/A
http://localhost:8080/service/USERID=101556000/B
http://localhost:8080/service/USERID=101556000/C
http://localhost:8080/service/USERID=101556000/A,B,C
http://localhost:8080/service/USERID=101556000/B,C
http://localhost:8080/service/USERID=101556000/C,A
--
And other combinations
The above output can be in any random order as well. But it should be all the possible combinations. And if all the possible combinations are finished then start again.
Any suggestion how can I achieve the above problem definition?
What you're asking is not trivial.
Let's look at 2 strings, A and B.
Here are all of the permutations.
A
B
AB
BA
Ok, let's look at 3 strings, A, B, and C.
Here are all the permutations.
A
B
C
AB
AC
BA
BC
CA
CB
ABC
ACB
BAC
BCA
CAB
CBA
Do you see a pattern yet?
First, you have to find all of the single string permutations. Then the two string permutations. Then the three string permutations. And so on, up to the number of strings.
Then, within a set of permutations (like the two string set), you have to find all of the possible permutations.
You can do this with java loops. You can also use recursion.
Given what is k-arrangement (http://en.wikibooks.org/wiki/Probability/Combinatorics), you are looking for the k-arrangement where k varies from 1 to D, where D is the size of the data collections.
This means to compute - my first post I can't post image so look at equation located at :
In order to do it, you can make k varies, and the for each k may n varies (i.e. deal only with a sub array or data to enumerate the k-permutations). These k-permutations can be found by walking the array to the right and to the left using recursion.
Here is a quick bootstrap that proves to enumerate whart is required :
public class EnumUrl {
private Set<String> enumeration = null;
private List<String> data = null;
private final String baseUrl = "http://localhost:8080/service/USERID=101556000/";
public EnumUrl(List<String> d) {
data = d;
enumeration = new HashSet<String>(); // choose HashSet : handle duplicates in the enumeration process
}
public Set<String> getEnumeration() {
return enumeration;
}
public static void main(String[] args) {
List<String> data = new ArrayList<String>();
data.add("A");
data.add("B");
data.add("C");
EnumUrl enumerator = new EnumUrl(data);
for (int k = 0; k < data.size(); k++) {
// start from any letter in the set
for (int i = 0; i < data.size(); i++) {
// enumerate possible url combining what's on the right of indice i
enumerator.enumeratePossibleUrlsToRight(data.get(i), i);
// enumerate possible url combining what's on the left of indice i
enumerator.enumeratePossibleUrlsToLeft(data.get(i), i);
}
// make a circular permutation of -1 before the new iteration over the newly combined data
enumerator.circularPermutationOfData();
}
// display to syso
displayUrlEnumeration(enumerator);
}
private void circularPermutationOfData() {
String datum = data.get(0);
for (int i = 1; i < data.size(); i++) {
data.set(i - 1, data.get(i));
}
data.set(data.size() - 1, datum);
}
private static void displayUrlEnumeration(EnumUrl enumerator) {
for (String url : enumerator.getEnumeration()) {
System.out.println(url);
}
}
private void enumeratePossibleUrlsToRight(String prefix, int startAt) {
enumeration.add(baseUrl + prefix);
if (startAt < data.size() - 1) {
startAt++;
for (int i = startAt; i < data.size(); i++) {
int x = i;
enumeratePossibleUrlsToRight(prefix + "," + data.get(x), x);
}
}
}
private void enumeratePossibleUrlsToLeft(String prefix, int startAt) {
enumeration.add(baseUrl + prefix);
if (startAt > 0) {
startAt--;
for (int i = startAt; i >= 0; i--) {
int x = i;
enumeratePossibleUrlsToLeft(prefix + "," + data.get(x), x);
}
}
}
}
The program outputs for {A,B,C} :
http://localhost:8080/service/USERID=101556000/B,C
http://localhost:8080/service/USERID=101556000/B,A,C
http://localhost:8080/service/USERID=101556000/B,C,A
http://localhost:8080/service/USERID=101556000/B,A
http://localhost:8080/service/USERID=101556000/C
http://localhost:8080/service/USERID=101556000/B
http://localhost:8080/service/USERID=101556000/C,B,A
http://localhost:8080/service/USERID=101556000/A,C,B
http://localhost:8080/service/USERID=101556000/A,C
http://localhost:8080/service/USERID=101556000/A,B
http://localhost:8080/service/USERID=101556000/A,B,C
http://localhost:8080/service/USERID=101556000/A
http://localhost:8080/service/USERID=101556000/C,B
http://localhost:8080/service/USERID=101556000/C,A
http://localhost:8080/service/USERID=101556000/C,A,B
And for {A,B,C,D} :
http://localhost:8080/service/USERID=101556000/B,A,D,C
http://localhost:8080/service/USERID=101556000/C,D
http://localhost:8080/service/USERID=101556000/A,D,C,B
http://localhost:8080/service/USERID=101556000/A,C,D
http://localhost:8080/service/USERID=101556000/D
http://localhost:8080/service/USERID=101556000/C
http://localhost:8080/service/USERID=101556000/A,C,B
http://localhost:8080/service/USERID=101556000/B
http://localhost:8080/service/USERID=101556000/A,B,C,D
http://localhost:8080/service/USERID=101556000/A,B,C
http://localhost:8080/service/USERID=101556000/D,C,B,A
http://localhost:8080/service/USERID=101556000/C,B,A,D
http://localhost:8080/service/USERID=101556000/A,B,D
http://localhost:8080/service/USERID=101556000/D,B
http://localhost:8080/service/USERID=101556000/D,C
http://localhost:8080/service/USERID=101556000/A
http://localhost:8080/service/USERID=101556000/D,C,A
http://localhost:8080/service/USERID=101556000/D,C,B
http://localhost:8080/service/USERID=101556000/C,D,A
http://localhost:8080/service/USERID=101556000/C,D,B
http://localhost:8080/service/USERID=101556000/D,A
http://localhost:8080/service/USERID=101556000/A,D,C
http://localhost:8080/service/USERID=101556000/A,D,B
http://localhost:8080/service/USERID=101556000/C,B,D
http://localhost:8080/service/USERID=101556000/B,A,D
http://localhost:8080/service/USERID=101556000/B,C
http://localhost:8080/service/USERID=101556000/B,A,C
http://localhost:8080/service/USERID=101556000/B,C,A
http://localhost:8080/service/USERID=101556000/B,A
http://localhost:8080/service/USERID=101556000/B,C,D
http://localhost:8080/service/USERID=101556000/C,B,A
http://localhost:8080/service/USERID=101556000/A,D
http://localhost:8080/service/USERID=101556000/D,A,B
http://localhost:8080/service/USERID=101556000/A,C
http://localhost:8080/service/USERID=101556000/D,A,C
http://localhost:8080/service/USERID=101556000/B,C,D,A
http://localhost:8080/service/USERID=101556000/A,B
http://localhost:8080/service/USERID=101556000/B,D
http://localhost:8080/service/USERID=101556000/C,D,A,B
http://localhost:8080/service/USERID=101556000/D,A,B,C
http://localhost:8080/service/USERID=101556000/D,B,A
http://localhost:8080/service/USERID=101556000/D,B,C
http://localhost:8080/service/USERID=101556000/B,D,A
http://localhost:8080/service/USERID=101556000/C,B
http://localhost:8080/service/USERID=101556000/C,A,D
http://localhost:8080/service/USERID=101556000/C,A
http://localhost:8080/service/USERID=101556000/B,D,C
http://localhost:8080/service/USERID=101556000/C,A,B
Which is not the exhaustive enumeration. Basically we should have:
(my first post I can't post image to look at equation located in my reply, I don't have the reputation to post 2 links ... #omg)
That makes 64 combinaisons, distributed as follows:
4 combinaisons of 1 element (k=1)
12 combinaisons of 12 element (k=2)
24 combinaisons of 24 element (k=3)
24 combinaisons of 24 element (k=4)
You can see that my program is OK for k=1, k=2, and k=3. But there are not 24 combinaisons for k=4. In order to complete the program, you will need to iterate also on other type of shuffling the data than circular permutation. Actually when k=4, circular permutation does not generate for instance ADBC as input data (hence DBCA cannot be generated by my implementation for instance). In this case, you will want to enumerate all possible data input array with n elements in all possible order. This is a special case of k-permutation, where k=n, and therefore leads to finding the n! permutation. We can achieve this by calling the EnumUrl method for each of the n! possible permutation.
For this, you should update EnumUrl enumerator = new EnumUrl(data); accordingly, but I guess I am letting some work for you to make :-)
HTH
A short version working for arbitrary set size, with generics, using guava, and the method for permutation given here.
Basically the idea is the following :
Generate the powerset, discard empty set
For each set of the powerset, generate all permutations
public class QuickEnumeration {
Set<T> objects;
public QuickEnumeration(Set<T> objects) {
this.objects = objects;
}
public List<List<T>> generateEnumeration() {
List<List<T>> result = new ArrayList<List<T>>();
// Compute the powerset
Set<Set<T>> powerset = Sets.powerSet(objects);
for (Set<T> set : powerset) {
// Discard empty set
if (set.size() > 0) {
// Arraylist faster for swapping
ArrayList<T> start = new ArrayList<T>(set);
permute(start, 0, result);
}
}
return result;
}
private void permute(ArrayList<T> arr, int k, List<List<T>> result) {
for (int i = k; i < arr.size(); i++) {
java.util.Collections.swap(arr, i, k);
permute(arr, k + 1, result);
java.util.Collections.swap(arr, k, i);
}
if (k == arr.size() - 1) {
result.add((List<T>) arr.clone());
}
}
public static void main(String[] args) {
Set<String> testSet = new HashSet<>();
testSet.add("A");
testSet.add("B");
testSet.add("C");
QuickEnumeration<String> enumerate = new QuickEnumeration<>(testSet);
System.out.println(enumerate.generateEnumeration());
}
}
Testing with "A","B","C" gives :
[[A], [B], [A, B], [B, A], [C], [A, C], [C, A], [B, C], [C, B], [A, B, C], [A, C, B], [B, A, C], [B, C, A], [C, B, A], [C, A, B]]
I am not entirely sure what you really want, so I ended up writing this piece of code for you. Hope it gets you started!
public static void doThis() {
String url1="http://www.example.com";
String string1="A";
String url2="http://www.foo.com";
String string2="B";
String url3="http://www.bar.com";
String string3="C";
Map<String, String> abbrMap = new HashMap<String, String>();
abbrMap.put(string1, url1);
abbrMap.put(string2, url2);
abbrMap.put(string3, url3);
String string = string1+string2+string3;
for(Map.Entry<String, String> m : abbrMap.entrySet()) {
arrange(string, m.getValue());
}
}
private static void arrange(String str, String url) {
if (str.length()==0) return;
StringBuffer sbuf = new StringBuffer();
for (int j=0; j<str.length(); j++) {
for(int i=j; i<str.length(); i++) {
char c = str.charAt(i);
sbuf.append(c);
System.out.println(url+"/"+sbuf.toString());
sbuf.append(",");
}
sbuf.setLength(0);
}
}
Output:
http://www.example.com/A
http://www.example.com/A,B
http://www.example.com/A,B,C
http://www.example.com/B
http://www.example.com/B,C
http://www.example.com/C
http://www.foo.com/A
http://www.foo.com/A,B
http://www.foo.com/A,B,C
http://www.foo.com/B
http://www.foo.com/B,C
http://www.foo.com/C
http://www.bar.com/A
http://www.bar.com/A,B
http://www.bar.com/A,B,C
http://www.bar.com/B
http://www.bar.com/B,C
http://www.bar.com/C
I'd like to create a list of tuples from each value within a set of lists. The set of lists can be open, but for the example I have the following three lists of Strings.
L1: (one, two three)
L2: (a, b, c)
L3: (yes, no)
I would like to return a list of tuples, where in each tuple I have on element from each list. In this case, I will have 18 combinations (3 x 3 x 2)
T1: (one, a, yes)
T2: (one, a, no)
T3: (one, b, yes)
T4: (one, b, no)
T5: (one, c, yes)
T6: (one, c, no)
T7: (two, a, yes)
and so on. In this case we're using Java.
List<List<String>> list = getInput();
List<List<String> tuples = combinations(list);
where getInput() returns my input (L1, L2, L3), and combinations creates my output (T1, T2, T3...)
Since #Ted Hopp posted a recursive solution i am posting a non-recursive solution.
This is a working solution,
/**
* #author kalyan
*
*/
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Stack;
public class Permutation
{
public static void printLists(List<List<String>> list) {
for(List<String> lstItem : list) {
System.out.println(lstItem.toString());
}
}
public static List<List<String>> recurse(List<LinkedList<String>> list ) {
List<List<String>> out = new ArrayList<List<String>>();
Stack<String> mystack = new Stack<String>();
int i = 0;
while (! (i == 0 && list.get(0).get(0).equals("TAIL"))) {
if ( i >= list.size()) {
/* We have got one element from all the list */
out.add(new ArrayList<String>(mystack));
/* Go back one row */
i --;
/* remove the last added element */
mystack.pop();
continue;
}
LinkedList<String> tuple = list.get(i);
if (tuple.getFirst().equals("TAIL")) {
/* We have finished one sub list go back one row */
i--;
mystack.pop();
/* also fall below to move the TAIL from begining to end */
}
else {
mystack.add(tuple.getFirst());
i++;
}
tuple.add(tuple.getFirst());
tuple.removeFirst();
}
return out;
}
public static void main(String[] args) {
List<LinkedList<String>> list = new ArrayList<LinkedList<String>>();
List<List<String>> perm = new ArrayList<List<String>>();
/* keep TAIL, so that we know processed a list */
LinkedList<String> num = new LinkedList<String>();
num.add("one"); num.add("two"); num.add("three"); num.add("TAIL");
LinkedList<String> alpha = new LinkedList<String>();
alpha.add("a"); alpha.add("b"); alpha.add("c"); alpha.add("TAIL");
LinkedList<String> bool = new LinkedList<String>();
bool.add("yes"); bool.add("no"); bool.add("tristate"); bool.add("TAIL");
list.add(num); list.add(alpha); list.add(bool);
perm = recurse (list);
printLists(perm);
}
}
This should be pretty easy with a recursive function. This is untested:
List<List<String>> listOfTuples(<List<List<String>> list) {
ArrayList<List<String>> result = new ArrayList<List<String>>();
List<String> prefix = new ArrayList<String>();
recurse(0, list, prefix, result);
return result;
}
void recurse(int index,
List<List<String>> input,
List<String> prefix,
List<List<String>> output)
{
if (index >= input.size()) {
output.add(new ArrayList<String>(prefix));
} else {
List<String> next = input.get(index++);
for (String item : next) {
prefix.add(item);
recurse(index, input, prefix, output);
prefix.remove(item);
}
}
}
The recursive solution above fails if any of the lists shares common elements.
Using a Stack and pushing/popping elements rather than adding/removing them from a list fixes it.
Here's the revised code for the recurse method:
void recurse(int index, List<List<String>> input, Stack<String> prefix, List<List<String>> output) {
if (index >= input.size()) {
String[] tuple = new String[prefix.size()];
prefix.copyInto(tuple);
output.add(Arrays.asList(tuple));
} else {
List<String> next = input.get(index++);
for (String item : next) {
prefix.push(item);
recurse(index, input, prefix, output);
prefix.pop();
}
}
}
1. Impose an arbitrary ordering on the lists.
For instance, create a list with order
given by index.
2. Call permute(thelists[1..n], buffer[1..n], 1).
permute(thelist[1..n], buffer[1..n], pos)
1. if pos > n then print buffer
2. else then
3. for i = 1 to |thelists[pos]| do
4. buffer[pos] = thelists[pos][i]
5. permute(thelists[1..n], buffer[1..n], pos + 1)