No Repeats is giving me conniption fits UPDATE: SOLVED. :D **Spoilers**

No Repeats is giving me conniption fits UPDATE: SOLVED. :D **Spoilers**
0

#1

I tried to do it on my own forever–I even almost had it by just brute force using random numbers but after listening to a Code Newbies podcast where the guest said it was important to be able to recognize when an algorithm is going to be useful, I decided to do it the right way, but I’m just not groking Heap’s algorithm. I’ve been googling and have copy/pasted then played with several of the ones I found, but i still don’t get it to the point that I can really use it in any meaningful way.

#3

I get that. I just don’t get it. I’ve been reading all about Heap’s algorithm, but I don’t feel like I really understand it.

#4

Recursion IS twisted and difficult to wrap your head around. Simple recursion everyone gets, but when each iteration is doing something tricky it quickly gets more difficult to conceptualize what the heck is going on. Sometimes writing a few iterations out on paper helps. Also have a look at the code I posted above, it is well commented.

#5

I tried to. when I clicked the link the code box was empty.

#6

Sorry about that - I’m not sure why that’s happening, but here it is below…

#7

okay. I was able to figure it out non-recursively by examining the graphic at the wikipedia page (I think anyhow, at least it looks right so far):

``````console.log(perm('aab'))

function perm(str) {
var arr = str.split('')
var permList = []
var n = arr.length
for (var i = 0; i < n; i++) {
for (var j = 1; j < n - 1; j++) {
permList.push(swap(arr, 0, j).join(''))
}
permList.push(swap(arr, 0, n - 1).join(''))
}
return permList
}

function swap(a, p1, p2) {
var temp
temp = a[p1]
a[p1] = a[p2]
a[p2] = temp
return a
}
``````

now to see if I can make it recursive.

edit: Hmm. I tried plugging it into the problem to see how it was going so far and it didn’t seem to work for the bigger ones: it says 42 instead of a number in the thousands. I’m missing something… I think it might be another loop.

#8

I have resolved this one recently and was a big pain, I made a tree with all the possibilities who has every branch to get the permutations.

#9

Well, I think I got it working for reals:

``````var permutation = []
perm(['a','b','c','d'])
console.log(permutation)

function perm(arr, n){
n = n||arr.length
if(n === 1) permutation.push(arr.join(''))
else{
for(var i = 0; i < n - 1; i++){
perm(arr, n - 1)
if(n % 2) arr = swap(arr, 0, n - 1)
else arr = swap(arr, i, n - 1)
}
perm(arr, n - 1)
}
}

function swap(a, p1, p2){
var temp = a[p1]
a[p1] = a[p2]
a[p2] = temp
return a
}
``````

Granted, it was javascriptization of the pseudo code example at the wikipedia page with a little bit of tweaking. But I had tried it before and it didn’t work. I’m gonna do some tracing of variables as it works tonight at work to try to understand it better, but I feel good enough about this to go ahead and finish the challenge. (the regex part was easy.)

I’m gonna look into closures too, cause if I understand it correctly, that is how I would be able to not have permutation as a global.

#10

Aaannnd solved it:

``````function permAlone(str) {
var permutation = [];
var strArr = str.split('');
return perm(strArr);

function perm(arr, n) {
n = n || arr.length;
if (n === 1) {
var arrStr = arr.join('');
if (arrStr.search(/(.)\1/) === -1) permutation.push(arrStr);
} else {
for (var i = 0; i < n - 1; i++) {
perm(arr, n - 1);
if (n % 2) arr = swap(arr, 0, n - 1);
else arr = swap(arr, i, n - 1);
}
perm(arr, n - 1);
}
if (n === arr.length) return permutation.length;
}

function swap(a, p1, p2) {
var temp = a[p1];
a[p1] = a[p2];
a[p2] = temp;
return a;
}

}
``````

Now all I have left is twitch, tic tac toe, and simon!

#11

Hey Chad, there is simple solution to this. Wrap your code in a immediately-invoked function expression (or IIFE, pronounced “iffy”). This not only cleans up the Global address space but makes your code private. Then using a return statement in a very particular way you can make public only the functions you want to expose. This is the “Module” pattern.

