This question already has answers here:
Recursively print all permutations of a string (Javascript)
(11 answers)
Closed 6 years ago.
I need to write a JavaScript function that shows me all the permutations of the digits of the number passed as an argument, but not sure how to do it.
For example, given 1020, it would produce
1020 , 0120 , 0210 , 0102.
Here's a working solution. Hope it helps!
var result = [];
var newArray = [];
function permute(someArray) {
var i, ch;
for (i = 0; i < someArray.length; i++) {
ch = someArray.splice(i, 1)[0];
newArray.push(ch);
if (someArray.length == 0) {
result.push(newArray.slice());
}
permute(someArray);
someArray.splice(i, 0, ch);
newArray.pop();
}
return result;
};
var n = 1901;
var arr = (""+n).split("");
var myResult = permute(arr);
for(var i in myResult){
console.log(myResult[i].join(""));
}
Related
This question already has answers here:
"Variable" variables in JavaScript
(9 answers)
Closed 5 years ago.
I want to optimize my javascript code with a FOR by i can't do this and i don't know why.
My code :
let pokemon1 = 'premier';
let pokemon2 = 'second';
let pokemon3 = 'troisieme';
for (var i = 1; i < 4; i++) {
console.log(pokemon[i]);
}
Do you know why it doesn't work ?
Thank you very much and sorry if i am a noob.
You should place the pokemon in an array:
let pokemon = [];
pokemon[0] = "premier";
pokemon[1] = "second";
pokemon[2] = "troisieme";
for(var i = 0; i < pokemon.length; i++){
console.log(pokemon[i])
};
Followed by some reading time: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration
Since you are using a list, you should use [] to define an array :
let pokemons = ['premier', 'second', 'troisième'];
for (let i = 0; i < pokemons.length; i++) {
console.log(pokemons[i]);
}
See https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Array for more information.
Also you should note that the first element of a list is 0.
So basically pokemons[0] === 'premier and pokemons[2] === 'troisième'
This question already has answers here:
How to randomize (shuffle) a JavaScript array?
(69 answers)
Closed 5 years ago.
I have an array that is rendering 25 images/pins every time a button is clicked, and it is only rendering the first 25 in the array. I want it to render 25 pins at a time but would like them to be random every time the button is clicked.
It was suggested I use part of an answer previously set in here, but I cannot figure out how to apply it or make sense of what I have.
This is what I was told to use:
randomIndex = Math.floor(Math.random() * currentIndex);
And replace current index with the array I want plus .length.
var pinIdArray = ["448460075380400214", "554857616577037440", "129619295506364205"];
var boardIdArray = [];
var showPins = [];
function(){
res.render("suggested", {pins: showPins});
You could use the Durstenfeld shuffle to shuffle the array and then take the first 25 elements in the array.
function shuffleArray(array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}
var array = [];
for(var i = 0; i < 500; i ++) {
array[i] = i;
}
console.log(shuffleArray(array).slice(0, 25));
Here is a function implemented in Javascript without any libraries. This also avoids shuffling the array so should be faster.
let pinIdArray = ["448460075380400214", "554857616577037440", "129619295506364205", "3403722138", "8005795986", "7717201977", "6689430878", "7705363504", "3827905985", "9133621064", "9162201846", "2655432017", "0197893312", "7220269979", "3218703261", "3478813716", "7445481990", "9806757977", "9357022147", "3492330721", "3504169963", "9259212333", "6574699545", "9727263383", "0016479256", "1624997250", "2083975447", "5683391989", "3466001901", "4660933902", "5216511997", "8820216343", "8583764035", "4563326839", "5201961267", "3429608185", "5007846054", "7437408815", "3472117054", "1545827364", "3152159572", "7913372317", "2550237417"];
function getRandomSubset(array, setSize) {
let maxValue = array.length, tmpSet = new Set(), randomIndices;
if (maxValue <= setSize) {
randomIndices = [...Array(setSize).keys()];
} else {
while (tmpSet.size < setSize) {
tmpSet.add(Math.floor(Math.random() * maxValue));
}
randomIndices = Array.from(tmpSet)
}
return randomIndices.map(index => array[index]);
}
//function(){
// res.render("suggested", {pins: getRandomSubset(pinIdArray, 25)});
// Test
console.log("25 Random Elements:", getRandomSubset(pinIdArray, 25));
You can randomize/shuffle the values in an array by using Lodash's _.shuffle function. The Lodash _.shuffle function uses a version of the Fisher-Yates shuffle.
var array = [1, 2, 3, 4];
var result = _.shuffle(array)
console.log(result);
<script src="https://cdn.jsdelivr.net/lodash/4.17.4/lodash.min.js"></script>
This question already has answers here:
Count number of matches of a regex in Javascript
(8 answers)
Get number of occurrences of a character in JavaScript [duplicate]
(7 answers)
Closed 8 years ago.
I have a string
file123,file456,file789
I want to count the number of time "," is in this string
for example for this string the answer should be 2
Simple regex will give you the length:
var str = "file123,file456,file789";
var count = str.match(/,/g).length;
There are lots of ways you can do this, but here's a few examples :)
1.
"123,123,123".split(",").length-1
2.
("123,123,123".match(/,/g)||[]).length
You can use RegExp.exec() to keep memory down if you're dealing with a big string:
var re = /,/g,
str = 'file123,file456,file789',
count = 0;
while (re.exec(str)) {
++count;
}
console.log(count);
Demo - benchmark comparison
The performance lies about 20% below a solution that uses String.match() but it helps if you're concerned about memory.
Update
Less sexy, but faster still:
var count = 0,
pos = -1;
while ((pos = str.indexOf(',', pos + 1)) != -1) {
++count;
}
Demo
It is probably quicker to split the string based on the item you want and then getting the length of the resulting array.
var haystack = 'file123,file456,file789';
var needle = ',';
var count = haystack.split(needle).length - 1;
Since split has to create another array, I would recommend writing a helper function like this
function count(originalString, character) {
var result = 0, i;
for (i = 0; i < originalString.length; i += 1) {
if (character == originalString.charAt(i)) {
result +=1;
}
}
return result;
}
var count = "file123,file456,file789".split(",").length - 1;
This question already has answers here:
Replace method doesn't work
(4 answers)
Closed 7 years ago.
I want to know why this procedure doesn't replace words
I have to do a procedure which reads a string and replace all word like this {{employee.Name}} into a value on the ticket's scope
var mySplitResult = Val.split(' ');
for (var i = 0; i < mySplitResult.length; i++) {
if (mySplitResult[i].match("{{") && mySplitResult[i].match(".")) {
var start = mySplitResult[i].lastIndexOf(".") + 1;
var end = mySplitResult[i].indexOf("}}");
var result = mySplitResult[i].substring(start, end);
for (var key in ticket.PNData) {
if (key == result) {
change.replace(mySplitResult[i], ticket.PNData[key]);
alert(change)
}
}
}
}
In JavaScript strings are immutable which means you must assign the result to a variable.
mySplitResult[i] = mychange.replace(mySplitResult[i], ticket.PNData[key]);
This question already has answers here:
How to randomize (shuffle) a JavaScript array?
(69 answers)
Closed 9 years ago.
I am trying to make a script which is outputting every number from 1-10.
Using a random number generator, in JavaScript.
I want every number to be unique.
Here is an example of what i would like the script to output:
5 9 7 6 1 3 4 8 2 10
This is my attempt:
var test = [];
var amountOfNumbers = 10;
var inArray = false;
var useNumbers = [];
for(var i=0; useNumbers.length<=amountOfNumbers; i++){
var rng = Math.floor((Math.random()*amountOfNumbers)+1);
for(var a=0; a<=test.length; a++){
if(rng == test[a]){
inArray == true;
}
}
if(!inArray){
document.write(rng);
test.push(rng);
useNumbers.push(rng);
}
}
Hope you can help.
for the record I am not interested in jQuery og any other library :)
1) How to fix your code
You have a few errors, among them the fact you don't reset inArray to false and that you don't iterate over the whole test array (use <, not <=). But using a loop to see if you already have the number isn't efficient, it's better to use an object as a map :
var test = [];
var amountOfNumbers = 10;
var useNumbers = {};
for(var i=0; test.length<amountOfNumbers; i++){
var rng = Math.floor((Math.random()*amountOfNumbers)+1);
if(!useNumbers[rng]){
document.write(rng);
test.push(rng);
useNumbers[rng] = true;
}
}
2) How to do it properly
Your algorithm will loop until it is lucky enough to find the remaining numbers. This isn't efficient and isn't predictable. The normal reliable practice is
to generate the array [1..10]
to shuffle it
Generating an array of the integers from 1 to N can be done with a simple loop or in a fancier way :
var arr = Array.apply(0,new Array(N)).map(function(_,i){ return i+1 });
Shuffling an array is usually done with the Fisher-Yates algorithm, for which you'll easily find JS implementations (it's easy to write anyway). A fast (theoretically not guaranteed to work with all future sort implementations) alternative is this one :
arr = arr.sort(function(a,b){ return Math.random()>0.5 });
The whole program
Your approach means to check over all the array in each step, looking if your random number is already inside the array, which means a lot lost time.
Best approach is disordering an ordered array. In each loop, we generate a random number (in the example, a number between 0 and 1) and with a 50% probability we change the item in the current position for other item in a random position (between 0 and the length of the array).
Hope it helps.
function disorder(arg) {
for (var i = 0; i < arg.length; i++) {
if (Math.random() < 0.5) {
var aux = arg[i];
var rndPos = Math.floor(Math.random()) * arg.length;
arg[i] = arg[rndPos];
arg[rndPos] = aux;
}
}
return arg;
}
var myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var myNewArray = disorder(myArray);
myNewArray.forEach(function(item) {
console.log(item);
});