Reputation: 51
I'm doing a simple recurse with node to generate all the strings of 10 characters. I've a memory leak during execution. The code is below. Any ideas ?
I think it may be linked to the console.log(word) line. Without this line, the code seems to work. However, instead if printing the result to the screen, my final goal is to achieve an http request with the generated word. I've tried that without screen printing and it generates an out of memory as well.
var char = [
'a',
'b',
'c',
'd',
'e',
'f',
'g',
'h',
'i',
'j',
'k',
'l',
'm',
'n',
'o',
'p',
'q',
'r',
's',
't',
'u',
'v',
'w',
'x',
'y',
'z',
' ',
'\''
];
function recurseWord( keyword ){
if ( keyword.length >= 10 ){
return null ;
}
else{
for ( var index = 0 ; index < char.length ; ++index){
keyword = keyword + char [index];
console.log (keyword);
recurseWord (keyword) ;
keyword = keyword.substring(0, keyword.length-1);
}
}
return null ;
}
var keyword = "";
recurseWord(keyword);
Upvotes: 1
Views: 153
Reputation: 8587
Jeannot, you must be funny enough, you can't generate them that way.
That's 26 to the power of 10 = 141'167'095'653'376 operations (i.e. ~half a million billion operations).
You have to measure it out, even with C/C++ (which is rather low and near cpu level), you should run below 1 billion operations only (by the power of CPUs in present year 2016).
Upvotes: 0
Reputation: 871
First of all you need to move the recursive call out of the for loop. Otherwise the loop will never exit because index
will stay at 0.
function recurseWord( keyword ){
console.log (keyword);
if ( keyword.length >= 10 ){
return null ;
}
else{
for ( var index = 0 ; index < char.length ; index++){
keyword = keyword + char [index];
console.log ("index "+index);
}
keyword += recurseWord(keyword.substring(0, keyword.length-1));
}
return null ;
}
Upvotes: 1
Reputation: 3390
As to why you are running out of memory I can't say exactly but you could try this instead. As a note, I am not running out of memory running this (been running a few minutes).
NOTE: This will lock your machine (400+ trillion operations)
var inputArr = "abcdefghijklmnopqrstuvwxyz ".split("").concat("\'");
function run(str) {
console.log(str);
}
function recurse(index, recursed) {
if (recursed === undefined)
recursed = "";
if (recursed.length >= 10)
return;
for (var i = 0; i < index.length; i++) {
run(recursed + index[i]);
recurse(index, recursed + index[i]);
}
}
recurse(inputArr);
Upvotes: 0