See the code here.

An example::

#12

The IIFE pattern is awesome not just for elegance, but for security as well. Aside from bugs in the JS engine itself, nothing can get at `privateMethod` from the outside. In the world of client-side JS where browsers routinely load third-party code on a whim, that can poke around and mess with other JS at will, encapsulation===security.

Might want to be careful about the term “Module” though: ES6 has modules now, they’re implemented differently, and while I think the IFFE pattern is superior, the confusion over an overloaded term is only going to mount over time.

#13

There term Module was taken directly from here:

I cannot say how official it is though…

#14

From what I can tell, ES6 modules were in fact based on that pattern (I wasn’t there, I wouldn’t know). Stuff like webpack implements modules as functions (there’s not much else they can use), so they share common DNA. I just say “IIFE” these days and leave the word “module” to the hash the standards committee made of it

#15

I tried doing this, and my solution works, except that I get a ‘RangeError: Maximum call stack size exceeded’ for inputs that are more than 6 characters. How did you get around that limitation?

#16

1. When you are forming each permutation, and you come across one that has repeating letters, you do not need to keep going.

this is the difference between only going through a handful of steps to solve the test case ‘aaaaaaaa’, or finding 40320 permutations just to filter every single one out afterwards.

2. You are asked to return a number, not a list. Storing an array of thousands of strings is unnecessary.

You dont actually need the list of strings, you just need to keep track of how many you find. This is only possible when you keep (1) in mind.

You can think of the problem in this way:

How many unique routes can I take through a string, without passing through identical letters consecutively?

Then you can set up a much simpler algorithm to traverse the letters of a string and count how many times it can successfully get through the entire string without hitting the same letter twice.

This is one possible solution using these two ideas:

``````function permAlone(s,p){

return s.split('').reduce(
(x,y,i)=> y==p ? x : s.length==1? 1 : x + permAlone(s.slice(0,i) + s.slice(i+1),y) ,0);

}``````

#17

I dint’t read your solution but I also used recursion to find the permutations and regular expression to filter. The problem is, it works for small strings but, for example, for ‘aaaaak’ it get stuck. Is there a possibility that the code is very inefficient or it is wrong? My solution…

#18

I saw what my problem was.

#19

Hi, I’m really trying to understand Recursions… it’s really hard and frustrationg… The basic function for factorials is easy to understand but for no Repeats… I just can’t seem to rap my head around how recursion works…

I’ve actually gotten all greens with the problem but I haven’t submitted it. My code is a snippet Frankenstein from various stackoverflow code which I don’t completely understand and I was hoping to really understand recursion before I move on.

I’m trying to understand the code you pasted as a jpeg in relation to this one which I got from the chat forums:

``````
from: Ghulam Shabir @ghulamshabir at the chat rooms for javascript

function generate(n, arr) {
if (n === 1) {
console.log(arr);
return;
}

for( var i = 0; i < n; i + + ) {
generate (n - 1, arr);

if( n % 2 === 0 )
swap(arr, i,  n - 1);
else
swap(arr, 0, n - 1);
}
}
function swap(arr, idxA, idxB) {
var temp = arr[idxA];
arr[idxA] = arr[idxB];
arr[idxB] = temp;
}

``````

They seem similar to me and both seem to use heap’s method as Ghulam Shabir @ghulamshabir suggested I study in producing the original permutations… The filtering I also found on the chat forums. My main concern is understanding just the block of code that produces the permutations…

I understand heap’s method is the following:

Given N is the total number of elements in an array ARR and a counter `i` which counts until N:
Get all the permutations of the first N-1 elements and then just add the last element of ARR to these for the first iteration of the counter ‘i’. as `i` counts up… depending on whether the N elements is odd or even, switch the last element of ARR with either the ‘i’ element or the first element.

I get the switch part of the code for switching the first, last and `i` elements after every succession of `I`. What I don’t get is where in the code the permutations of the first N-1 elements are generated? Does anybody know a step-by-step walkthrough for the code itself? there are numerous diagrams on the net but I haven’t found one that explains how the “computer” applies these “plans” in recursion. Thanks again… hope to figure it out before I move on… Thanks.