Created
August 24, 2018 20:25
-
-
Save ahamedali95/24aaf7673a06be6c8ac83fddf276329d to your computer and use it in GitHub Desktop.
findUniqueNumbers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Write a function findUniqueNumbers(num1, num2) that takes two integers and returns the unique numbers. | |
//For example: | |
//findUniqueNumbers(8, 8) => null | |
//findUniqueNumbers(88, 9) => 9 | |
//findUniqueNumbers(81233, 12798) => 79 | |
//findUniqueNumbers(123, 890) => 123890 | |
//findUniqueNumbers(9047662375, 631560977) => 412 | |
function findUniqueNumbers(num1, num2) { | |
//Convert the integer to string and apply spread operator to spread the values | |
const collection1 = removeDuplicates([...num1.toString()]); | |
const collection2 = removeDuplicates([...num2.toString()]); | |
//Following filter functions find the symmetric difference of the collections | |
//i.e., [1,2,3,5] && [5,10] => [1,2,3,10] | |
const result = collection1 | |
.filter(ele => collection2.indexOf(ele) === -1) | |
.concat(collection2.filter(ele => collection1.indexOf(ele) === -1)) | |
.join(""); | |
return parseInt(result); | |
} | |
//The following function removes all the duplicates from a collection | |
//i.e., [8,1,2,3,3] => [8,1,2] | |
function removeDuplicates(arr) { | |
//The callback function returns only the numbers that are not in the | |
//subsequence. That is only the non-repeated numbers. | |
return arr.filter((ele, idx, collection) => { | |
return getElementsExcludingCurrent(collection, idx).indexOf(ele) === -1; | |
}); | |
} | |
//The following function gets all elements in the array excluding the current number | |
//i.e., getElementsExcludingCurrent([8,1,2,3,3], 4) => [8,1,2,3] + [] => [8,1,2,3] | |
function getElementsExcludingCurrent(arr, i) { | |
return arr.slice(0, i).concat(arr.slice(i + 1)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment