Skip to content

Instantly share code, notes, and snippets.

@taroyanaka
Forked from CrossEye/permutations.js
Created October 23, 2018 04:26
Show Gist options
  • Save taroyanaka/479d4be5c5143aeb14c459115d296711 to your computer and use it in GitHub Desktop.
Save taroyanaka/479d4be5c5143aeb14c459115d296711 to your computer and use it in GitHub Desktop.
Find permutations of a list of (distinct) values. Uses Ramda
// https://codepen.io/taroyanaka/pen/bmxoMw?editors=0011
const R = require('ramda');
const permutations = (tokens, subperms = [[]]) =>
R.isEmpty(tokens) ?
subperms :
R.addIndex(R.chain)((token, idx) => permutations(
R.remove(idx, 1, tokens),
R.map(R.append(token), subperms)
), tokens);
R.map(R.join(''), permutations(['A', 'B', 'C']));
//=> ["ABC", "ACB", "BAC", "BCA", "CAB", "CBA"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment