Make all possible combinations of URL with the String - java

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

Related

Best way of calculating permutations [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I'm trying to figure out the best way of finding/automating all the possible permutations for a certain scenario.
I have a program which takes in a set of numbers [X, Y , Z], Each number has a predefined uncertainty. Therefore, I want to run my program against [X, Y , Z], [X+e, Y, Z] [x-e, Y, Z], [X, Y+e, Z] etc. Right now I have built an object which contains all the 27 possibilities and I'm iterating through it in order to provide my program with a new set of input. (I'll run my program 27 times with different set of inputs)
as time goes, I'd need to update my program to take in a bigger set of numbers. So I'm wondering whether there is a better way of calculating all the possible permutations my base set may have.
I'd rather know the way of implementing this instead of using any existing libraries (if there is any). I see this as a learning program. Thanks!
Instead of writing down the the 3x3x3 sets of 3 numbers by hand, you can use nested loops. If you have 3 loops, one inside the other, each running 3 times, you get 27 outputs:
double[] numbers = new double[3];
double[] e = {-1e-6, 0, 1e-6};
for (double eX : e) {
for (double eY : e) {
for (double eZ : e) {
double[] newNumbers = {numbers[0] + eX, numbers[1] + eY, numbers[2] + eZ};
// Run your program using "newNumbers". Just as an example:
System.out.println(Arrays.toString(newNumbers));
}
}
}
As for
as time goes, I'd need to update my program to take in a bigger set of numbers
If the size of the set is going to be small and fixed, you can just add more nested loops. If not, you are going to need more advanced techniques .
Here is a permutation method I found some time ago. It prints them within the method. It only does single dimension permutations but you may be able to adapt it to your needs.
public static void generate(int n, int[] a) {
if (n == 1) {
System.out.println(Arrays.toString(a));
} else {
for (int i = 0; i < n - 1; i++) {
generate(n - 1, a);
if ((n & 1) == 0) {
swap(i, n - 1, a);
} else {
swap(0, n - 1, a);
}
}
generate(n - 1, a);
}
}
public static void swap(int a, int b, int[] array) {
int temp = array[a];
array[a] = array[b];
array[b] = temp;
}
I believe the best way to do this is to implement a Spliterator and wrap it in a Stream:
public interface Combinations<T> extends Stream<List<T>> {
public static <T> Stream<List<T>> of(Collection<T> collection) {
SpliteratorSupplier<T> supplier =
new SpliteratorSupplier<T>(collection);
return supplier.stream();
}
...
}
Which solves the general use-case:
Combinations.of(List.of(X, Y, Z)).forEach(t -> process(t));
Implementing the Spliterator is straightforward but tedious and I have written about it here. The key components are a DispatchSpliterator:
private Iterator<Supplier<Spliterator<T>>> spliterators = null;
private Spliterator<T> spliterator = Spliterators.emptySpliterator();
...
protected abstract Iterator<Supplier<Spliterator<T>>> spliterators();
...
#Override
public Spliterator<T> trySplit() {
if (spliterators == null) {
spliterators = Spliterators.iterator(spliterators());
}
return spliterators.hasNext() ? spliterators.next().get() : null;
}
#Override
public boolean tryAdvance(Consumer<? super T> consumer) {
boolean accepted = false;
while (! accepted) {
if (spliterator == null) {
spliterator = trySplit();
}
if (spliterator != null) {
accepted = spliterator.tryAdvance(consumer);
if (! accepted) {
spliterator = null;
}
} else {
break;
}
}
return accepted;
}
A Spliterator for each prefix:
private class ForPrefix extends DispatchSpliterator<List<T>> {
private final int size;
private final List<T> prefix;
private final List<T> remaining;
public ForPrefix(int size, List<T> prefix, List<T> remaining) {
super(binomial(remaining.size(), size),
SpliteratorSupplier.this.characteristics());
this.size = size;
this.prefix = requireNonNull(prefix);
this.remaining = requireNonNull(remaining);
}
#Override
protected Iterator<Supplier<Spliterator<List<T>>>> spliterators() {
List<Supplier<Spliterator<List<T>>>> list = new LinkedList<>();
if (prefix.size() < size) {
for (int i = 0, n = remaining.size(); i < n; i += 1) {
List<T> prefix = new LinkedList<>(this.prefix);
List<T> remaining = new LinkedList<>(this.remaining);
prefix.add(remaining.remove(i));
list.add(() -> new ForPrefix(size, prefix, remaining));
}
} else if (prefix.size() == size) {
list.add(() -> new ForCombination(prefix));
} else {
throw new IllegalStateException();
}
return list.iterator();
}
}
and one for each combination:
private class ForCombination extends DispatchSpliterator<List<T>> {
private final List<T> combination;
public ForCombination(List<T> combination) {
super(1, SpliteratorSupplier.this.characteristics());
this.combination = requireNonNull(combination);
}
#Override
protected Iterator<Supplier<Spliterator<List<T>>>> spliterators() {
Supplier<Spliterator<List<T>>> supplier =
() -> Collections.singleton(combination).spliterator();
return Collections.singleton(supplier).iterator();
}
}

How to implement recursive function only using stacks?

I have an assignment where I am given recursive functions, and have to rewrite it using only stacks (no recursion). I do not know how to implement the following function
public static void fnc1(int a, int b) {
if (a <= b) {
int m = (a+b)/2;
fnc1(a, m-1);
System.out.println(m);
fnc1(m+1, b);
}
}
The problem is I cannot figure out how to implement recursive functions where there is head and tail recursion.
I tried to loop through a stack, popping a value (a, b) each time and pushing a new value (a, m-1) or (m+1, b) instead of caling "fnc1()", but the output was always out of order.
EDIT:
Here is my attempted Code:
public static void Fnc3S(int a, int b) {
myStack stack1_a = new myStack();
myStack stack1_b = new myStack();
myStack output = new myStack();
stack1_a.push(a);
stack1_b.push(b);
while(!stack1_a.isEmpty()) {
int aVal = stack1_a.pop();
int bVal = stack1_b.pop();
if(aVal <= bVal) {
int m = (aVal+bVal)/2;
stack1_a.push(aVal);
stack1_b.push(m-1);
output.push(m);
stack1_a.push(m+1);
stack1_b.push(bVal);
}
}
while(!output.isEmpty()) {
System.out.println(output.pop());
}
}
And this outputs:
(a, b) = (0, 3)
Recursive:
0
1
2
3
Stack Implementation:
0
3
2
1
to implement this recursion properly you need to understand order in which execution happens and then insert variables in reverse order (as stack pops latest element):
Check code below with comments:
public static void Fnc3S(int a, int b) {
Stack<Integer> stack = new Stack<>(); // single stack for both input variables
Stack<Integer> output = new Stack<>(); // single stack for output variable
stack.push(a); // push original input
stack.push(b);
do {
int bVal = stack.pop();
int aVal = stack.pop();
if (aVal <= bVal) {
int m = (aVal + bVal) / 2;
output.push(m); // push output
stack.push(m + 1); // start with 2nd call to original function, remember - reverse order
stack.push(bVal);
stack.push(aVal); // push variables used for 1st call to original function
stack.push(m - 1);
} else {
if (!output.empty()) { // original function just returns here to caller, so we should print any previously calculated outcome
System.out.println(output.pop());
}
}
} while (!stack.empty());
}

Combine values of a list of data that are almost equal

so i asked before but it seems i wasnt clear enough of what im talking about, so im trying to make it clearer now:
what im trying to do is prepare data for an import. the data i get is human made an not very efficient, so im removing unnecessary entrys and try to combine the data as much as possible.
its for something like a configurator. the data i get looks something like this:
123 : 45 : AB = 12
This means: if Option 1 is 1 OR 2 OR 3 and Option 2 is 4 OR 5 and Option 3 is A OR B the result will be 1 AND 2
i created a class thats something like this:
Class Options{
String opt1;
String opt2;
String opt3;
String optResult;
//and some other stuff
boolean hasSameOptions(Options o){
return opt1.equals(o.opt1) && opt2.equals(o.opt2) && opt3.equals(o.opt3);
}
public void AddOptions(String options) {
for (String s : options.split("")) {
if (!optResult.contains(s)) {
optResult = optResult + s;
}
}
}
}
now, the data is repetitive and can be combined. Like:
12 : 45 : AB = 12
12 : 45 : AB = 3
12 : 45 : AB = 4
This would mean actually mean: 12 : 45 : AB = 1234
So, what i do is break the Strings apart to get only single values with the result, for example:
1 : 4 : A = 12
1 : 4 : B = 12
1 : 5 : A = 12
//and so on.
I make a list of all these Values and then try to Combine them again to get more efficient List.
The first step i do is get all Objects who have the same Options but different Results and combine the results. that happens like this:
public static List<Options> cleanList(List<Options> oldList) {
List<Options> newList = new ArrayList<>();
for (Options item : oldList) {
Options temp = findEqualOptions(newList, item);
if (temp != null)
temp.AddOptions(item.optResult);
else
newList.add(item);
}
return newList;
}
public static <T> T findByProperty(Collection<T> col, Predicate<T> filter) {
return col.stream().filter(Objects::nonNull).filter(filter).findFirst().orElse(null);
}
public static Options findEqualOptions(List<Options> list, Options opt) {
return findByProperty(list, d -> d.hasSameOptions(opt));
}
After that, i try to compress the list even more, by combining elements who have only ONE different value. For example:
1 : 2 : A = 12
1 : 3 : A = 12
-> 1 : 23 : A = 12
i do it like this:
for (int i = 0; i < list.size(); i++) {
for (int j = i + 1; j < list.size(); j++) {
Option o1 = list.get(i);
Option o2 = list.get(j);
int diff1 = 0;
int diff2 = 0;
int diff3 = 0;
int diff4 = 0;
if(!o1.opt1.equals(o2.opt1))
diff1 = 1;
if(!o1.opt2.equals(o2.opt2))
diff2 = 1;
//and so on
if((diff1+diff2+diff3+diff4)>1)
continue;
if(diff1 == 1)
o1.opt1 = o1.opt1 + o2.opt1;
//and so on...
list.remove(j--);
}
}
i do this until there are no more changes. It works well, but slowly. especially the method cleanList().
does anybody have any idea how to make it better? i tried to use a stream to get the whole list of equals options directly like this:
public static <T> List<T> findByMultipleValue(Collection<T> col, Predicate<T> filter) {
return col.stream().filter(filter).collect(Collectors.toList());
}
public static List<Options> getEqualOptionsList(List<Options> optList, Options opt){
return findByMultipleValue(optList, o -> o.hasSameOptions(opt));
}
but that made it A LOT slower.
PS. : its not the complete code, just an example of what im trying to do. I hope it is more understandable this time :)
probably not the most elegant or optimal solution but here is already a quick approach that give the result based on your description. It use the HashMap as proposed in the comment of #Joseph Larson
I went for a set of char to ensure values are not duplicate in it but feel free to adapt :)
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
class Scratch {
public static class Option{
String opt1;
String opt2;
String opt3;
String optResult;
public Option(String opt1, String opt2, String opt3, String optResult) {
this.opt1 = opt1;
this.opt2 = opt2;
this.opt3 = opt3;
this.optResult = optResult;
}
public static String merge(String a, String b){
StringBuilder value = new StringBuilder();
Set<Character> result = new HashSet<>();
for(char c : a.toCharArray()){
result.add(c);
}
for(char c : b.toCharArray()){
result.add(c);
}
for(char c : result){
value.append(c);
}
return value.toString();
}
public Option(Option a, Option b) {
this(merge(a.opt1, b.opt1), merge(a.opt2, b.opt2), merge(a.opt3, b.opt3), merge(a.optResult, b.optResult));
}
String getKey(){
return String.join(":", opt1, opt2, opt3);
}
int distance(Option option){
int diff1 = this.opt1.equals(option.opt1)?0:1;
int diff2 = this.opt2.equals(option.opt2)?0:1;
int diff3 = this.opt3.equals(option.opt3)?0:1;
int diff4 = this.optResult.equals(option.optResult)?0:1;
return diff1 + diff2 + diff3 + diff4;
}
public String toString(){
return getKey();
}
}
public static void main(String[] args) {
Option[] data = new Option[]{
new Option("12", "45", "AB", "12"),
new Option("12", "45", "AB", "3"),
new Option("12", "45", "AB", "4"),
new Option("12", "45", "AC", "1"),
new Option("12", "45", "AC", "12"),
new Option("3", "45", "AC", "13"),
new Option("12", "45", "AD", "12"),
};
mergeExact(data);
mergeClose(data, 1);
}
private static void mergeClose(Scratch.Option[] data, int distance){
Map<Option, Set<Character>> buffer = new HashMap<>();
for(Option option : data) {
boolean found = false;
Option toDelete = null;
for(Map.Entry<Option, Set<Character>> entry : buffer.entrySet()){
if(option.distance(entry.getKey()) <= distance){
Option merged = new Option(entry.getKey(), option);
for(char c : option.optResult.toCharArray()){
entry.getValue().add(c);
}
buffer.put(merged, entry.getValue());
toDelete = entry.getKey();
found = true;
break;
}
}
if(found) {
buffer.remove(toDelete);
}else{
Set<Character> set = new HashSet<>();
for(char c : option.optResult.toCharArray()){
set.add(c);
}
buffer.put(option, set);
}
}
System.out.println(String.format("merge with distance of %d:: %s", distance, buffer));
}
private static void mergeExact(Scratch.Option[] data) {
Map<String, Set<Character>> buffer = new HashMap<>();
for(Option option : data){
Set<Character> item = buffer.computeIfAbsent(option.getKey(), k -> new HashSet<>());
for(char c : option.optResult.toCharArray()){
item.add(c);
}
}
System.out.println("exact merge:: "+buffer);
}
}
output is
exact merge:: {3:45:AC=[1, 3], 12:45:AD=[1, 2], 12:45:AC=[1, 2], 12:45:AB=[1, 2, 3, 4]}
merge with distance of 1:: {12:45:AB=[1, 2, 3, 4], 3:45:AC=[1, 3], 12:45:ACD=[1, 2]}
EDIT: missed a part of the question, updating to add the merge when difference is close. This part is probably even worst that the first one in terms of optimisation but it's a working bases :)

How to check to see which value of a list is highest another another list

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;
}

Arranging corresponding values in descending manner

I have two sets of columns right now but I am not sure how do I program it and what set of class for me to use it. Both are in separate arrays. One for letters and the other for the numbers.
a 12
b 9
c 156
So a corresponds to 12 and b corresponds to 9 etc etc. The list is actually a frequency of letters in a text file so I have 26 of them.
Both are not in the same array. As I have separate arrays for both of them. I want to try and arrange
and make them be in a descending manner.
So that the output would be:
c 156
a 12
b 9
I'm still unsure about various capabilities of ArrayList or HashMap or Tree Map. So any help with this?
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
public class Test {
public static void main(String[] args) {
HashMap<String,Integer> map = new HashMap<String,Integer>();
ValueComparator bvc = new ValueComparator(map);
TreeMap<String,Integer> sorted_map = new TreeMap(bvc);
map.put("A",5);
map.put("B",60);
map.put("C",65);
map.put("D",3);
System.out.println("unsorted map");
for (String key : map.keySet()) {
System.out.println("key/value: " + key + "/"+map.get(key));
}
sorted_map.putAll(map);
System.out.println("results");
for (String key : sorted_map.keySet()) {
System.out.println("key/value: " + key + "/"+sorted_map.get(key));
}
}
}
class ValueComparator implements Comparator {
Map base;
public ValueComparator(Map base) {
this.base = base;
}
public int compare(Object a, Object b) {
if((Integer)base.get(a) < (Integer)base.get(b)) {
return 1;
} else if((Integer)base.get(a) == (Integer)base.get(b)) {
return 0;
} else {
return -1;
}
}
}
You can create a class that has the character and the frequency as data member, and make the class implements Comparable interface.
There are 2 options here, you can either:
Insert all objects into a class that implements List interface (e.g. ArrayList). Then call Collections.sort(List<T> list) on the List.
Insert all objects into TreeSet. You can obtain the sorted item via iterator().
From the question, it seems that the 2 pieces of data are not members of some existing object in the first place. If any chance that they do, you don't have to create a new class for the character and frequency. You can insert the existing object into a List, implement a class that extends on Comparator interface, and sort the List with Collections.sort(List<T> list, Comparator<? super T> c).
You have the following two lists.
[a, b, c]
[12, 9, 156]
First, zip the two lists together, so that you get a list (or a projection thereof) of tuples.
[(a, 12), (b, 9), (c, 156)]
Then sort this list by second item in each tuple, with whatever ordering you want.
[(c, 156), (a, 12), (b, 1)]
Now unzip this back into the two lists.
[c, a, b]
[156, 12, 1]
And there's your answer.
The italicized words indicate the generic abstractions used in the above solution, all of which are likely already available in this library.
Try this:
public static void main(String[] args) throws Exception {
char[] letters = { 'a', 'b', 'c' };
int[] numbers = { 12, 9, 156 };
printDescendind(letters, numbers);
}
public static void printDescendind(char[] letters, int[] numbers) {
class Holder implements Comparable<Holder> {
char letter;
int number;
public int compareTo(Holder o) {
return number != o.number ? o.number - number : letter - o.letter;
}
public String toString() {
return String.format("%s %s", letter, number);
}
}
List<Holder> list = new ArrayList<Holder>(letters.length);
for (int i = 0; i < letters.length; i++) {
Holder h = new Holder();
h.letter = letters[i];
h.number = numbers[i];
list.add(h);
}
Collections.sort(list);
for (Holder holder : list) {
System.out.println(holder);
}
}

Categories