Java array checksum independent of element order - java

Say I have two arrays, e.g. [B,D,C,A] and [B,A,D,C]. What mechanism would generate the same checksum on both arrays (and any array containing a permutation of their elements)?
In the following example, check_a and check_b will not be equal. Putting the elements into an alphabetical order is not an option, as the objects in the array might not be Strings or anything sortable at all.
String[] a = {"B","D","C","A"};
String[] b = {"B","A","D","C"};
String check_a = a.hashCode();
String check_b = b.hashCode();

Quick example
public class ArrayHash {
public static void main(String[] args) {
String[] one = new String[]{"A", "B", "C", "D"};
String[] two = new String[]{"D", "C", "B", "A"};
System.out.println("One = " + one.hashCode());
System.out.println("Two = " + two.hashCode());
System.out.println("Method for one = "+hash(one));
System.out.println("Method for two = "+hash(two));
}
private static int hash(Object[] array) {
int ret = 0;
for (Object c : array) {
ret += (124567890 + c.hashCode()) * c.hashCode();
}
return ret;
}
}
it gives an output
One = 366712642
Two = 1829164700
Method for one = 266
Method for two = 266
as you can see, you have to iterate over all elements and sum (or multiply) their hashes. that will give you same result no matter in what order they are.

Lets suppose you have a function that get checksumm of elements. To get checksum you want you need to find operation with Commutative property there are lot of them. For example +, *, ^

Related

Combine 2 lists according to compared object's variable [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
So I have got 2 object lists A and B. I will call merged list c. That is from the class Flights.
public class Flights{
String airline;
}
Where
The list looks like this
list<Flights>a
list<Flights>b
list<Flights>c
The combined list should always have alternating element from A and B.
e.g. c = a(1), b(1), a(3), b(4). C also should have the following properties
The position of elements in C should be such that elements in A are compare to B where elements that have the same airline is placed beside one another. E.g. merged list = A.united, B.united, A.emirates, B.emirates and so on
By matching I mean placing the elements after the other
After completing step 1, it should then find the elements in A and B that were previously not added to C. Match all those elements to all elements from the other list. E.g. if a(5) wasn't added to the list previously, it will be matched with b(1-5)
Then, go through each element in A and make sure there is a match with all elements in B.
Example
Say A has 1,2,3 and B has 2,3,10, then the output as [2,2],[3,3],[1,2],[1,3],[1,10],[2,3],[2,10],[3,10]
The brackets mean each match.
My current code
List<Flights> secondaryFlights // filled a
List<Flights> primaryFlights // filled b
List<Flights> flightsList // Empty c
for ( Flights p : primaryFlights) {
for ( Flights s : secondaryFlights) {
if ( p.getAirline().equals(s.getAirline())) {
flightsList.add(p);
flightsList.add(s);
}
}
}
while( !flightsList.containsAll(primaryFlights) || !flightsList.containsAll(secondaryFlights)) {
}
Get more understanding from
String a[] = { "A", "E", "I" };
String b[] = { "O", "U" };
List list = new ArrayList(Arrays.asList(a));
list.addAll(Arrays.asList(b));
Object[] c = list.toArray();
System.out.println(Arrays.toString(c));
Fixed with something like this
List<String>list1 = new ArrayList<String>();
list1.add("tommy");
list1.add("Alex");
list1.add("Bryan");
list1.add("Tom");
list1.add("William");
list1.add("Willy");
List<String>list2 = new ArrayList<String>();
list2.add("Alex");
list2.add("William");
list2.add("Candice");
list2.add("Jane");
list2.add("Parker");
list2.add("tommy");
List<String>merged = new ArrayList<String>();
for ( String str1 : list1) {
for ( String str2 : list2) {
if ( str1.equals(str2)) {
merged.add("[ " + str1);
merged.add(str2 + "]");
}
}
}
for ( String str1 : list1) {
for ( String str2 : list2) {
if ( !str1.equals(str2)) {
merged.add("[ " + str1);
merged.add(str2 + "]");
}
}
}
System.out.println(merged);
Looking at your examples, you need matched once first and all unmatched ones in their order, so you can do like below:
Create a set of second list and loop over the first list. If element in first list exists in the set, add them.
For unmatched ones, create a new set to avoid duplicating results. If the pair is un-visited, you can add it to the result. You can create the pair in a way it is convenient and doesn't overlap under any scenario. Taking your 1,2,3 and 2,3,10 example, I have separated integers by a pipe symbol(|). Java does seem to have Pair class too. You can use it if you like.
Snippet:
private static List<Integer> getData(List<Integer> l1,List<Integer> l2){
List<Integer> res = new ArrayList<>();
Set<Integer> set = new HashSet<>(l2);
for(int i=0;i<l1.size();++i){
int x = l1.get(i);
if(set.contains(x)){
res.add(x);
res.add(x);
}
}
Set<String> pairs = new HashSet<>();
for(int i=0;i<l1.size();++i){
int x = l1.get(i);
for(int j=0;j<l2.size();++j){
int y = l2.get(j);
int min = Math.min(x,y);
int max = Math.max(x,y);
if(x != y && !pairs.contains(min + "|" + max)){
res.add(x);
res.add(y);
pairs.add(min + "|" + max);
}
}
}
return res;
}
Driver code:
public static void main(String[] args) {
List<Integer> l1 = Arrays.asList(1,2,3);
List<Integer> l2 = Arrays.asList(2,3,10);
System.out.println(getData(l1,l2).toString());
}
Note: You can replicate the same logic for your Flight class dataset. To compare strings, you can use compareTo method.

Sort an Array based on Another Array with different values

I want to sort an array based on another array with different values.
Consider the following:
Reference Array: {"A","B","C"}
Obtained Array1: {"C","A","B"}
Obtained Array2: {"cc","aa","bb"}
Obtained Array3: {"123","asrd","sdhg"}
values corresponding to
A -> aa and asrd
B -> bb and sdhg
C -> cc and 123
I want to sort my obtained array 1, 2 and 3 in the order specified by my reference array.
Expected Result:
Obtained Array after sorting: {"A","B","C"}
Obtained Array2 after sorting: {"aa","bb","cc"}
Obtained Array3 after sorting: {"asrd","sdhg","123"}
PS: The reference array elements order can be anything ([A,B,C] or [C,B,A] etc). Obtained arrays 2 and 3 should be sorted accordingly.
I know how to sort Obtained Array 1 in the order of my reference array. I tried a logic to sort obtained arrays 2 and 3 but the result i get is wrong
String[] referenceArray = new String[] { "A", "B", "C" };
String[] obtainedArray1 = new String[] { "C", "A", "B" };
String[] obtainedArray2 = new String[] { "cc", "aa", "bb" };
String[] obtainedArray3 = new String[] { "123", "asrd", "sdhg" };
final List<String> referenceArrayList= Arrays.asList(referenceArray);
ArrayList<String> obtainedArray1_List= new ArrayList<String>(Arrays.asList(obtainedArray1));
ArrayList<String> obtainedArray2_List= new ArrayList<String>(Arrays.asList(obtainedArray2));
ArrayList<String> obtainedArray3_List= new ArrayList<String>(Arrays.asList(obtainedArray3));
// Sorting ObtainedArray1_List - This works Fine
Collections.sort(obtainedArray1_List, Comparator.comparing(s -> referenceArrayList.indexOf(s)));
//Sorting obtainedArray2_List - Not Working
Collections.sort(obtainedArray2_List, Comparator.comparing(s -> referenceArrayList.indexOf(obtainedArray1[obtainedArray2_List.indexOf(s)])));
The result of obtainedArray2_List after sorting: ["aa","cc","bb"]
Expected Result is ["aa","bb","cc"]
As JB Nizet already said, you're making your life complicated. You have three separate arrays, while their contents are related. You're saying that A, aa and asrd belong together, as well as B, bb and sdhg, and C, cc and 123.
These can be thought of three properties of a single object. That's the point of object-orientation. You should define a class which represents these three properties:
public class Holder {
private String letter;
private String lower;
private String text;
public Holder(String letter, String lower, String text) {
this.letter = letter;
this.lower = lower;
this.text = text;
}
public String getLetter() {
return this.letter;
}
#Override
public String toString() {
return String.format("Holder(letter=%s, lower=%s, text=%s)",
this.letter, this.lower, this.text);
}
}
Your three arrays should never exist in the first place, but instead being an array or collection with Holder objects. For convenience, here is a transformation to a List<Holder>.
List<Holder> holders = IntStream.range(0, obtainedArray1.length)
.mapToObj(i -> new Holder(obtainedArray1[i], obtainedArray2[i], obtainedArray3[i]))
.collect(Collectors.toList());
Now you can simply sort collect a new, sorted list, instead of three separate sorted arrays.
List<String> referenceList = Arrays.asList("A", "B", "C");
List<Holder> sorted = holders.stream()
.sorted(Comparator.comparing(t -> referenceList.indexOf(t.letter)))
.collect(Collectors.toList());

How can I generate lists of size k elements if I am given a bunch of combinations, each combination having k-1 elements?

In a way, it is the reverse of the problem of generating subsets of size k from an array containing k+1 elements.
For example, if somebody gives me the pairs {a,b} , {a,c} , {b,c} , {a,e} , {b,e}, {a,f}, I need an algorithm that will tell me the triplets {a,b,c} and (a,b,e} are completely covered for their pairwise combinations in the pairs given to me. I need to generalize from pair/triplet in my example to the case k/k+1
My hunch was that there would be a well documented and efficient algorithm that solves my problem. Sadly, searching the internet did not help obtaining it. Questions already posted in stackoverflow do not cover this problem. I am thereby compelled to post this question to find my solution.
I'm not familiar with an established algorithm for this and you didn't ask for a specific language so I've written up a C# algorithm that accomplishes what you've asked and matches the test values provided. It doesn't have much real-world error checking. I've got a .Net fiddle you can run to see the results within a web browser. https://dotnetfiddle.net/ErwTeg
It works by converting your array of arrays (or similar container) to a dictionary with every unique value as a key and the value for each key being every value that is found within any list with the key. From your sample, a gets {b,c,e,f} (We'll call them friends, and this is what the GetFriends function does)
The AreFriendsWithEachother function indicates whether or not all passed values are friends with all other values.
The results of the friends list are then fed to the MakeTeam function which makes teams of a given size by enumerating every friend that a key has and trying every size length permutation of these. For instance, in the original example a has friend permutations of {{a,b,c},{a,b,e},{a,b,f},{a,c,b},{a,c,e},{a,c,f},{a,e,b},{a,e,c},{a,e,f},{a,f,b},{a,f,c},{a,f,e}}. Of these we make sure that all three values are friends by checking the friends list we created earlier. If all values within a permutation are friends then we add it to our results cache. The results would then be culled for all duplicate sets. This is handled in C# by using HashSet which only adds items that aren't already on the list.
The MakeTeam function is terrible looking because it contains a runtime variable number of loops (normally visualized by foreach). I am rolling up and down through enumerators and emulating the foreach loops myself.
I've included versions for MakeTeamOf3 and MakeTeamOf4 which show static loop structures, which are very easily adapted when you know your k value ahead of time.
The same code is provided here
using System;
using System.Collections.Generic;
using System.Linq;
namespace kfromkm1 // k elements from k minus 1
{
public class Program
{
static readonly string[][] pairs =
{
new string[] { "a", "b" },
new string[] { "a", "c" },
new string[] { "b", "c" },
new string[] { "a", "e" },
new string[] { "b", "e" },
new string[] { "a", "f" }
};
static readonly string[][] pairsExpectedResult =
{
new string[] { "a", "b", "c" },
new string[] { "a", "b", "e" }
};
static readonly string[][] triplets =
{
new string[] { "a", "b", "c" },
new string[] { "a", "b", "d" },
new string[] { "a", "c", "d" },
new string[] { "b", "c", "d" },
new string[] { "b", "c", "e" }
};
static readonly string[][] tripletsExpectedResults =
{
new string[] { "a", "b", "c", "d" }
};
public static void Main(string[] args)
{
Dictionary<string, HashSet<string>> friendsList = GetFriends(pairs);
Dump(nameof(pairs), pairs);
Console.WriteLine();
Dump(nameof(pairsExpectedResult), pairsExpectedResult);
Console.WriteLine();
HashSet<HashSet<string>> teams = MakeTeams(friendsList, 3);
Dump(nameof(teams), teams);
Console.WriteLine();
friendsList = GetFriends(triplets);
Dump(nameof(triplets), triplets);
Console.WriteLine();
Dump(nameof(tripletsExpectedResults), tripletsExpectedResults);
Console.WriteLine();
teams = MakeTeams(friendsList, 4);
Dump(nameof(teams), teams);
Console.ReadLine();
}
// helper function to display results
static void Dump<T>(string name, IEnumerable<IEnumerable<T>> values)
{
Console.WriteLine($"{name} =");
int line = 0;
bool notfirst;
foreach (IEnumerable<T> layer in values)
{
Console.Write($"{line}: {{");
notfirst = false;
foreach (T value in layer)
{
if (notfirst)
Console.Write($", {value}");
else
{
Console.Write(value);
notfirst = true;
}
}
Console.WriteLine("}");
line++;
}
}
// items are friends if they show up in a set (pair in the example) together
// list can be a list of lists, array of arrays, list of arrays, etc
// {a, b} means a and b are friends
// {a, b, c} means a is friends with b and c, b is friends with a and c, c is friends with a and b
static Dictionary<T, HashSet<T>> GetFriends<T>(IEnumerable<IEnumerable<T>> list) where T : IEquatable<T>
{
Dictionary<T, HashSet<T>> result = new Dictionary<T, HashSet<T>>();
foreach (IEnumerable<T> set in list) // one set at a time
{
foreach (T current in set) // enumerate the set from front to back
{
foreach (T other in set) // enumerate the set with a second pointer to compare every item
{
if (!current.Equals(other)) // ignore self
{
if (!result.ContainsKey(current)) // initialize this item's result hashset
result[current] = new HashSet<T>();
result[current].Add(other); // add friend (hashset will ignore duplicates)
}
}
}
}
return result;
}
// indicates whether or not all items are friends
static bool AreFriendsWithEachother<T>(Dictionary<T, HashSet<T>> friendsList, IEnumerable<T> values)
{
if (friendsList == null) // no list = no results
throw new ArgumentNullException(nameof(friendsList));
foreach (T first in values)
{
if (!friendsList.ContainsKey(first)) // not on list, has no friends
return false;
foreach (T other in values)
{
if (!friendsList[first].Contains(other) && !first.Equals(other)) // false if even one doesn't match, don't count self as non-friend for computational ease
return false;
}
}
return true; // all matched so true
}
// size represents how many items should be in each team
static HashSet<HashSet<T>> MakeTeams<T>(Dictionary<T, HashSet<T>> friendsList, int size) where T : IEquatable<T>
{
if (friendsList == null) // no list = no results
throw new ArgumentNullException(nameof(friendsList));
if (size < 2)
throw new ArgumentOutOfRangeException(nameof(size), size, "Size should be greater than 2");
HashSet<HashSet<T>> result = new HashSet<HashSet<T>>(HashSet<T>.CreateSetComparer());
T[] values = new T[size];
IEnumerator<T>[] enumerators = new IEnumerator<T>[size - 1]; // gotta cache our own enumerators with a variable number of "foreach" layers
int layer;
bool moveNext;
foreach (T key in friendsList.Keys) // this is a mess because it's a runtime variable number of copies of enumerators running over the same list
{
values[0] = key;
for (int index = 0; index < size - 1; index++)
enumerators[index] = friendsList[key].GetEnumerator();
moveNext = true;
layer = 0;
while (moveNext)
{
while (layer < size - 1 && moveNext)
{
if (enumerators[layer].MoveNext())
layer++;
else
{
if (layer == 0)
moveNext = false;
else
{
enumerators[layer].Reset();
layer--;
}
}
}
for (int index = 1; index < size; index++)
values[index] = enumerators[index - 1].Current;
if (values.Distinct().Count() == size && AreFriendsWithEachother(friendsList, values))
result.Add(new HashSet<T>(values));
layer--;
}
}
return result;
}
// provided as an example
static HashSet<HashSet<T>> MakeTeamsOf3<T>(Dictionary<T, HashSet<T>> friendsList) where T : IEquatable<T>
{
if (friendsList == null) // no list = no results
throw new ArgumentNullException(nameof(friendsList));
HashSet<HashSet<T>> result = new HashSet<HashSet<T>>(HashSet<T>.CreateSetComparer());
T[] values;
foreach (T key in friendsList.Keys) // start with every key
{
foreach (T first in friendsList[key])
{
foreach (T second in friendsList[key])
{
values = new T[] { key, first, second };
if (values.Distinct().Count() == 3 && AreFriendsWithEachother(friendsList, values)) // there's no duplicates and they are friends
result.Add(new HashSet<T>(values));
}
}
}
return result;
}
// provided as an example
static HashSet<HashSet<T>> MakeTeamsOf4<T>(Dictionary<T, HashSet<T>> friendsList) where T : IEquatable<T>
{
if (friendsList == null) // no list = no results
throw new ArgumentNullException(nameof(friendsList));
HashSet<HashSet<T>> result = new HashSet<HashSet<T>>(HashSet<T>.CreateSetComparer());
T[] values;
foreach (T key in friendsList.Keys) // start with every key
{
foreach (T first in friendsList[key])
{
foreach (T second in friendsList[key])
{
foreach (T third in friendsList[key])
{
values = new T[] { key, first, second, third };
if (values.Distinct().Count() == 4 && AreFriendsWithEachother(friendsList, values)) // there's no duplicates and they are friends
result.Add(new HashSet<T>(values));
}
}
}
}
return result;
}
}
}
Function to generate SetOfkNbrdElementCombinations
//to generate outputs with k values greater than two (pairwise)
Take SetOfkNbrdElementCombinations as an input
//Example - {{a,b},{b,c},...} : here k is 2 (though variable name will retain the letter k); elements are a,b,c,..; sets {a,b}, {b,c} are 2-numbered combinations of elements
Take nextSize as an input
//nextSize should be bigger than the k in the input SetOfkNbrdElementCombinations by 1.
//For example above where k is 2, nextSize would be 3
//Logic:
Comb(SetOfkNbrdElementCombinations={S1,S2,...Sn},nextSize) = {S1,Comb({SetOfkNbrdElementCombinations-a1},nextSize-l)}
//The recursive algorithm specified in the line above generates sets containing unique nextSize numbered combinations of the combinations in SetOfkNbrdElementCombinations
//Code that implements the algorithm is available at Rosetta code
//In our example it would generate {{{a,b},{b,c},{b,e}},{{a,b},{b,c},{a,c}},...} (triplets of pairs)
//My logic to generate nextSize numbered combinations of elements is below
// Example of my output, based on the example input above, would be {{a,b,c},{a,c,e},...}
Intitialize oputSetOfkNbrdElementCombinations to empty
For each nextSize sized combination of combinations generated above
Join the contained combinations in a union set
If the nbr of elements in the union is nextSize, add the union set to oputSetOfkNbrdElementCombinations
Output oputSetOfkNbrdElementCombinations
Here is the Java implementation of the algorithm. You can copy, paste and run on https://ide.geeksforgeeks.org/
/* This program takes k sized element combinations and generates the k+1 sized element combinations
that are possible.
For example if the program is given {a,b,c}, {a,b,d}, {a,c,d}, {b,c,d}, {b,c,e}
which are 3 sized combinations, it will identify {a,b,c,d} the
4 sized combination that has all the 3 sized combinations of its elements covered
in what were provided to the program
The program can scale to higher values of k.
The program uses only the hashset data structure
*/
//AUTHOR: Suri Chitti
import java.util.*;
public class uppOrdCombsFromCombs {
//sample CSV strings...let us pretend they came from a file
//This is a sample of input to the program
static String[] csvStrings = new String[] {
"a,b,c",
"a,b,d",
"a,c,d",
"b,c,d",
"b,c,e"
};
/* //Another sample CSV strings...let us pretend they came from a file
//This is another sample of input to the program
static String[] csvStrings = new String[] {
"a,b",
"b,c",
"a,c",
"c,e",
"a,e"
};
*/ /////USE ONLY ONE SAMPLE
//Before we can generate a k+1 sized combination of elements from a bunch
//of k sized combinations we need to obtain groups containing k+1 number of
// k sized combinations
//The method below, called SetOfNxtSizeNbrdkElementCombinationsets will do it for us
//It takes a bunch of k sized combinations called the parameter hsSetOfkNbrdCombinationsetsPrm
//which is a hashset.
//It also takes k+1 as input called the parameter nextSize which is an integer
//Outputs k+1 sized groups of k sized element combinations as a variable called hsSetOfNxtSizeNbrdCombinationsets
//which is hashset
static HashSet SetOfNxtSizeNbrdCombinationsets(HashSet hsSetOfkNbrdCombinationsetsPrm, Integer nextSize){
HashSet hsSetOfNxtSizeNbrdCombinationsets = new HashSet<>();//is it better to have nested <HashSet> tokens in this declaration?
HashSet hsRecursor = new HashSet<>(hsSetOfkNbrdCombinationsetsPrm);
Iterator <HashSet> loopIterator1 = hsSetOfkNbrdCombinationsetsPrm.iterator();
while (loopIterator1.hasNext()) {
HashSet hsName = loopIterator1.next();
if(nextSize == 1){
hsSetOfNxtSizeNbrdCombinationsets.add(hsName);
}
else {
HashSet hsConc1 = new HashSet<>();
hsRecursor.remove(hsName);
hsConc1 = SetOfNxtSizeNbrdCombinationsets(hsRecursor,nextSize-1);
Iterator <HashSet> loopIterator2 = hsConc1.iterator();
while (loopIterator2.hasNext()) {
HashSet hsConc2 = new HashSet<>();
HashSet hsConc3 = new HashSet<>();
hsConc2 = loopIterator2.next();
Iterator <HashSet> loopIterator3 = hsConc2.iterator();
Object obj = loopIterator3.next();
if (String.class.isInstance(obj)) {
hsConc3.add(hsName);
hsConc3.add(hsConc2);
}
else {
loopIterator3 = hsConc2.iterator();
hsConc3.add(hsName);
while (loopIterator3.hasNext()) {
hsConc3.add(loopIterator3.next());
}
}
hsSetOfNxtSizeNbrdCombinationsets.add(hsConc3);
}
}
}
return hsSetOfNxtSizeNbrdCombinationsets;
}
//The method below takes the k+1 sized groupings of k sized element combinations
//generated by the method above and generates all possible K+1 sized combinations of
//elements contained in them
//Name of the method is SetOfkNbrdCombinationsets
//It takes the k+1 sized groupings in a parameter called hsSetOfNxtSizeNbrdCombinationsetsPrm which is a HashSet
//It takes the value k+1 as a parameter called nextSize which is an Integer
//It returns k+1 sized combinations as a variable called hsSetOfkNbrdCombinationsets which is a HashSet
//This is the intended output of the whole program
static HashSet SetOfkNbrdCombinationsets(HashSet hsSetOfNxtSizeNbrdCombinationsetsPrm, Integer nextSize){
HashSet hsSetOfkNbrdCombinationsets = new HashSet<>();
HashSet hsMember = new HashSet<>();
Iterator <HashSet> loopIteratorOverParam = hsSetOfNxtSizeNbrdCombinationsetsPrm.iterator();
while (loopIteratorOverParam.hasNext()) {
hsMember = loopIteratorOverParam.next();
HashSet hsInnerUnion = new HashSet<>();
Iterator <HashSet> loopIteratorOverMember = hsMember.iterator();
while (loopIteratorOverMember.hasNext()) {
HashSet hsInnerMemb = new HashSet<>(loopIteratorOverMember.next());
hsInnerUnion.addAll(hsInnerMemb);
}
if (hsInnerUnion.size()==nextSize) {
HashSet hsTemp = new HashSet<>(hsInnerUnion);
hsSetOfkNbrdCombinationsets.add(hsTemp);
}
hsInnerUnion.clear();
}
return hsSetOfkNbrdCombinationsets;
}
public static void main(String args[]) {
HashSet hsSetOfkNbrdCombinationsets = new HashSet<>();//should this have nested <HashSet> tokens?
HashSet hsSetOfNxtSizeNbrdCombinationsets = new HashSet<>();//should this have nested <HashSet> tokens?
Integer innerSize=0,nextSize = 0;
System.out.println("Ahoy");
//pretend we are looping through lines in a file here
for(String line : csvStrings)
{
String[] linePieces = line.split(",");
List<String> csvPieces = new ArrayList<String>(linePieces.length);
for(String piece : linePieces)
{
//System.out.println(piece); will print each piece in separate lines
csvPieces.add(piece);
}
innerSize = csvPieces.size();
Set<String> hsInner = new HashSet<String>(csvPieces);
hsSetOfkNbrdCombinationsets.add(hsInner);
}
nextSize = innerSize+1; //programmatically obtain nextSize
hsSetOfNxtSizeNbrdCombinationsets = SetOfNxtSizeNbrdCombinationsets(hsSetOfkNbrdCombinationsets,nextSize);
hsSetOfkNbrdCombinationsets = SetOfkNbrdCombinationsets(hsSetOfNxtSizeNbrdCombinationsets, nextSize);
System.out.println("The " + nextSize + " sized combinations from elements present in the input combinations are: " + hsSetOfkNbrdCombinationsets);
} //end of main
} //end of class

Comparing the list of elements and string array

I have the below code
public void main() throws InterruptedException {
//expected messages to be displayed in tool tip are as below
String[] expected_tootltip_Msgs = {"A", "B", "C",
"D","E","F","G"};
//declaring integer to know the total count
Integer counter=0;
Thread.sleep(20000);
List<WebElement> listImages=driver.findElements(By.tagName("img"));
System.out.println("No. of Images: "+listImages.size());
for(WebElement image:listImages)
{
if(image.isDisplayed())
{
counter++;
System.out.println(image.getAttribute("alt"));
}
}
System.out.println("No. of total displable images: "+counter);
}
How can I compare the String expected_tooltip_msgs and the output displayed from the list elements? If both are same my test case would be pass. Can someone help me on this?
I think what you need is to put the expected Strings into a List (if you expect duplicates) or a Set (if you have no duplicates).
e.g.
List<String> expectedTooltips = Lists.newArrayList("A", "B", "C",
"D","E","F","G"); // this uses the Guava library helper method, you could use List.of if you are using Java 9
...
List<String> actualTooltips = new ArrayList<>();
for(WebElement image:listImages)
{
if(image.isDisplayed())
{
actualTooltips.add(image.getAttribute("alt"));
}
}
boolean areTooltipsAsExpected = expectedTooltips.equals(actualTooltips);

Finding common between Array-list of Strings

I've array-list "mArrayListvarinats" of String which contains pipe separated strings like
225356175|225356176|225356177|225356178|225356179|225356180|225356181|225356182|225356183|225356184|225356185|225356186|225356187|225356188|225356189|225356190|225356191|225356192
The size of mArrayListvarinats may be 0 upto n Now I want to find out common string between those Strings from mArrayListvarinats.
for ex. if it's size is two the code may be like as follows.
String temp[] = mArrayListvarinats.get(0).split("\\|");
String temp1[] = mArrayListvarinats.get(1).split("\\|");
and then loop will work on both the arrays to get common one.But how to achieve it for any no of size inside the loop as those temp arrays will be generated in the loop on mArrayListvarinats?
Something like this should work :
HashSet<String> allStrings = new HashSet<String>();
HashSet<String> repeatedStrings = new HashSet<String>();
for(String pipedStrings: mArrayListvarinats){
String temp[] = pipedStrings.split("\\|");
for(String str : temp){
if(!allStrings.add(str)){
repeatedStrings.add(str);
}
}
}
This way, you will have your HashSet allStrings that contains all your unique strings. And the other HashSet repeatedStrings which contains all the strings that appears more than once.
Try this short version:
public static void main(String[] args) {
List<String> a = new ArrayList<>(asList("225356176|225356177|225356178".split("\\|")));
List<String> b = new ArrayList<>(asList("225356175|225356176|225356177".split("\\|")));
a.retainAll(b);
b.retainAll(a);
System.out.println(b);
}
OUTPUT:
[225356176, 225356177]
Iterate through each of them and put them in a HashSet. If you get false while adding it means it's already there. You can put it in a separate Hashset. this way you will get a hashset of all unique string and an another hashset of strings that occured multiple times
Set<String> set=new HashSet<String>();
for (int i = 0; i < temp.length; i++) {
set.add(str[i]);
}
for (int i = 0; i < temp1.length; i++) {
set.add(str1[i]);
}
The set will contain common strings.
If you are only interested in getting common strings found in mArrayListvarinats variable, then you should use Set data structure. Set in java will only contain unique entries. From the example strings it sounds that you are collecting string which has numeric values. So there won't be any problem due to that. But if you are collecting alpha numeric value then you need to take care of alphabet's case, as Set collects values which are case sensitive. So for Set A is not equal to a.
This will find common among all your lists.
List<String> common = Arrays.asList(mArrayListvarinats.get(0).split("\\|"));
for(String varinats: mArrayListvarinats){
List<String> items = Arrays.asList(varinats.split("\\|"));
common = ListUtils.intersection(items,common);
}
But for this you have to use Apache commons collection library , which I hope is not a issue for you :)
Below code will return you the frequency of each string present in the array.
public static void main(String[] args) {
String mArrayListvarinats = "225356175,225356176,225356177,225356178,225356179,225356180,225356181,225356182,225356183,225356184,225356185,225356186,225356187,225356188,225356189,225356190,225356191,225356192,225356192";
List<String> list = Arrays.asList(mArrayListvarinats.split(","));
Set<String> uniqueWords = new HashSet<String>(list);
for (String word : uniqueWords) {
System.out.println(word + ": " + Collections.frequency(list, word));
}
}
String with frequency more than 1 are duplicates/common. You can take actions based on frequency.

Categories

Resources