Skip to content

Instantly share code, notes, and snippets.

@lparolari
Created September 22, 2021 22:15
Show Gist options
  • Save lparolari/23cdfb34bbfba869f3fc5991bf8a91ed to your computer and use it in GitHub Desktop.
Save lparolari/23cdfb34bbfba869f3fc5991bf8a91ed to your computer and use it in GitHub Desktop.
Very simple solution for symmetric difference between sets with functional set abstraction. (freecodecamp.org coding interview execise: https://www.freecodecamp.org/learn/coding-interview-prep/algorithms/find-the-symmetric-difference)
function exists(s, x) {
for (let i = 0; i < s.length; i++) {
if (s[i] === x)
return true
}
return false
}
function insert(s, x) {
if (!exists(s, x))
return [...s, x]
return s
}
function union(s1, s2) {
let res = [...s1]
for (let i = 0; i < s2.length; i++) {
res = insert(res, s2[i])
}
return res
}
function intersect(s1, s2) {
let res = []
for (let i = 0; i < s1.length; i++) {
if (exists(s2, s1[i]))
res = insert(res, s1[i])
}
return res
}
function diff(s1, s2) {
let res = []
for (let i = 0; i < s1.length; i++) {
if (!exists(s2, s1[i])) {
res = insert(res, s1[i])
}
}
return res
}
function sym(s1, s2, ...args) {
const symDiff = diff(union(s1, s2), intersect(s1, s2));
if (args.length == 0)
return symDiff
return sym(symDiff, ...args)
}
sym([1, 2, 3], [5, 2, 1, 4]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment