Skip to content

Instantly share code, notes, and snippets.

@r9software
Created June 27, 2019 23:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save r9software/1c3d3e358fd951fa07dd5d3c9600396e to your computer and use it in GitHub Desktop.
Save r9software/1c3d3e358fd951fa07dd5d3c9600396e to your computer and use it in GitHub Desktop.
/** I will have to go with the linear solution */
/***
* Write a function called "reconcileHelper" that processes two arrays of integers.
Each array will have only distinct numbers (no repeats of the same integer in the same array), and the arrays are not sorted.
Your job is to find out which numbers are in array 1, but not array 2, and which numbers are in array 2, but not in array
* */
public String reconcileHelper(int[] array1, int[] array2){
//add to a hashmap so it is simpler to use
HashMap<Integer,Integer> tmp1=extractHashMap(array1);
HashMap<Integer,Integer> tmp2=extractHashMap(array2);
if(tmp1.size()<=tmp2.size())
deleteRepeated(tmp1,tmp2);
else
deleteRepeated(tmp2,tmp1);
String array1Result = getStringFromHash(tmp1);
String array2Result = getStringFromHash(tmp2);
return "Numbers that are in array 1 that aren't in array 2: \n"+
array1Result+"\nNumbers that are in array 1 that aren't in array 2: \n"+
array2Result;
}
/**
* Helper to extract integer to hashmap
*/
private HashMap<Integer, Integer> extractHashMap(int[] array1) {
HashMap<Integer, Integer> tmp1=new HashMap<>();
for(int a:array1){
tmp1.put(a,a);
}
return tmp1;
}
/***
* Helper that returns the result
*/
private String getStringFromHash( HashMap<Integer, Integer> tmp1) {
String array1Result="";
for (Map.Entry<Integer, Integer> entry : tmp1.entrySet())
array1Result = array1Result + entry.getKey() + " ";
return array1Result;
}
/**
* Helper that deletes the repeated from smaller to bigger hashmap
*
* */
private void deleteRepeated(HashMap<Integer, Integer> smaller, HashMap<Integer, Integer> bigger){
Iterator itSmaller = smaller.entrySet().iterator();
Iterator itBigger = bigger.entrySet().iterator();
while (itSmaller.hasNext())
{
Map.Entry itemSmaller = (Map.Entry) itSmaller.next();
while (itBigger.hasNext())
{
Map.Entry itemBigger = (Map.Entry) itBigger.next();
if((int)itemBigger.getValue()==(int)itemSmaller.getValue()){
itSmaller.remove();
itBigger.remove();
break; //break so we dont call next on the same
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment