Skip to content

Instantly share code, notes, and snippets.

@geraldyeo
Created July 28, 2016 12:28
Show Gist options
  • Save geraldyeo/6c4eaea8a1a6bcc480cac5328cbff664 to your computer and use it in GitHub Desktop.
Save geraldyeo/6c4eaea8a1a6bcc480cac5328cbff664 to your computer and use it in GitHub Desktop.
Interwave letters
// Given two strings, print all the inter-leavings
// of the Strings in which characters from two strings
// should be in same order as they were in original strings.
//
// e.g.
// for "abc", "de", print all of these:
// adebc, abdec, adbce, deabc, dabce, etc, etc
var s1 = 'abc'
var s2 = 'de'
var output = '';
function interweave(s1, s2, i1, i2, output) {
if (i1 === s1.length && i2 === s2.length) {
console.log(output);
}
if (i1 < s1.length) {
interweave(s1, s2, i1+1, i2, output+s1.charAt(i1));
}
if (i2 < s2.length) {
interweave(s1, s2, i1, i2+1, output+s2.charAt(i2));
}
}
interweave(s1, s2, 0, 0, output)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment