Advertisement
Guest User

Untitled

a guest
Jun 26th, 2019
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 10.72 KB | None | 0 0
  1. var permArr = [], usedChars = [];
  2. function permute(input) {
  3. var i, ch, chars = input.split("");
  4. for (i = 0; i < chars.length; i++) {
  5. ch = chars.splice(i, 1);
  6. usedChars.push(ch);
  7. if (chars.length == 0)
  8. permArr[permArr.length] = usedChars.join("");
  9. permute(chars.join(""));
  10. chars.splice(i, 0, ch);
  11. usedChars.pop();
  12. }
  13. return permArr
  14. };
  15.  
  16. function permutator(inputArr) {
  17. var results = [];
  18.  
  19. function permute(arr, memo) {
  20. var cur, memo = memo || [];
  21.  
  22. for (var i = 0; i < arr.length; i++) {
  23. cur = arr.splice(i, 1);
  24. if (arr.length === 0) {
  25. results.push(memo.concat(cur));
  26. }
  27. permute(arr.slice(), memo.concat(cur));
  28. arr.splice(i, 0, cur[0]);
  29. }
  30.  
  31. return results;
  32. }
  33.  
  34. return permute(inputArr);
  35. }
  36.  
  37. const permutator = (inputArr) => {
  38. let result = [];
  39.  
  40. const permute = (arr, m = []) => {
  41. if (arr.length === 0) {
  42. result.push(m)
  43. } else {
  44. for (let i = 0; i < arr.length; i++) {
  45. let curr = arr.slice();
  46. let next = curr.splice(i, 1);
  47. permute(curr.slice(), m.concat(next))
  48. }
  49. }
  50. }
  51.  
  52. permute(inputArr)
  53.  
  54. return result;
  55. }
  56.  
  57. permutator(['c','a','t']);
  58.  
  59. [ [ 'c', 'a', 't' ],
  60. [ 'c', 't', 'a' ],
  61. [ 'a', 'c', 't' ],
  62. [ 'a', 't', 'c' ],
  63. [ 't', 'c', 'a' ],
  64. [ 't', 'a', 'c' ] ]
  65.  
  66. permutator([1,2,3]);
  67.  
  68. [ [ 1, 2, 3 ],
  69. [ 1, 3, 2 ],
  70. [ 2, 1, 3 ],
  71. [ 2, 3, 1 ],
  72. [ 3, 1, 2 ],
  73. [ 3, 2, 1 ] ]
  74.  
  75. var inputArray = [1, 2, 3];
  76.  
  77. var result = inputArray.reduce(function permute(res, item, key, arr) {
  78. 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);
  79. }, []);
  80.  
  81.  
  82. alert(JSON.stringify(result));
  83.  
  84. /*
  85. Permutate the elements in the specified array by swapping them
  86. in-place and calling the specified callback function on the array
  87. for each permutation.
  88.  
  89. Return the number of permutations.
  90.  
  91. If array is undefined, null or empty, return 0.
  92.  
  93. NOTE: when permutation succeeds, the array should be in the original state
  94. on exit!
  95. */
  96. function permutate(array, callback) {
  97. // Do the actual permuation work on array[], starting at index
  98. function p(array, index, callback) {
  99. // Swap elements i1 and i2 in array a[]
  100. function swap(a, i1, i2) {
  101. var t = a[i1];
  102. a[i1] = a[i2];
  103. a[i2] = t;
  104. }
  105.  
  106. if (index == array.length - 1) {
  107. callback(array);
  108. return 1;
  109. } else {
  110. var count = p(array, index + 1, callback);
  111. for (var i = index + 1; i < array.length; i++) {
  112. swap(array, i, index);
  113. count += p(array, index + 1, callback);
  114. swap(array, i, index);
  115. }
  116. return count;
  117. }
  118. }
  119.  
  120. if (!array || array.length == 0) {
  121. return 0;
  122. }
  123. return p(array, 0, callback);
  124. }
  125.  
  126. // Empty array to hold results
  127. var result = [];
  128. // Permutate [1, 2, 3], pushing every permutation onto result[]
  129. permutate([1, 2, 3], function (a) {
  130. // Create a copy of a[] and add that to result[]
  131. result.push(a.slice(0));
  132. });
  133. // Show result[]
  134. document.write(result);
  135.  
  136. [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,2,1],[3,1,2]]
  137.  
  138. function permutator (arr) {
  139. var permutations = [];
  140. if (arr.length === 1) {
  141. return [ arr ];
  142. }
  143.  
  144. for (var i = 0; i < arr.length; i++) {
  145. var subPerms = permutator(arr.slice(0, i).concat(arr.slice(i + 1)));
  146. for (var j = 0; j < subPerms.length; j++) {
  147. subPerms[j].unshift(arr[i]);
  148. permutations.push(subPerms[j]);
  149. }
  150. }
  151. return permutations;
  152. }
  153.  
  154. perms [] = [[]]
  155. perms xs = [ x:ps | x <- xs , ps <- perms ( xs\[x] ) ]
  156.  
  157. r = [[1]]; // result
  158. t = []; // interim result
  159.  
  160. r array | push next item to | get length many rotations
  161. | each sub array | of each subarray
  162. -----------------------------------------------------------
  163. [[1]] | [[1,2]] | [[1,2],[2,1]]
  164. ----------|-------------------|----------------------------
  165. [[1,2], | [[1,2,3], | [[1,2,3],[2,3,1],[3,1,2],
  166. [2,1]] | [2,1,3]] | [2,1,3],[1,3,2],[3,2,1]]
  167. ----------|-------------------|----------------------------
  168. previous t| |
  169. -----------------------------------------------------------
  170.  
  171. [ 'ABC', 'BAC', 'BCA', 'ACB', 'CAB', 'CBA' ]
  172.  
  173. function perm(xs) {
  174. return xs.length === 0 ? [[]] : perm(xs.slice(1)).reduce(function (acc, ys) {
  175. for (var i = 0; i < xs.length; i++) {
  176. acc.push([].concat(ys.slice(0, i), xs[0], ys.slice(i)));
  177. }
  178. return acc;
  179. }, []);
  180. }
  181.  
  182. console.log(JSON.stringify(perm([1, 2, 3,4])));
  183.  
  184. function permutations( base ) {
  185. if (base.length == 0) return [[]]
  186. return permutations( base.slice(1) ).reduce( function(acc,perm) {
  187. return acc.concat( base.map( function(e,pos) {
  188. var new_perm = perm.slice()
  189. new_perm.splice(pos,0,base[0])
  190. return new_perm
  191. }))
  192. },[])
  193. }
  194.  
  195. #!/usr/bin/env node
  196. "use strict";
  197.  
  198. function perm(arr) {
  199. if(arr.length<2) return [arr];
  200. var res = [];
  201. arr.forEach(function(x, i) {
  202. perm(arr.slice(0,i).concat(arr.slice(i+1))).forEach(function(a) {
  203. res.push([x].concat(a));
  204. });
  205. });
  206. return res;
  207. }
  208.  
  209. console.log(perm([1,2,3,4]));
  210.  
  211. function permutations(arr) {
  212. return (arr.length === 1) ? arr :
  213. arr.reduce((acc, cv, index) => {
  214. let remaining = [...arr];
  215. remaining.splice(index, 1);
  216. return acc.concat(permutations(remaining).map(a => [].concat(cv,a)));
  217. }, []);
  218. }
  219.  
  220. const flatten = xs =>
  221. xs.reduce((cum, next) => [...cum, ...next], []);
  222.  
  223. const without = (xs, x) =>
  224. xs.filter(y => y !== x);
  225.  
  226. const permutations = xs =>
  227. flatten(xs.map(x =>
  228. xs.length < 2
  229. ? [xs]
  230. : permutations(without(xs, x)).map(perm => [x, ...perm])
  231. ));
  232.  
  233. permutations([1,2,3])
  234. // [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
  235.  
  236. perm = x => x[0] ? x.reduce((a, n) => (perm(x.filter(m => m!=n)).forEach(y => a.push([n,...y])), a), []): [[]]
  237.  
  238. var count=0;
  239. function permute(pre,cur){
  240. var len=cur.length;
  241. for(var i=0;i<len;i++){
  242. var p=clone(pre);
  243. var c=clone(cur);
  244. p.push(cur[i]);
  245. remove(c,cur[i]);
  246. if(len>1){
  247. permute(p,c);
  248. }else{
  249. print(p);
  250. count++;
  251. }
  252. }
  253. }
  254. function print(arr){
  255. var len=arr.length;
  256. for(var i=0;i<len;i++){
  257. document.write(arr[i]+" ");
  258. }
  259. document.write("<br />");
  260. }
  261. function remove(arr,item){
  262. if(contains(arr,item)){
  263. var len=arr.length;
  264. for(var i = len-1; i >= 0; i--){ // STEP 1
  265. if(arr[i] == item){ // STEP 2
  266. arr.splice(i,1); // STEP 3
  267. }
  268. }
  269. }
  270. }
  271. function contains(arr,value){
  272. for(var i=0;i<arr.length;i++){
  273. if(arr[i]==value){
  274. return true;
  275. }
  276. }
  277. return false;
  278. }
  279. function clone(arr){
  280. var a=new Array();
  281. var len=arr.length;
  282. for(var i=0;i<len;i++){
  283. a.push(arr[i]);
  284. }
  285. return a;
  286. }
  287.  
  288. function nPr(xs, r) {
  289. if (!r) return [];
  290. return xs.reduce(function(memo, cur, i) {
  291. var others = xs.slice(0,i).concat(xs.slice(i+1)),
  292. perms = nPr(others, r-1),
  293. newElms = !perms.length ? [[cur]] :
  294. perms.map(function(perm) { return [cur].concat(perm) });
  295. return memo.concat(newElms);
  296. }, []);
  297. }
  298.  
  299. let permutations = []
  300.  
  301. permutate([], {
  302. color: ['red', 'green'],
  303. size: ['big', 'small', 'medium'],
  304. type: ['saison', 'oldtimer']
  305. })
  306.  
  307. function permutate (currentVals, remainingAttrs) {
  308. remainingAttrs[Object.keys(remainingAttrs)[0]].forEach(attrVal => {
  309. let currentValsNew = currentVals.slice(0)
  310. currentValsNew.push(attrVal)
  311.  
  312. if (Object.keys(remainingAttrs).length > 1) {
  313. let remainingAttrsNew = JSON.parse(JSON.stringify(remainingAttrs))
  314. delete remainingAttrsNew[Object.keys(remainingAttrs)[0]]
  315.  
  316. permutate(currentValsNew, remainingAttrsNew)
  317. } else {
  318. permutations.push(currentValsNew)
  319. }
  320. })
  321. }
  322.  
  323. [
  324. [ 'red', 'big', 'saison' ],
  325. [ 'red', 'big', 'oldtimer' ],
  326. [ 'red', 'small', 'saison' ],
  327. [ 'red', 'small', 'oldtimer' ],
  328. [ 'red', 'medium', 'saison' ],
  329. [ 'red', 'medium', 'oldtimer' ],
  330. [ 'green', 'big', 'saison' ],
  331. [ 'green', 'big', 'oldtimer' ],
  332. [ 'green', 'small', 'saison' ],
  333. [ 'green', 'small', 'oldtimer' ],
  334. [ 'green', 'medium', 'saison' ],
  335. [ 'green', 'medium', 'oldtimer' ]
  336. ]
  337.  
  338. function permutations(arr) {
  339. var finalArr = [];
  340. function iterator(arrayTaken, tree) {
  341. var temp;
  342. for (var i = 0; i < tree; i++) {
  343. temp = arrayTaken.slice();
  344. temp.splice(tree - 1 - i, 0, temp.splice(tree - 1, 1)[0]);
  345. if (tree >= arr.length) {
  346. finalArr.push(temp);
  347. } else {
  348. iterator(temp, tree + 1);
  349. }
  350. }
  351. }
  352. iterator(arr, 1);
  353. return finalArr;
  354. };
  355.  
  356. const removeItem = (arr, i) => {
  357. return arr.slice(0, i).concat(arr.slice(i+1));
  358. }
  359.  
  360. const makePermutations = (strArr) => {
  361. const doPermutation = (strArr, pairArr) => {
  362. return strArr.reduce((result, permutItem, i) => {
  363. const currentPair = removeItem(pairArr, i);
  364. const tempResult = currentPair.map((item) => permutItem+item);
  365. return tempResult.length === 1 ? result.concat(tempResult) :
  366. result.concat(doPermutation(tempResult, currentPair));
  367. }, []);
  368. }
  369. return strArr.length === 1 ? strArr :
  370. doPermutation(strArr, strArr);
  371. }
  372.  
  373.  
  374. makePermutations(["a", "b", "c", "d"]);
  375. //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"]
  376.  
  377. function stringPermutations ([...input]) {
  378. if (input.length === 1) return input;
  379.  
  380. return input
  381. .map((thisChar, index) => {
  382. const remainingChars = [...input.slice(0, index), ...input.slice(index + 1)];
  383. return stringPermutations(remainingChars)
  384. .map(remainder => thisChar + remainder);
  385. })
  386. .reduce((acc, cur) => [...acc, ...cur]);
  387. }
  388.  
  389. var p = l => l.length<2 ? [l] : l.length==2 ? [l[0]+l[1],l[1]+l[0]] : Function('throw Error("unimplemented")')();
  390.  
  391. function swap(array1, index1, index2) {
  392. var temp;
  393. temp = array1[index1];
  394. array1[index1] = array1[index2];
  395. array1[index2] = temp;
  396. }
  397.  
  398. function permute(a, l, r) {
  399. var i;
  400. if (l == r) {
  401. console.log(a.join(''));
  402. } else {
  403. for (i = l; i <= r; i++) {
  404. swap(a, l, i);
  405. permute(a, l + 1, r);
  406. swap(a, l, i);
  407. }
  408. }
  409. }
  410.  
  411.  
  412. permute(["A","B","C", "D"],0,3);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement