Java HashMap custom Object - java

Example:
d1 = "the sky is blue"
d2 = "the car is blue"
Key Value
the [<d1,1>,<d2,1>]
sky [<d1,1>]
is [<d1,1>,<d2,1>]
blue [<d1,1>,<d2,1>]
car [<d2,1>]
Where:
key = String
ex:
<d1,1>
d1 = Document id
1 = How many times the word apear on file
I created a document type object with the docid variables and frequency.
public class Documento {
private final int docid;
private final int frequencia;
public Documento(int docid, int frequencia) {
this.docid = docid;
this.frequencia = frequencia;
}
public int getDocid() {
return docid;
}
public int getFrequencia() {
return frequencia;
}
#Override
public boolean equals(Object o) {
if ((o instanceof Documento) && docid == ((Documento) o).docid && frequencia == ((Documento) o).frequencia) {
return true;
}
return false;
}
And the dictionary class that is a hashmap with
public class Dicionario {
public Map<String, Documento> indice = new HashMap<>();
public void InsereDicionario(String palavra, int docid) {
int cont = indice.containsKey(palavra) ? indice.get(palavra).getFrequencia() : 0;
indice.put(palavra, new Documento(docid, cont + 1));
}
public int frequencia(String palavra) {
return indice.get(palavra).getFrequencia();
}
public void criaDicionario(String entrada) {
String[] palavras = entrada.split("\\s+");
for (int i = 0; i < palavras.length; i++) {
InsereDicionario(palavras[i], 1);
}
}
public void ListaPalavras(){
for(String key:indice.keySet()){
System.out.println("");
}
}
But what I really need the dictionary is a list of documents , and I do not know how to do this , someone could help me ?
or is there an easier way to do this ?

If you need a list of documents, why not create one? With Java8 this becomes even more convenient:
For example:
public Map<String, List<Documento>> indice = new HashMap<>();
//register new word
indice.putIfAbsent(palavra, new ArrayList<>());
//add additional occurence
indice.get(palavra).add(documento);
//get frequency
int frequencia = indice.get(palavra)
.stream()
.map(d -> d.getFrequencia())
.reduce(0, (s, i) -> s + i);
An alternative would be to use Guava's Multimap, see here

Map<String, List<Documento>>
Obviously you need to adapt the rest of the code.
For example, when you need to add something to the dictionary, if it's the first time you need to create the List with that single document, next time you need to take the already created list and add documents there.

Related

HashMap Storing only one entry

I'm taking a binary String like this:
010010010000110100001010
as a String, converting it to Integer Array like this:
int[] DD = new DD[binString.length()];
char temp = binString.charAt(i);
int binData = Character.getNumericValue(temp);
DD[i] = binData;
and I'm tying to save these Integer values in to HashMap(I have to store into a HashMap as per instructions given to me) like this:
Map<String, Integer> toMemory = new HashMap<String, Integer>();
for(int i=0;i<binString.length();i++) {
char temp = binString.charAt(i);
int binData = Character.getNumericValue(temp);
DD[i] = binData;
if((DD[i] & (DD[i]-1) ) == 0) {
toMemory.put(new String("ON"), new Integer(DD[i]));
} else {
toMemory.put(new String("ON"), new Integer(DD[i]));
}
}
for(String s: toMemory.keySet()) {
if(s.startsWith("ON")) {
System.out.println(toMemory.get(s));
}
}
The issue I'm facing here is that, only one entry is being stored in the HashMap, say {"ON",0}. And no other values are being stored. My expected output is this:
{"ON" , 1 , "OFF" , 0, "ON" , 1 .........}
Is there any better way to store the values to get my expected output? Any help will be much appreciated.
P.S: Please ignore the recurring code, and I'm relatively new to programming.
Your usage of a Map is flawed. Maps take a unique key and return a value.
You are trying to use duplicate keys. Instead, look at using a List with a wrapper class:
class ClassName {
public String status;
public int value;
public ClassName(String status, int value){
this.status = status;
this.value = value;
}
}
List<ClassName> list = new ArrayList();
To add to the list, create a new instance of your class and call List#add:
list.add(new ClassName("ON", 1));
as Infuzed Guy said, you are using the Map the wrong way. It's a unique "key to value mapping".
As long as you are using several times the same key and want to store all the dada, you need to use a List.
Here is what I could come up with the little you gave us: test it here
import java.util.LinkedList;
import java.util.List;
class Main {
public static void main(String[] args) {
class Tuple<X, Y> { //The wrapper object
public final X x;
public final Y y;
public Tuple(X x, Y y) { //Object constructor
this.x = x;
this.y = y;
}
public String toString() //Here for printing purpose
{
return "\"" + this.x + "\", " + this.y;
}
}
//Note here te use of List
List<Tuple> toMemory = new LinkedList<>();
String binString = "10100100101100101011";
int[] DD = new int[binString.length()];
for(int i=0; i < binString.length(); ++i)
{
//Here I use the char value
//to get the by subtraction
DD[i] = binString.charAt(i) - '0';
if(DD[i] == 1) //Simple check with the int value
{
toMemory.add(new Tuple<>("ON", DD[i]));
}
else
{
toMemory.add(new Tuple<>("OFF", DD[i]));
}
}
//Print the List
System.out.print("{ ");
for(Tuple s: toMemory) {
System.out.print(s +", ");
}
System.out.println("}");
}
}

Sort ArrayList items by name

I am trying to rearrange an ArrayList based on the name of the items to be on specific index.
My list currently is this:
"SL"
"TA"
"VP"
"SP"
"PR"
and i want to rearrange them to:
"SL"
"SP"
"TA"
"PR"
"VP"
but based on the name and not in the index.
I have tried this:
for (int i=0; i< list.size(); i++){
if (list.get(i).getCategoryName().equals("SL")){
orderedDummyJSONModelList.add(list.get(i));
}
}
for (int i=0; i< list.size(); i++){
if (list.get(i).getCategoryName().equals("SP")){
orderedDummyJSONModelList.add(list.get(i));
}
}
for (int i=0; i< list.size(); i++){
if (list.get(i).getCategoryName().equals("TA")){
orderedDummyJSONModelList.add(list.get(i));
}
}
for (int i=0; i< list.size(); i++){
if (list.get(i).getCategoryName().equals("PR")){
orderedDummyJSONModelList.add(list.get(i));
}
}
for (int i=0; i< list.size(); i++){
if (list.get(i).getCategoryName().equals("VP")){
orderedDummyJSONModelList.add(list.get(i));
}
}
and it works fine, but i want to know if there is a more efficient way to do in 1 for loop or maybe a function. I do not wish to do it like this:
orderedDummyJSONModelList.add(list.get(0));
orderedDummyJSONModelList.add(list.get(3));
orderedDummyJSONModelList.add(list.get(1));
orderedDummyJSONModelList.add(list.get(4));
orderedDummyJSONModelList.add(list.get(2));
Which also works. Any ideas?
You can use Collection.Sort method as Collection.Sort(list) since list is a List<String> you will be fine. But if you want to implement a new comparator:
Collections.sort(list, new NameComparator());
class NameComparator implements Comparator<String> { //You can use classes
#Override
public int compare(String a, String b) { //You can use classes
return a.compareTo(b);
}
}
EDIT:
You can define a class comparator for your needs:
class ClassComparator implements Comparator<YourClass> { //You can use classes
#Override
public int compare(YourClass a, YourClass b) { //You can use classes
return a.name.compareTo(b.name);
}
}
The key thing here is: you need to get clear on your requirements.
In other words: of course one can shuffle around objects stored within a list. But: probably you want to do that programmatically.
In other words: the correct approach is to use the built-in Collection sorting mechanisms, but with providing a custom Comparator.
Meaning: you better find an algorithm that defines how to come from
"SL"
"TA"
"VP"
"SP"
"PR"
to
"SL"
"SP"
"TA"
"PR"
"VP"
That algorithm should go into your comparator implementation!
The point is: you have some List<X> in the first place. And X objects provide some sort of method to retrieve those strings you are showing here. Thus you have to create a Comparator<X> that works on X values; and uses some mean to get to those string values; and based on that you decide if X1 is <, = or > than some X2 object!
here´s an answer just specific for your problem working just for the given output. If the List contains anything else this might break your ordering, as there is no rule given on how to order it and the PR just randomly appears in the end.
public static void main(String[] args) {
List<String> justSomeNoRuleOrderingWithARandomPRInside = new ArrayList<String>();
justSomeNoRuleOrderingWithARandomPRInside.add("SL");
justSomeNoRuleOrderingWithARandomPRInside.add("TA");
justSomeNoRuleOrderingWithARandomPRInside.add("VP");
justSomeNoRuleOrderingWithARandomPRInside.add("SP");
justSomeNoRuleOrderingWithARandomPRInside.add("PR");
java.util.Collections.sort(justSomeNoRuleOrderingWithARandomPRInside, new NameComparator());
for(String s : justSomeNoRuleOrderingWithARandomPRInside) {
System.out.println(s);
}
}
static class NameComparator implements Comparator<String> { //You can use classes
#Override
public int compare(String a, String b) { //You can use classes
// Lets just add a T in front to make the VP appear at the end
// after TA, because why not
if (a.equals("PR")) {
a = "T"+a;
} else if(b.equals("PR")) {
b = "T"+b;
}
return a.compareTo(b);
}
}
O/P
SL
SP
TA
PR
VP
But honestly, this solution is crap, and without any clear rule on how to order these this will be doomed to fail as soon as you change anything as #GhostCat tried to explain.
How about this
// define the order
List<String> ORDER = Arrays.asList("SL", "SP", "TA", "PR", "VP");
List<MyObject> list = ...
list.sort((a, b) -> {
// lamba syntax for a Comparator<MyObject>
return Integer.compare(ORDER.indexOf(a.getString()), ORDER.indexOf(b.getString());
});
Note that this will put any strings that aren't defined in the ORDER list at the start of the sorted list. This may or may not be acceptable - it may be worth checking that only valid strings (i.e. members of ORDER) appear as the result of MyObject.getString().
Use a hashmap to store the weight of all strings (Higher the value of the hashmap means the later this string should come in the final list).
Using a Hashmap, so you can expand it later for other strings as well. It'll be easier to enhance in future.
Finally, Use a custom Comparator to do it.
Required Setup:
List<String> listOfStrings = Arrays.asList("SL", "TA", "VP", "SP", "PR");
HashMap<String, Integer> sortOrder = new HashMap<>();
sortOrder.put("SL", 0);
sortOrder.put("TA", 1);
sortOrder.put("VP", 2);
sortOrder.put("SP", 3);
sortOrder.put("PR", 4);
Streams:
List<String> sortedList = listOfStrings.stream().sorted((a, b) -> {
return Integer.compare(sortOrder.get(a), sortOrder.get(b));
}).collect(Collectors.toList());
System.out.println(sortedList);
Non-Stream:
Collections.sort(listOfStrings, (a, b) -> {
return Integer.compare(sortOrder.get(a), sortOrder.get(b));
});
OR
listOfStrings.sort((a, b) -> {
return Integer.compare(sortOrder.get(a), sortOrder.get(b));
});
System.out.println(listOfStrings);
Output:
[SL, TA, VP, SP, PR]
You can build an index map using a LinkedHashMap. This will be used to lookup the order which to sort using the category names of your items.
ItemSorting
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class ItemSorting {
public static void main(String[] args) {
List<Item> list = new ArrayList<Item>();
IndexMap indexMap = new IndexMap("SL", "SP", "TA", "PR", "VP");
ItemComparator itemComparator = new ItemComparator(indexMap);
list.add(new Item("SL"));
list.add(new Item("TA"));
list.add(new Item("VP"));
list.add(new Item("SP"));
list.add(new Item("PR"));
Collections.sort(list, itemComparator);
for (Item item : list) {
System.out.println(item);
}
}
}
ItemComparator
import java.util.Comparator;
public class ItemComparator implements Comparator<Item> {
private IndexMap indexMap;
public IndexMap getIndexMap() {
return indexMap;
}
public void setIndexMap(IndexMap indexMap) {
this.indexMap = indexMap;
}
public ItemComparator(IndexMap indexMap) {
this.indexMap = indexMap;
}
#Override
public int compare(Item itemA, Item itemB) {
if (itemB == null) return -1;
if (itemA == null) return 1;
if (itemA.equals(itemB)) return 0;
Integer valA = indexMap.get(itemA.getCategoryName());
Integer valB = indexMap.get(itemB.getCategoryName());
if (valB == null) return -1;
if (valA == null) return 1;
return valA.compareTo(valB);
}
}
IndexMap
import java.util.LinkedHashMap;
public class IndexMap extends LinkedHashMap<String, Integer> {
private static final long serialVersionUID = 7891095847767899453L;
public IndexMap(String... indicies) {
super();
if (indicies != null) {
for (int i = 0; i < indicies.length; i++) {
this.put(indicies[i], new Integer(i));
}
}
}
}
Item
public class Item {
private String categoryName;
public Item(String categoryName) {
super();
this.categoryName = categoryName;
}
public String getCategoryName() {
return categoryName;
}
public void setCategoryName(String categoryName) {
this.categoryName = categoryName;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((categoryName == null) ? 0 : categoryName.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
Item other = (Item) obj;
if (categoryName == null) {
if (other.categoryName != null) return false;
} else if (!categoryName.equals(other.categoryName)) return false;
return true;
}
#Override
public String toString() {
return String.format("Item { \"categoryName\" : \"%s\" }", categoryName);
}
}
Result
Item { "categoryName" : "SL" }
Item { "categoryName" : "SP" }
Item { "categoryName" : "TA" }
Item { "categoryName" : "PR" }
Item { "categoryName" : "VP" }
You coud define a helper method like this one:
public static int get(String name) {
switch (name) {
case "SL":
return 1;
case "SP":
return 2;
case "TA":
return 3;
case "PR":
return 4;
case "VP":
return 5;
default:
return 6;
}
}
and write in your main method something like:
ArrayList<String> al = new ArrayList<>();
al.add("SL");
al.add("TA");
al.add("VP");
al.add("SP");
al.add("PR");
Collections.sort(al, (o1, o2) -> return get(o1) - get(o2); );
al.forEach((s) -> System.out.println(s));
You can create a Map that maintains the position. When you iterate through the unordered list just get the position of that string value and insert into new array(not arraylist), then later if required you can convert that array to ArrayList.
Example code:
Map<String,Integer> map = new HashMap<>(); //you can may be loop through and make this map
map.put("SL", 0);
map.put("SP", 1);
map.put("TA",2);
map.put("PR",3);
map.put("VP",3);
List<String> list1 // your unordered list with values in random order
String[] newArr = new String[list1.size()];
for(String strName: list1){
int position = map.get(strName);
arr[position] = strName;
}
//newArr has ordered result.

How to get index from Arraylist which contains string

Below is my model:
public class Products {
String date = "", item = "";
public Products () {
}
public Products (String date String item ) {
this.date = date
this.item = item ;
}
public String getdate() {
return date
}
public void setdate (String date) {
this.date = date
}
public String getitem () {
return item
}
public void setitem (String item) {
this.item = item
}
}
And below code for defined the Arralist:
private ArrayList<TasksCharts> mArrayList;
and i have data in ArrayList:
position 0 -> date - "2016-10-02" , item = "pens"
position 1 -> date - "2016-10-03" , item = "xyz"
position 2 -> date - "2016-10-03" , item = "fts"
Now i want the position of ArraList whose contain "pens" . So for that i have eritten below code:
if (containsSubString(mArrayList, "pens")) {
int listIndex = getItemPos("pens");
}
private int getItemPos(String item) {
return mArrayList.indexOf(item);
}
When i runt this it will give me -1 index for item pens.
How can i get the index of particular item ?
Does a TasksCharts Object containing pens equal a String Object containing pens?
Unless you have overriden the equals method I would say "no".
I would recommend that you use a Map instead or you will have to loop through looking for a TasksCharts Object containing pens
You can run a for loop to get job done .
private int getItempos(ArrayList<TasksCharts> mArrayList, String str)
{
for(int i=0;i<mArrayList.size();i++)
{
if(mArrayList.get(i).item.indexOf(str)!=-1)
{
return i;
}
}
return -1;
}
Hope this helps!
you should do sth like this :
private int getItemPos(String key , String item) {
int i = 0;
for (i=0; i<mArrayList.size(); i++)
{
if(mArrayList.get(i).get(key).equalsIgnoreCase(item))
{
return i;
}
}
return -1;
}
and call
int x = getItemPos("item" , "pen");
I have simply added products in the same ArrayList and then used for-loop to find that product position.
ArrayList<Products> mArrayList = new ArrayList<>();
Products products1 = new Products("2016-10-05", "Pens");
Products products2 = new Products("2016-10-04", "Pencil");
Products products3 = new Products("2016-10-03", "Book");
Products products4 = new Products("2016-10-02", "Dairy");
mArrayList.add(products1);
mArrayList.add(products2);
mArrayList.add(products3);
mArrayList.add(products4);
for (Products products : mArrayList) {
if (products.getitem().equals("Pens")) {
Log.d("Position", mArrayList.indexOf(products) + "");
}
}
This will give Output as
D/Position: 0

implementing comparator to sort list of strings

I have a list of strings which I would like to sort instead of by their lexicographic order- by their weight (number of times the word appears in the specifies URL / number of words in this URL).
the problem is with the methode "searchPrefix" that when I creat a new Comparator, it obviously doesn't recognize the fields of that class in which I use to calculate the weight.
things iv'e tried:
1. using SortedMap and then there is no need to implement the Comparator, only that the instructions specifically note to implement the Comparator.
2. using getters (also didn't work because i'm working within the class and the methode);
3. implement the list as List> urlList = new ArrayList... also didn't work.
(The implementation of Comparator is what I would like to do)
how do I change it to work?
package il.ac.tau.cs.sw1.searchengine;
import java.util.*
public class MyWordIndex implements WordIndex {
public SortedMap<String, HashMap<String, Integer>> words;
public HashMap<String, Integer> urls;
public MyWordIndex() {
this.words = new TreeMap<String, HashMap<String, Integer>>();;
this.urls = new HashMap<String, Integer>();
}
#Override
public void index(Collection<String> words, String strURL) {
this.urls.put(strURL, words.size()); // to every page- how many words in it.
String subPrefix = "";
HashMap<String, Integer> help1; // how many times a word appears on that page
for (String word : words) {
if (word == null || word == "") // not a valid word
continue;
word.toLowerCase();
help1 = new HashMap<String, Integer>();
for (int i = 0; i < word.length(); i++) {
subPrefix = word.substring(0, i);
if (this.words.get(subPrefix) == null) { // new prefix
help1.put(strURL, 1);
this.words.put(subPrefix, help1);
}
else { // prefix exists
if (this.words.get(subPrefix).get(strURL) == null)//new URL with old prefix
this.words.get(subPrefix).put(strURL, 1);
else // both url and prefix exists
this.words.get(subPrefix).put(strURL, help1.get(strURL) + 1);
}
}
}
}
#Override
public List<String> searchPrefix(String prefix) {
prefix.toLowerCase();
List<String> urlList = new ArrayList<String>();
for (String word : this.words.keySet()) {
if (word.startsWith(prefix)) {
for (String strUrl : this.words.get(word).keySet()) {
urlList.add(strUrl);
}
}
}
Collections.sort(urlList, new Comparator<String>() {
#Override
public int compare(String strUrl1, String strUrl2) {
Double d1 = this.words.get(word).get(strUrl1) / this.urls.get(strUrl1);
Double d2 = this.words.get(word).get(strUrl2) / this.urls.get(strUrl2);
return Double.compare(d1, d2);
}
});
........
}
These changes take you closer to a solution.
Double d1 = MyWordIndex.this.words.get(word).get(strUrl1) / (double) MyWordIndex.this.urls.get(strUrl1);
Double d2 = MyWordIndex.this.words.get(word).get(strUrl2) / (double) MyWordIndex.this.urls.get(strUrl2);
I don't know what word is supposed to be though as there is no variable with that name in scope.
Suggestion for the for-loop in your index method:
for (int i = 1; i < word.length(); i++) { // no point starting at 0 - empty string
subPrefix = word.substring(0, i);
if (this.words.get(subPrefix) == null) { // new prefix
help1.put(strURL, 1);
this.words.put(subPrefix, help1);
}
else { // prefix exists
Integer count = this.words.get(subPrefix).get(strURL);
if (count == null)//new URL with old prefix
count = 0;
this.words.get(subPrefix).put(strURL, count + 1);
}
}
While we are on this, may I suggest Guava multiset which does this sort of counting for you automatically:
import com.google.common.collect.Multiset;
import com.google.common.collect.HashMultiset;
public class MultiTest{
public final Multiset<String> words;
public MultiTest() {
words = HashMultiset.create();
}
public static void main(String []args) {
MultiTest test = new MultiTest();
test.words.add("Mandible");
test.words.add("Incredible");
test.words.add("Commendable");
test.words.add("Mandible");
System.out.println(test.words.count("Mandible")); // 2
}
}
Finally to solve your problem, this should work, haven't tested:
#Override
public List<String> searchPrefix(String prefix) {
prefix = prefix.toLowerCase(); // Strings are immutable so this returns a new String
Map<String, Double> urlList = new HashMap<String, Double>();
for (String word : this.words.keySet()) {
if (word.startsWith(prefix)) {
for (String strUrl : this.words.get(word).keySet()) {
Double v = urlList.get(strUrl);
if (v == null) v = 0;
urlList.put(strUrl, v + this.words.get(word).get(strUrl));
}
}
}
List<String> myUrls = new ArrayList<String>(urlList.keySet());
Collections.sort(myUrls, new Comparator<String>() {
#Override
public int compare(String strUrl1, String strUrl2) {
return Double.compare(urlList.get(strUrl1) / MyWordIndex.this.urls.get(strUrl1),
urlList.get(strUrl2) / MyWordIndex.this.urls.get(strUrl2));
}
});
return myUrls;
}

Test all possible combinations of rows

The problem is the following. There are multiple rows that have non-unique identifiers:
id value
0: {1,2,3}
0: {1,2,2}
1: {1,2,3}
2: {1,2,3}
2: {1,1,3}
I have the function equals that can compare multiple rows between each other. I need to write a code that selects the rows as an input of the function equals. The rows selected must have unique ids, BUT I should check all possible combinations of unique ids. For instance, if there are 5 rows with ids: 0,0,1,2,3, then I should check the following two combinations of ids: 0,1,2,3 and 0,1,2,3, because 0 apears twice. Of course, each of these two combinations will consist of unique rows that have id=0.
My code snippet is the following:
public class Test {
public static void main(String[] args) {
ArrayList<Row> allRows = new ArrayList<Row>();
allRows.add(new Row(0,new int[]{1,2,3}));
allRows.add(new Row(0,new int[]{1,2,2}));
allRows.add(new Row(1,new int[]{1,2,3}));
allRows.add(new Row(2,new int[]{1,2,3}));
allRows.add(new Row(2,new int[]{1,1,3}));
boolean answer = hasEqualUniqueRows(allRows);
}
private boolean hasEqualUniqueRows(ArrayList<Row> allTokens) {
for (int i=0; i<allTokens.size(); i++) {
ArrayList<Integer[]> rows = new ArrayList<Integer[]>();
rows = findUniqueRows(i,allTokens);
boolean answer = equalsExceptForNulls(rows);
if (answer) return true;
}
return false;
}
// Compare rows for similarities
public static <T> boolean equalsExceptForNulls(ArrayList<T[]> ts) {
for (int i=0; i<ts.size(); i++) {
for (int j=0; j<ts.size(); j++) {
if (i != j) {
boolean answer = equals(ts.get(i),ts.get(j));
if (!answer) return false;
}
}
}
return true;
}
public static <T> boolean equals(T[] ts1, T[] ts2) {
if (ts1.length != ts2.length) return false;
for(int i = 0; i < ts1.length; i++) {
T t1 = ts1[i], t2 = ts2[i];
if (t1 != null && t2 != null && !t1.equals(t2))
return false;
}
return true;
}
class Row {
private String key;
private Integer[] values;
public Row(String k,Integer[] v) {
this.key = k;
this.values = v;
}
public String getKey() {
return this.key;
}
public Integer[] getValues() {
return this.values;
}
}
}
Since the number of rows with unique ids is apriori unknown, I don´t know how to solve this problem. Any suggestions? Thanks.
Edit#1
I updated the code. Now it´s more complete. But it lacks the implementation of the function findUniqueRows. This function should select rows from the ArrayList that have unique keys (ids). Could someone help me to develop this function? Thanks.
Assuming the objective is to find every combination without duplicates you can do this with the following. The test to find duplicates is just to confirm it doesn't generate any duplicates in the first place.
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
public class Main {
public static void main(String... args) {
Bag<Integer> b = new Bag<>();
b.countFor(1, 2);
b.countFor(2, 1);
b.countFor(3, 3);
Set<String> set = new LinkedHashSet<>();
for (List<Integer> list : b.combinations()) {
System.out.println(list);
String s = list.toString();
if (!set.add(s))
System.err.println("Duplicate entry " + s);
}
}
}
class Bag<E> {
final Map<E, AtomicInteger> countMap = new LinkedHashMap<>();
void countFor(E e, int n) {
countMap.put(e, new AtomicInteger(n));
}
void decrement(E e) {
AtomicInteger ai = countMap.get(e);
if (ai.decrementAndGet() < 1)
countMap.remove(e);
}
void increment(E e) {
AtomicInteger ai = countMap.get(e);
if (ai == null)
countMap.put(e, new AtomicInteger(1));
else
ai.incrementAndGet();
}
List<List<E>> combinations() {
List<List<E>> ret = new ArrayList<>();
List<E> current = new ArrayList<>();
combinations0(ret, current);
return ret;
}
private void combinations0(List<List<E>> ret, List<E> current) {
if (countMap.isEmpty()) {
ret.add(new ArrayList<E>(current));
return;
}
int position = current.size();
current.add(null);
List<E> es = new ArrayList<>(countMap.keySet());
if (es.get(0) instanceof Comparable)
Collections.sort((List) es);
for (E e : es) {
current.set(position, e);
decrement(e);
combinations0(ret, current);
increment(e);
}
current.remove(position);
}
}

Categories

Resources