Skip to content

Instantly share code, notes, and snippets.

@robbiemu
Last active July 29, 2017 01:18
Show Gist options
  • Save robbiemu/36def0de45dab889ab8032eccbad2e3b to your computer and use it in GitHub Desktop.
Save robbiemu/36def0de45dab889ab8032eccbad2e3b to your computer and use it in GitHub Desktop.
/* I was not happy with my original version ... but I couldn't quiet grasp what was meant by combination. I now think of it as an "ordered combination". You must keep an index to get the set prescribed. This took me a while to realize and then more time to code and debug. */
const flatten = list => list.reduce(
(a, b) => a.concat(Array.isArray(b) ? flatten(b) : b), []
)
class IndexedSubstring {
constructor ({string, index}) {
this.string = string
this.index = index
}
isEqualTo (indexedSubstring) {
return this.string === indexedSubstring.string &&
this.index === indexedSubstring.index
}
}
class ISSet {
constructor () {
this.set = []
}
add () {
flatten(Array.from(arguments)).forEach(is => {
if(!this.set.some(x => x.index === is.index && x.string === is.string))
this.set.push(is)
})
}
filter (facb) { return this.set.filter(facb) }
map (facb) { return this.set.map(facb) }
}
function combinationsOfString(res, str, start=0) {
Array(str.length).fill().forEach((_,i) => { // for i in length
let l = str.substring(0, i)
let ISl = new IndexedSubstring({string:l, index:i+start})
let r = str.substring(i)
let ISr = new IndexedSubstring({string:r, index:r.length+start+i})
res.add(i===0? ISr: [ISl, ISr]) // get rid of initial blank
if (i && l.length > 1) {
let set = [].concat.apply([],
combinationsOfString(new ISSet(), l, start)
).filter(x => !ISl.isEqualTo(x))
res.add(
set,
set.map(x => new IndexedSubstring({
string: x.string + r,
index: ISr.index
}))
)
}
if (i && r.length > 1) {
let set = combinationsOfString(new ISSet(), r, i+start)
.filter(x => !ISr.isEqualTo(x))
res.add(
set,
set.map(x => new IndexedSubstring({
string: l + x.string,
index: x.index
}))
)
}
})
return res
}
combinationsOfString(new ISSet(), "dogs").map(x => x.string)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment