Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var permArr = [], usedChars = [];
- function permute(input) {
- var i, ch, chars = input.split("");
- for (i = 0; i < chars.length; i++) {
- ch = chars.splice(i, 1);
- usedChars.push(ch);
- if (chars.length == 0)
- permArr[permArr.length] = usedChars.join("");
- permute(chars.join(""));
- chars.splice(i, 0, ch);
- usedChars.pop();
- }
- return permArr
- };
- function permutator(inputArr) {
- var results = [];
- function permute(arr, memo) {
- var cur, memo = memo || [];
- for (var i = 0; i < arr.length; i++) {
- cur = arr.splice(i, 1);
- if (arr.length === 0) {
- results.push(memo.concat(cur));
- }
- permute(arr.slice(), memo.concat(cur));
- arr.splice(i, 0, cur[0]);
- }
- return results;
- }
- return permute(inputArr);
- }
- const permutator = (inputArr) => {
- let result = [];
- const permute = (arr, m = []) => {
- if (arr.length === 0) {
- result.push(m)
- } else {
- for (let i = 0; i < arr.length; i++) {
- let curr = arr.slice();
- let next = curr.splice(i, 1);
- permute(curr.slice(), m.concat(next))
- }
- }
- }
- permute(inputArr)
- return result;
- }
- permutator(['c','a','t']);
- [ [ 'c', 'a', 't' ],
- [ 'c', 't', 'a' ],
- [ 'a', 'c', 't' ],
- [ 'a', 't', 'c' ],
- [ 't', 'c', 'a' ],
- [ 't', 'a', 'c' ] ]
- permutator([1,2,3]);
- [ [ 1, 2, 3 ],
- [ 1, 3, 2 ],
- [ 2, 1, 3 ],
- [ 2, 3, 1 ],
- [ 3, 1, 2 ],
- [ 3, 2, 1 ] ]
- var inputArray = [1, 2, 3];
- var result = inputArray.reduce(function permute(res, item, key, arr) {
- return res.concat(arr.length > 1 && arr.slice(0, key).concat(arr.slice(key + 1)).reduce(permute, []).map(function(perm) { return [item].concat(perm); }) || item);
- }, []);
- alert(JSON.stringify(result));
- /*
- Permutate the elements in the specified array by swapping them
- in-place and calling the specified callback function on the array
- for each permutation.
- Return the number of permutations.
- If array is undefined, null or empty, return 0.
- NOTE: when permutation succeeds, the array should be in the original state
- on exit!
- */
- function permutate(array, callback) {
- // Do the actual permuation work on array[], starting at index
- function p(array, index, callback) {
- // Swap elements i1 and i2 in array a[]
- function swap(a, i1, i2) {
- var t = a[i1];
- a[i1] = a[i2];
- a[i2] = t;
- }
- if (index == array.length - 1) {
- callback(array);
- return 1;
- } else {
- var count = p(array, index + 1, callback);
- for (var i = index + 1; i < array.length; i++) {
- swap(array, i, index);
- count += p(array, index + 1, callback);
- swap(array, i, index);
- }
- return count;
- }
- }
- if (!array || array.length == 0) {
- return 0;
- }
- return p(array, 0, callback);
- }
- // Empty array to hold results
- var result = [];
- // Permutate [1, 2, 3], pushing every permutation onto result[]
- permutate([1, 2, 3], function (a) {
- // Create a copy of a[] and add that to result[]
- result.push(a.slice(0));
- });
- // Show result[]
- document.write(result);
- [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,2,1],[3,1,2]]
- function permutator (arr) {
- var permutations = [];
- if (arr.length === 1) {
- return [ arr ];
- }
- for (var i = 0; i < arr.length; i++) {
- var subPerms = permutator(arr.slice(0, i).concat(arr.slice(i + 1)));
- for (var j = 0; j < subPerms.length; j++) {
- subPerms[j].unshift(arr[i]);
- permutations.push(subPerms[j]);
- }
- }
- return permutations;
- }
- perms [] = [[]]
- perms xs = [ x:ps | x <- xs , ps <- perms ( xs\[x] ) ]
- r = [[1]]; // result
- t = []; // interim result
- r array | push next item to | get length many rotations
- | each sub array | of each subarray
- -----------------------------------------------------------
- [[1]] | [[1,2]] | [[1,2],[2,1]]
- ----------|-------------------|----------------------------
- [[1,2], | [[1,2,3], | [[1,2,3],[2,3,1],[3,1,2],
- [2,1]] | [2,1,3]] | [2,1,3],[1,3,2],[3,2,1]]
- ----------|-------------------|----------------------------
- previous t| |
- -----------------------------------------------------------
- [ 'ABC', 'BAC', 'BCA', 'ACB', 'CAB', 'CBA' ]
- function perm(xs) {
- return xs.length === 0 ? [[]] : perm(xs.slice(1)).reduce(function (acc, ys) {
- for (var i = 0; i < xs.length; i++) {
- acc.push([].concat(ys.slice(0, i), xs[0], ys.slice(i)));
- }
- return acc;
- }, []);
- }
- console.log(JSON.stringify(perm([1, 2, 3,4])));
- function permutations( base ) {
- if (base.length == 0) return [[]]
- return permutations( base.slice(1) ).reduce( function(acc,perm) {
- return acc.concat( base.map( function(e,pos) {
- var new_perm = perm.slice()
- new_perm.splice(pos,0,base[0])
- return new_perm
- }))
- },[])
- }
- #!/usr/bin/env node
- "use strict";
- function perm(arr) {
- if(arr.length<2) return [arr];
- var res = [];
- arr.forEach(function(x, i) {
- perm(arr.slice(0,i).concat(arr.slice(i+1))).forEach(function(a) {
- res.push([x].concat(a));
- });
- });
- return res;
- }
- console.log(perm([1,2,3,4]));
- function permutations(arr) {
- return (arr.length === 1) ? arr :
- arr.reduce((acc, cv, index) => {
- let remaining = [...arr];
- remaining.splice(index, 1);
- return acc.concat(permutations(remaining).map(a => [].concat(cv,a)));
- }, []);
- }
- const flatten = xs =>
- xs.reduce((cum, next) => [...cum, ...next], []);
- const without = (xs, x) =>
- xs.filter(y => y !== x);
- const permutations = xs =>
- flatten(xs.map(x =>
- xs.length < 2
- ? [xs]
- : permutations(without(xs, x)).map(perm => [x, ...perm])
- ));
- permutations([1,2,3])
- // [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
- perm = x => x[0] ? x.reduce((a, n) => (perm(x.filter(m => m!=n)).forEach(y => a.push([n,...y])), a), []): [[]]
- var count=0;
- function permute(pre,cur){
- var len=cur.length;
- for(var i=0;i<len;i++){
- var p=clone(pre);
- var c=clone(cur);
- p.push(cur[i]);
- remove(c,cur[i]);
- if(len>1){
- permute(p,c);
- }else{
- print(p);
- count++;
- }
- }
- }
- function print(arr){
- var len=arr.length;
- for(var i=0;i<len;i++){
- document.write(arr[i]+" ");
- }
- document.write("<br />");
- }
- function remove(arr,item){
- if(contains(arr,item)){
- var len=arr.length;
- for(var i = len-1; i >= 0; i--){ // STEP 1
- if(arr[i] == item){ // STEP 2
- arr.splice(i,1); // STEP 3
- }
- }
- }
- }
- function contains(arr,value){
- for(var i=0;i<arr.length;i++){
- if(arr[i]==value){
- return true;
- }
- }
- return false;
- }
- function clone(arr){
- var a=new Array();
- var len=arr.length;
- for(var i=0;i<len;i++){
- a.push(arr[i]);
- }
- return a;
- }
- function nPr(xs, r) {
- if (!r) return [];
- return xs.reduce(function(memo, cur, i) {
- var others = xs.slice(0,i).concat(xs.slice(i+1)),
- perms = nPr(others, r-1),
- newElms = !perms.length ? [[cur]] :
- perms.map(function(perm) { return [cur].concat(perm) });
- return memo.concat(newElms);
- }, []);
- }
- let permutations = []
- permutate([], {
- color: ['red', 'green'],
- size: ['big', 'small', 'medium'],
- type: ['saison', 'oldtimer']
- })
- function permutate (currentVals, remainingAttrs) {
- remainingAttrs[Object.keys(remainingAttrs)[0]].forEach(attrVal => {
- let currentValsNew = currentVals.slice(0)
- currentValsNew.push(attrVal)
- if (Object.keys(remainingAttrs).length > 1) {
- let remainingAttrsNew = JSON.parse(JSON.stringify(remainingAttrs))
- delete remainingAttrsNew[Object.keys(remainingAttrs)[0]]
- permutate(currentValsNew, remainingAttrsNew)
- } else {
- permutations.push(currentValsNew)
- }
- })
- }
- [
- [ 'red', 'big', 'saison' ],
- [ 'red', 'big', 'oldtimer' ],
- [ 'red', 'small', 'saison' ],
- [ 'red', 'small', 'oldtimer' ],
- [ 'red', 'medium', 'saison' ],
- [ 'red', 'medium', 'oldtimer' ],
- [ 'green', 'big', 'saison' ],
- [ 'green', 'big', 'oldtimer' ],
- [ 'green', 'small', 'saison' ],
- [ 'green', 'small', 'oldtimer' ],
- [ 'green', 'medium', 'saison' ],
- [ 'green', 'medium', 'oldtimer' ]
- ]
- function permutations(arr) {
- var finalArr = [];
- function iterator(arrayTaken, tree) {
- var temp;
- for (var i = 0; i < tree; i++) {
- temp = arrayTaken.slice();
- temp.splice(tree - 1 - i, 0, temp.splice(tree - 1, 1)[0]);
- if (tree >= arr.length) {
- finalArr.push(temp);
- } else {
- iterator(temp, tree + 1);
- }
- }
- }
- iterator(arr, 1);
- return finalArr;
- };
- const removeItem = (arr, i) => {
- return arr.slice(0, i).concat(arr.slice(i+1));
- }
- const makePermutations = (strArr) => {
- const doPermutation = (strArr, pairArr) => {
- return strArr.reduce((result, permutItem, i) => {
- const currentPair = removeItem(pairArr, i);
- const tempResult = currentPair.map((item) => permutItem+item);
- return tempResult.length === 1 ? result.concat(tempResult) :
- result.concat(doPermutation(tempResult, currentPair));
- }, []);
- }
- return strArr.length === 1 ? strArr :
- doPermutation(strArr, strArr);
- }
- makePermutations(["a", "b", "c", "d"]);
- //result: ["abcd", "abdc", "acbd", "acdb", "adbc", "adcb", "bacd", "badc", "bcad", "bcda", "bdac", "bdca", "cabd", "cadb", "cbad", "cbda", "cdab", "cdba", "dabc", "dacb", "dbac", "dbca", "dcab", "dcba"]
- function stringPermutations ([...input]) {
- if (input.length === 1) return input;
- return input
- .map((thisChar, index) => {
- const remainingChars = [...input.slice(0, index), ...input.slice(index + 1)];
- return stringPermutations(remainingChars)
- .map(remainder => thisChar + remainder);
- })
- .reduce((acc, cur) => [...acc, ...cur]);
- }
- var p = l => l.length<2 ? [l] : l.length==2 ? [l[0]+l[1],l[1]+l[0]] : Function('throw Error("unimplemented")')();
- function swap(array1, index1, index2) {
- var temp;
- temp = array1[index1];
- array1[index1] = array1[index2];
- array1[index2] = temp;
- }
- function permute(a, l, r) {
- var i;
- if (l == r) {
- console.log(a.join(''));
- } else {
- for (i = l; i <= r; i++) {
- swap(a, l, i);
- permute(a, l + 1, r);
- swap(a, l, i);
- }
- }
- }
- permute(["A","B","C", "D"],0,3);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement