Unique characters in each string: Difference between revisions
Content added Content deleted
(→{{header|JavaScript}}: Added a version in JavaScript) |
|||
Line 287: | Line 287: | ||
"3ycxdb1fgxa2yz" |
"3ycxdb1fgxa2yz" |
||
]</lang> |
]</lang> |
||
{{Out}} |
|||
<pre>123abc</pre> |
|||
=={{header|JavaScript}}== |
|||
<lang javascript>(() => { |
|||
"use strict"; |
|||
// onceInEach :: [String] -> String |
|||
const onceInEach = ws => |
|||
// Characters which occur exactly once |
|||
// in each word in the list. |
|||
0 < ws.length ? (() => { |
|||
const |
|||
wordCount = ws.length, |
|||
charFreqs = charCounts(ws.join("")), |
|||
shared = ws.slice(1).reduce( |
|||
(a, x) => intersect(a)(new Set([...x])), |
|||
new Set([...ws[0]]) |
|||
); |
|||
return sort( |
|||
[...shared].filter( |
|||
c => wordCount === charFreqs[c] |
|||
) |
|||
).join(""); |
|||
})() : ""; |
|||
// ---------------------- TEST ----------------------- |
|||
const main = () => |
|||
onceInEach([ |
|||
"1a3c52debeffd", |
|||
"2b6178c97a938stf", |
|||
"3ycxdb1fgxa2yz" |
|||
]); |
|||
// --------------------- GENERIC --------------------- |
|||
// charCounts :: String -> Dict Char Int |
|||
const charCounts = cs => |
|||
// Dictionary of chars, with the |
|||
// frequency of each in cs. |
|||
[...cs].reduce( |
|||
(a, c) => Object.assign( |
|||
a, { |
|||
[c]: 1 + (a[c] || 0) |
|||
} |
|||
), {} |
|||
); |
|||
// intersect :: Set -> Set -> Set |
|||
const intersect = a => |
|||
// The intersection of two sets. |
|||
b => new Set([...a].filter(i => b.has(i))); |
|||
// sort :: Ord a => [a] -> [a] |
|||
const sort = xs => |
|||
// An A-Z sorted copy of xs. |
|||
[...xs].slice().sort( |
|||
(a, b) => a < b ? -1 : (a > b ? 1 : 0) |
|||
); |
|||
// MAIN --- |
|||
return main(); |
|||
})();</lang> |
|||
{{Out}} |
{{Out}} |
||
<pre>123abc</pre> |
<pre>123abc</pre> |