r/programmingchallenges • • Mar 10 '17

Can someone help me with this recursive algorithm? ([a,b], 2) => a b ab a^2 b^2 a^2b b^a a^2 b^2. Working it out in JavaScript.

I'm trying to create a totally general feature mapper. So, for example, with ([a,b, c], 3) i would want every combination. To map up to order 3, it would look like this:

  • a
  • b
  • c
  • a b
  • b c
  • a c
  • a b c
  • a2
  • b2
  • c2
  • a2 b
  • a b2
  • a2 b2
  • b2 c
  • b c2
  • b2 c2
  • a2 c
  • a c2
  • a2 c2
  • a2 b2 c2
  • a3
  • b3
  • c3
  • a3 b
  • a b3
  • a3 b2
  • a2 b3
  • a3 b3
  • etc

You get the point. Thinking through the recursion is just murdering my brain on this one. Any help would be very much appreciated.

My current source is:

var _combinations = (function() {
	var combinations = [];
	function recurse(active, rest) {
		if (rest.length == 0) {
			combinations = combinations.concat(active);
		} 
		else {
			recurse(active + rest[0], rest.slice(1, rest.length)); // [a,b,c], a [b, c], a b [c], a b c 
			recurse(active, rest.slice(1, rest.length));           // a [b, c], a [b, c], a [c]
		}
	}
	recurse([], ['a', 'b', 'c']);
	combinations.sort(function(a,b) {
		return a.length - b.length;
	});
	return combinations;
})()

var _orderedCombinations = (function(combinations) {
	var orderedCombinations = "";
	var curCombo;
	function recurse(active, rest) {
		if (rest.length == 0) {
			if(active.length > 0) {
				var activeArray = active.split('');
				var others = curCombo.filter(function(item) {
					for(var i = 0; i < activeArray.length; i++) {
						if(activeArray[i] === item) {
							return false;
						}
					}
					return true;
				});
				active = "";
				for(var i = 0; i < activeArray.length; i++) {
					active += activeArray[i] + '²';
				}
				active += others.join('');
				orderedCombinations += active + "\r\n";
			}
		} 
		else {
			recurse(active + rest[0], rest.slice(1, rest.length)); 
			recurse(active, rest.slice(1, rest.length));
		}
	}
	combinations.forEach(function(combo) {
		curCombo = combo.split(''); 
		recurse([], curCombo);
	});
	return orderedCombinations;
})(_combinations);
//console.log(_combinations)
console.log(_orderedCombinations);
3 Upvotes

6 comments sorted by

View all comments

Show parent comment

3

u/shadowbaneverything Mar 11 '17

lol, no matter what someone will downvote you on the internet (it wasnt me).

man, this is great! i haven't had a chance to check it yet but that looks like just what i needed. thank you!!!!

if you are interested i asked on codegolf too and the answers were really f'ing impressive. lol but I can't comprehend any of them.

1

u/Plastonick Mar 11 '17

Haha yeah, Codegolf isn't the place for readable code :p I love that someone's done it in LaTeX.

If you don't understand something about my (and I think another commenter suggested the same approach) solution, feel free to ask!