Enumerating a n-item combination of set Java/Groovy - java

I'm trying to write an operation that can enumerate all the combinations of a set of N elements. In other words, the N is unknown and depends on user input. On receiving the N, the function should be able to give all the possible combination of an N-item set, with all elements from a set U. Say, U={A,B,C...J}, 10 elements in total.
One more example of what I need, the function enumerate(3) should tell me all the possible combinations like {A,B,C},{A,D,J} etc., using elements picked from U.
I tried to do this in a way using for loops(initializing an integer since the size of U happen to be 10 in this case, so I can use 123 to denote {A,B,C}...). But the code smells bad and I'd like to know how this can be done in a more elegant with using recursive calls.
Java/Groovy are both acceptable (because I'm trying in them too). If anybody could provide ideas how to do this with closures in Groovy it'll be even more appreciated.
Also please don't use integers to denote the combination as I did, because I think this only applies to a certain U with no generality.
Thanks!

I believe I have the solution.
import java.util.HashSet;
import java.util.Set;
public class Generator<T> {
Set<T> source;
Set<Set<T>> combinations;
public Generator(Set<T> source) {
this.source = source;
}
public static void main(String[] args) {
final Set<String> source = new HashSet<>();
for (char character = 'A'; character <= 'Z'; character++){
source.add(String.valueOf(character));
}
final Generator<String> stringGenerator = new Generator<>(source);
stringGenerator.generate(3);
}
public void generate(int size){
if (size == 0){
return;
}
Set<Set<T>> newCombinations = new HashSet<>();
for (T element : source) {
if (combinations == null || combinations.isEmpty()){
final HashSet<T> set = new HashSet<>();
set.add(element);
newCombinations.add(set);
} else {
for (Set<T> combination : combinations) {
final HashSet<T> newCombination = new HashSet<>(combination);
if (newCombination.add(element)) {
newCombinations.add(newCombination);
}
}
}
}
combinations = newCombinations;
generate(size - 1);
}
}
It was fast dirty implementation, so probably it misses some cases, but it generally demonstrates the idea with at least one working case.

Related

Duplicate items added in ConcurrentSkipListSet

I am trying to maintain insertion order in ConcurrentSkipListSet. The item being added is a custom class type with value(String) and index (int) properties. It implements Comparable interface. The set behaves very inconsistently, sometimes adding duplicate items. Items are considered duplicate if they have same value.
// This is the Item class being added in the set.
final class Item implements Comparable<Item> {
private String value;
private int index;
Item(String val, int idx) {
this.value = val;
this.index = idx;
}
#Override
public int compareTo(Item o) {
// returns zero when values are equal indicating it's a duplicate item.
return this.value.equals(o.value) ? 0 : this.index - o.index;
}
#Override
public String toString() {
return this.value;
}
}
// Below is the main class.
public class Test {
ConcurrentSkipListSet<Item> set;
AtomicInteger index;
public Test() {
set = new ConcurrentSkipListSet<>();
index = new AtomicInteger(0);
}
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
Test test = new Test();
test.addItems();
test.assertItems();
}
}
//trying to test it for 10 times. It always fails for once or twice.
private void assertItems() {
Iterator<Item> iterator = set.iterator();
String[] values = {"yyyy", "bbbb", "aaaa"};
for (String value : values) {
if (!value.equals(iterator.next().toString())) {
System.out.println("failed for :" + set);
return;
}
}
System.out.println("passed for :" + set);
}
//adding items with some duplicate values
private void addItems() {
set.add(new Item("yyyy", index.getAndIncrement()));
set.add(new Item("bbbb", index.getAndIncrement()));
set.add(new Item("yyyy", index.getAndIncrement()));
set.add(new Item("aaaa", index.getAndIncrement()));
}
Expected : passed for :[yyyy, bbbb, aaaa]
Actual : failed for :[yyyy, bbbb, yyyy, aaaa]
But as mentioned before, the result is very inconsistent. Most of the times, it passes.
Please let know what could be the reason for this behavior. Is the 'compareTo()' method wrong? If so, it should always fail.
Ideally we should override 'equals()' method also. But it doesn't matter from sorted set perspective.
Appreciate your help.
You have broken the contract of compareTo, which results in undefined behaviour.
Finally, the implementor must ensure that x.compareTo(y)==0 implies
that sgn(x.compareTo(z)) == sgn(y.compareTo(z)), for all z.
You can easily see that you fail this requirement by pulling your Items out into variables:
final Item x = new Item("yyyy", index.getAndIncrement());
final Item z = new Item("bbbb", index.getAndIncrement());
final Item y = new Item("yyyy", index.getAndIncrement());
System.out.println(x.compareTo(y));
System.out.println(x.compareTo(z));
System.out.println(y.compareTo(z));
Output:
0
-1
1
The signs are different, therefore the contract has been broken.
In your compareTo-implementation you are mixing two different properties in an illegal way. Thus you break the contract of the Comparable interface.
In your comparison, you look at the index only if the values are not equal. This way you do not define an overall natural order for your items. Depending on what comparison is done first, the result of sorting a list will be random.
#Override
public int compareTo(Item o) {
int vCompare = this.value.compareTo(o.value);
if (vCompare == 0) {
return this.index - o.index;
}
return vCompare;
}
This implementation will first compare by value and then by index. It adheres to the Comparable contract and actually defines a natural order for Items and works fine with the Set implementation.
Caution: This sample implementation will break the tests.
The tests are there to show the code behaves as intended. But in this case the intended behavior is the actual issue.
It is incompatible with the Comparable contract.
You cannot sort a list by numeric index and expect a lookup by alphabetical value to succeed. But that's exactly what is attempted here. Sort by index but find duplicate names. It does not work this way.
I don't know the implementation of ConcurrentSkipListSet in detail, but it looks like you need to override the equals method of your class to specify what qualifies two objects to be equal.
This is not an answer, rather a solution to achieve the objective based on root cause finding by #Michael and #Jochen. Modified the Item class comparator to below to have natural order of value String.
public int compareTo(Item o) {
return this.value.compareTo(o.value);
}
And then, added an index based comparator to achieve FIFO retrieval.
// This iterator would now be used in assertItems() method in main class.
private Iterator<Item> getFIFOIterator() {
ArrayList<Item> list = new ArrayList<>(set);
list.sort(Comparator.comparingInt(Item::getIndex));
return list.iterator();
}
#Michael and #Jochen : Appreciate you for taking your time and figuring out the root cause.

How good or bad is it to iterate over a hash-table after checking that it contains a value you want to remove?

I'm currently practicing Algorithm design on HackerRank.
This question pertains to the challenge found here:
https://www.hackerrank.com/challenges/ctci-ransom-note
I solved this problem fairly quickly. However, I ran into an issue that kind of bugs me. I can check for a value on my hash table by using the contains(value) function. However, I didn't see any way to retrieve the key/keys associated with it. In order to do this I was forced to iterate through the table until I found that value again.
While I see the usefulness of Hash Tables... I don't think I am going about solving the problem in an optimal way. I feel like it's a time waster to iterate through the table if I already know it contains the value I want to remove.
One idea I had was to make two tables and have them be the "mirrored" version of one another, as in the original map is using the numbers as keys and the copy or mirrored map uses the keys as the values. However, this seems impractical and I have a feeling that I'm just missing something essential in my knowledge of Hash functions or something.
One reason I'm thinking about this is that I recently made a program that uses a sqlight table to hold data. I only need one loop to search for and delete these values, which makes it more efficient doesn't it?
Could I please get an explanation of how to better achieve what my code below does?
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int m = in .nextInt();
int n = in .nextInt();
String isTrue = "Yes";
Hashtable myTable = new Hashtable();
String magazine[] = new String[m];
for (int magazine_i = 0; magazine_i < m; magazine_i++) {
myTable.put(magazine_i, in .next());
}
Set < Integer > keySet = myTable.keySet();
for (int ransom_i = 0; ransom_i < n; ransom_i++) {
String temp = in .next();
//System.out.println("Line " + ransom_i);
if (!myTable.containsValue(temp)) {
isTrue = "No";
break;
} else {
for (int key: keySet) {
if (myTable.get(key).equals(temp)) {
myTable.remove(key);
//System.out.println("Found it");
break;
}
}
}
}
System.out.println(isTrue);
}
}
Here's an easy way to do it:
public class DenyReturn<K,T> extends Map<K,T>{
private Map m;
private List<T> dontreturn;
public DenyReturn(Map<K,T> m, List<T> dontreturn) {
this.m = m;
this.dontreturn = dontreturn;
}
public T get(Object key) {
T val = super.get(key);
if (dontreturn.contains(val)) return null;
return val;
}
//implement all other methods of Map by invoking the inner map methods
}

Truncating A Java Stack

I have a Stack<String> defined in Java that I use for navigation through a workflow.
What I would like to do is ensure that all values in the stack are unique: when a transition to a "previous" state occurs, I want to remove everything off the stack AFTER the first occurrence of the previous state in the stack.
Is there an easy way to do this?
Edit: More information was requested. Here's an example of the contents of a stack:
[state2, state3, state2, state1, startState]
I need the ability to accept a String, check the stack and see if there are multiple occurrences of it, then pop elements until the "bottommost" occurrence of that String. "Truncate" was probably a bad description of what I wanted to do... "pop until I hit an arbitrary index" is probably closer to what I need.
Consider using deque. Below is the link which explains why should you use it over stack.
Why should I use Deque over Stack?
Stack implements List (among various other interfaces). Get a ListIterator for the last element, and move it backwards until you find an occurrence of the new state, counting how many elements along the way, and then pop that many elements. (If you don't find the new state, then of course you don't pop anything, and you push the new state onto the stack instead).
This might not be particularly efficient, but it will certainly work. If you also want it to be efficient, you probably need to use another data structure (either instead of or as well as the stack). One possibility is to use a Map (in addition to the stack) to keep track of which states are on the stack together with the index at which they occur, or at least a Set to keep track of which states are on the stack (you can then just pop states until you find the one you are looking for). You would maintain the stack and the map or set in parallel.
Or if you were serious about:
"pop until I hit an arbitrary index" is probably closer to what I need.
... then surely this would suffice:
int numberToPop = stack.size() - arbitraryIndex - 1;
while (numberToPop-- > 0) {
stack.pop();
}
Would it simplify your overall code if you created your own container that is basically a set that's a stack? Something like (not a complete implementation):
public class StackSet<T> {
private final Set<T> set;
private final Deque<T> queue;
public StackSet(){
set = new HashSet<>();
queue = new ArrayDeque<>();
}
public void push(T value){
if(set.add(value)){
queue.push(value);
}
}
public T pop(){
return queue.pop();
}
}
That should guarantee no duplicates.
Here's an example of a truncate method with Deque instead of Stack.
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Collection;
import java.util.Deque;
public class ExampleDeque
{
public static void main(String[] args)
{
Deque<String> deque = new ArrayDeque<String>();
deque.offer("startState");
deque.offer("state1");
deque.offer("state2");
deque.offer("state3");
deque.offer("state2");
System.out.println("Before");
print(deque);
deque = truncate(deque, "state2");
System.out.println("After");
print(deque);
}
static Deque<String> truncate (Deque<String> deque, String value)
{
if(!deque.contains(value)) return deque;
String[] array = deque.toArray(new String[deque.size()]);
for(int i = 0; i < array.length; i++)
{
if(array[i] == value)
{
String[] truncated = Arrays.copyOfRange(array, 0, i + 1);
Collection<String> collection = Arrays.asList(truncated);
return new ArrayDeque<>(collection);
}
}
return null;
}
static void print(Deque<String> deque)
{
for(String s : deque)
System.out.println(s);
System.out.println();
}
}

Is it possible to loop setters and getters?

I'm fairly confident that there's no way this could work, but I wanted to ask anyway just in case I'm wrong:
I've heard many times that whenever you have a certain number of lines of very similar code in one batch, you should always loop through them.
So say I have something like the following.
setPos1(getCard1());
setPos2(getCard2());
setPos3(getCard3());
setPos4(getCard4());
setPos5(getCard5());
setPos6(getCard6());
setPos7(getCard7());
setPos8(getCard8());
setPos9(getCard9());
setPos10(getCard10());
setPos11(getCard11());
setPos12(getCard12());
There is no way to cut down on lines of code as, e.g., below, right?
for (i = 0; i < 12; i++) {
setPos + i(getCard + i)());
}
I'm sure this will have been asked before somewhere, but neither Google nor SO Search turned up with a negative proof.
Thanks for quickly confirming this!
No way to do that specifically in Java without reflection, and I don't think it would be worth it. This looks more like a cue that you should refactor your getcard function to take an integer argument. Then you could loop.
This is a simple snippet that shows how to loop through the getters of a certain object to check if the returned values are null, using reflection:
for (Method m : myObj.getClass().getMethods()) {
// The getter should start with "get"
// I ignore getClass() method because it never returns null
if (m.getName().startsWith("get") && !m.getName().equals("getClass")) {
// These getters have no arguments
if (m.invoke(myObj) == null) {
// Do something
}
}
}
Like the others stated, probably it's not an elegant implementation. It's just for the sake of completeness.
You could do it via reflection, but it would be cumbersome. A better approach might be to make generic setPos() and getCard() methods into which you could pass the index of the current item.
You need to ditch the getter/setter pairs, and use a List to store your objects rather then trying to stuff everything into one God object.
Here's a contrived example:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Foo {
public static class Card {
int val;
public Card(int val) {
this.val = val;
}
public int getVal() {
return val;
}
}
public static class Position {
int value;
public Position(Card card) {
this.value = card.getVal();
}
}
public static void main(String[] args) {
List<Card> cards = new ArrayList<Card>(Arrays.asList(new Card(1), new Card(2), new Card(3)));
List<Position> positions = new ArrayList<Position>();
for (Card card : cards) {
positions.add(new Position(card));
}
}
}
You can't dynamically construct a method name and then invoke it (without reflection). Even with reflection it would be a bit brittle.
One option is to lump all those operations into one method like setAllPositions and just call that method.
Alternatively, you could have an array of positions, and then just loop over the array, setting the value at each index.
Card[] cardsAtPosition = new Card[12];
and then something like
public void setCardsAtEachPosition(Card[] valuesToSet) {
// check to make sure valuesToSet has the required number of cards
for (i = 0; i < cardsAtPosition.length; i++) {
cardsAtPosition[i] = valuesToSet[i];
}
}
Reflection would be your only option for your example case.

Array element set pointcut. Is there a workaround?

I just read that it is not possible to define a pointcut on a single array element (bug link). Considering I really need to detect an array element modification, I would like to know if there is any workaround for this kind of problem (a pattern or something).
Something like what is described in this article
public class FieldPointcuts {
static int ar[];
public static void main(String[] args) {
ar = new int[] {100}; //set
ar[0] = 200; //get
}
}
and advice
before(int i, Object s, Object[] a):
arrayset() && args(i, s) && target(a)
{
System.out.println (" Arrayset:["+i+"/"+(a.length-1)+"] = "+s) ;
}
Thanks in advance.
Unfortunately, there is nothing I can think of that will work. The best that I can think of would be to use Lists instead of arrays, but if you are weaving into third party code, this would not be possible.

Categories