<div id='passarr'>1572 4528 3564 8921 4521</div>
I need to create a new random integer (4 digits), unique regarding the above content.
js
var content = $('#passarr').text();
var passarr = content.split(' ');
var pass = Math.floor(Math.random() * 9000) + 1000;
var i = 0;
while (i == 0) {
if (jQuery.inArray(pass, passarr) > -1) {
var pass = Math.floor(Math.random() * 9000) + 1000;
i = 1;
}
}
seems it works, but not sure this is the right and shortest way.
any suggestion?
Your code is the way to go. However, you can eliminate a few smaller mistakes ( an unneccessary i and non working code in < 0.00001%) :
var content = $('#passarr').text();
var passarr = content.split(' ');
do {
var pass = Math.floor(Math.random() * 9000) + 1000;
} while (jQuery.inArray(pass, passarr) > -1);
console.log(pass);
Related
I'm putting together a quiz with A/B questions. Every answer has 5 parameters that have to be updated as the user advances through the quiz to show a final results page.
It's very simple but I can't figure out why the parameters aren't updating. This is my first Javascrips project, can somebody point me in the right direction? Thank you!
//The five parameters to be updated
let totalOrg = 2;
let totalDel = 2;
let totalMod = 0;
let totalLux = 2;
let totalSer = 2;
// Array with values to modify the parameters for A or B answers
var valueDataA = [
[1,2,5,1,3],
[6,5,1,2,8]
];
var valueDataB = [
[-6,-3,-7,-3,-2],
[-1,-7,-5,-2,-3]
];
//Function to add the values to the parameters
function chooseOptionA() {
totalOrg = totalOrg + valueDataA[currentQuestion][0];
totalDel = totalDel + valueDataA[currentQuestion][1];
totalMod = totalMod + valueDataA[currentQuestion][2];
totalLux = totalLux + valueDataA[currentQuestion][3];
totalSer = totalSer + valueDataA[currentQuestion][4];
console.log(totalParameters);
};
function chooseOptionB() {
totalOrg = totalOrg + valueDataB[currentQuestion][0];
totalDel = totalDel + valueDataB[currentQuestion][1];
totalMod = totalMod + valueDataB[currentQuestion][2];
totalLux = totalLux + valueDataB[currentQuestion][3];
totalSer = totalSer + valueDataB[currentQuestion][4];
console.log(totalParameters);
};
let totalParameters = [totalOrg, totalDel, totalMod, totalLux, totalSer];
When you place totalOrg in the array totalParameters, you are not placing a pointer to the first variable, but the value, i.e. 2. So the final line of code is no different from:
let totalParameters = [2, 2, 0, 2, 2];
This will clarify why that array is not getting any changes when the functions are called. There are several ways to do this. I will propose one, where the first "parameter" values are stored in a single object, whose property names correspond to your current variable names. You must then adapt the rest of your code to reference those properties:
let totalParameters = {
totalOrg: 2,
totalDel: 2,
totalMod: 0,
totalLux: 2,
totalSer: 2
};
var valueDataA = [
[1,2,5,1,3],
[6,5,1,2,8]
];
var valueDataB = [
[-6,-3,-7,-3,-2],
[-1,-7,-5,-2,-3]
];
function chooseOptionA() {
totalParameters.totalOrg += valueDataA[currentQuestion][0];
totalParameters.totalDel += valueDataA[currentQuestion][1];
totalParameters.totalMod += valueDataA[currentQuestion][2];
totalParameters.totalLux += valueDataA[currentQuestion][3];
totalParameters.totalSer += valueDataA[currentQuestion][4];
console.log(totalParameters);
};
function chooseOptionB() {
totalParameters.totalOrg += valueDataB[currentQuestion][0];
totalParameters.totalDel += valueDataB[currentQuestion][1];
totalParameters.totalMod += valueDataB[currentQuestion][2];
totalParameters.totalLux += valueDataB[currentQuestion][3];
totalParameters.totalSer += valueDataB[currentQuestion][4];
console.log(totalParameters);
};
Let me pitch you a different approach
//The five parameters to be updated
let totalOrg = 2;
let totalDel = 2;
let totalMod = 0;
let totalLux = 2;
let totalSer = 2;
// Array with values to modify the parameters for A or B answers
var valueDataA = [
[1,2,5,1,3],
[6,5,1,2,8]
];
var valueDataB = [
[-6,-3,-7,-3,-2],
[-1,-7,-5,-2,-3]
];
/**
* updateParameters
*
* Function to update the values of the parameters
*
* #param {Array<Number>} parameters
* #param {Array<Number>} parameterUpdates
* #returns {Array<Number>}
*/
function updateParameters(parameters, parameterUpdates) {
for (let i = 0; i < parameters.length; i++) {
parameters[i] += parameterUpdates[i];
}
return parameters;
}
let totalParameters = [totalOrg, totalDel, totalMod, totalLux, totalSer];
for (let currentQuestionIndex = 0; currentQuestionIndex < 2 /** questions.length */; currentQuestionIndex++) {
let option = 'A'; /** actually getUserChoice(); */
if (option == 'A') {
totalParameters = updateParameters(totalParameters, valueDataA[currentQuestionIndex])
} else if(option == 'B') {
totalParameters = updateParameters(totalParameters, valueDataB[currentQuestionIndex])
}
console.log(totalParameters);
// you can use destructuring assignment to get individual parameters written
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
[totalOrg, totalDel, totalMod, totalLux, totalSer] = totalParameters;
}
I want to randomize elements on pageload - and just show 4 of them regardless on how many there are.
The closest I come is this:
$(document).ready(function() {
$(".itembox.newcenterbox").hide();
var elements = $(".itembox.newcenterbox");
var elementCount = elements.size();
var elementsToShow = 4;
var alreadyChoosen = ",";
var i = 0;
while (i < elementsToShow) {
var rand = Math.floor(Math.random() * elementCount);
if (alreadyChoosen.indexOf("," + rand + ",") < 0) {
alreadyChoosen += rand + ",";
elements.eq(rand).show();
++i;
}
}
});
It works for me on my local site - but it chrashes my live site.and I can't figure out why.
Is there a better way to do this?
Maybe your elementCount is less than elementsToShow? In this case, you will always get rand value between 0 and 3, and it will lead to an infinite loop.
Try the code below. Also I removed unnecessary loop iterations when you check the rand index.
$(document).ready(function() {
var elements = $(".itembox.newcenterbox");
var elementsToShow = 4;
var i = 0;
if(elements.length < elementsToShow) return;
for (i = 0; i < elementsToShow; i++) {
elements.splice(Math.floor(Math.random() * elements.length), 1);
}
elements.hide();
});
I am trying to create an array of length 25, and generate a random number every 1 second and add it to this array.
However, I want that once the length of array is reached, the old values start being replaced with the newly random generated values. This is where I have arrived so far, I am not that familiar with javascript, so any improvements are welcome:
var arr = [];
arr.length = 25;
function generate() {
arr.push(Math.floor(Math.random() * 6) + 1);
}
setInterval(generate, 1000);
Can anyone tell me how I can enforce the length of the array to 25 and once this length is reached start replacing old values with new ones? I need that the new values are always added to the end of the array as these will be used to generate a graph.
Thanks
You should probably just remove the first element if the array is of length 25 using shiftMDN
function generate() {
if( arr.length == 25 ) arr.shift();
arr.push(Math.floor(Math.random() * 6) + 1);
}
You can check array length before you add elements in array. When array size of array reaches 25 you can set indexer variable to zero again.
var arr = [];
var i = 0;
function generate() {
if(arr.length < 25)
arr[i++] = Math.floor(Math.random() * 6) + 1;
else
i=0;
}
As #megawas suggested you can use remainder by dividing i by 25
var arr = [];
var i = 0;
function generate() {
arr[(i++)%25] = Math.floor(Math.random() * 6) + 1;
}
Here we go:
var arr = []
var arr_position = 0
var arr_length = 25
function generate() {
arr[arr_position] = Math.floor(Math.random() * 6) + 1
if(arr_position == arr_length-1){
arr_position = 0
} else {
arr_position++
}
}
setInterval(generate, 1000)
var arr = [];
var constant = 25;
function generate() {
arr.push(Math.floor(Math.random() * 6) + 1);
if(arr.length == constant){
arr.splice(0,1);
}
}
setInterval(generate, 1000);
I am using the below code to assign a random class (out of five) to each individual image on my page.
$(this).addClass('color-' + (Math.floor(Math.random() * 5) + 1));
It's working great but I want to make it so that there are never two of the same class in a row.
Even better would be if there were never two of the same in a row, and it also did not use any class more than once until all 5 had been used... As in, remove each used class from the array until all of them have been used, then start again, not allowing the last of the previous 5 and the first of the next 5 to be the same color.
Hope that makes sense, and thanks in advance for any help.
You need to create an array of the possible values and each time you retrieve a random index from the array to use one of the values, you remove it from the array.
Here's a general purpose random function that will not repeat until all values have been used. You can call this and then just add this index onto the end of your class name.
var uniqueRandoms = [];
var numRandoms = 5;
function makeUniqueRandom() {
// refill the array if needed
if (!uniqueRandoms.length) {
for (var i = 0; i < numRandoms; i++) {
uniqueRandoms.push(i);
}
}
var index = Math.floor(Math.random() * uniqueRandoms.length);
var val = uniqueRandoms[index];
// now remove that value from the array
uniqueRandoms.splice(index, 1);
return val;
}
Working demo: http://jsfiddle.net/jfriend00/H9bLH/
So, your code would just be this:
$(this).addClass('color-' + (makeUniqueRandom() + 1));
Here's an object oriented form that will allow more than one of these to be used in different places in your app:
// if only one argument is passed, it will assume that is the high
// limit and the low limit will be set to zero
// so you can use either r = new randomeGenerator(9);
// or r = new randomGenerator(0, 9);
function randomGenerator(low, high) {
if (arguments.length < 2) {
high = low;
low = 0;
}
this.low = low;
this.high = high;
this.reset();
}
randomGenerator.prototype = {
reset: function() {
this.remaining = [];
for (var i = this.low; i <= this.high; i++) {
this.remaining.push(i);
}
},
get: function() {
if (!this.remaining.length) {
this.reset();
}
var index = Math.floor(Math.random() * this.remaining.length);
var val = this.remaining[index];
this.remaining.splice(index, 1);
return val;
}
}
Sample Usage:
var r = new randomGenerator(1, 9);
var rand1 = r.get();
var rand2 = r.get();
Working demo: http://jsfiddle.net/jfriend00/q36Lk4hk/
You can do something like this using an array and the splice method:
var classes = ["color-1", "color-2", "color-3", "color-4", "color-5"];
for(i = 0;i < 5; i++){
var randomPosition = Math.floor(Math.random() * classes.length);
var selected = classes.splice(randomPosition,1);
console.log(selected);
alert(selected);
}
var used = [];
var range = [0, 5];
var generateColors = (function() {
var current;
for ( var i = range[0]; i < range[5]; i++ ) {
while ( used.indexOf(current = (Math.floor(Math.random() * 5) + 1)) != -1 ) ;
used.push(current);
$(" SELECTOR ").addClass('color-' + current);
}
});
Just to explain my comment to jfriend00's excellent answer, you can have a function that returns the members of a set in random order until all have been returned, then starts again, e.g.:
function RandomList(list) {
var original = list;
this.getOriginal = function() {
return original;
}
}
RandomList.prototype.getRandom = function() {
if (!(this.remainder && this.remainder.length)) {
this.remainder = this.getOriginal().slice();
}
return this.remainder.splice(Math.random() * this.remainder.length | 0,1);
}
var list = new RandomList([1,2,3]);
list.getRandom(); // returns a random member of list without repeating until all
// members have been returned.
If the list can be hard coded, you can keep the original in a closure, e.g.
var randomItem = (function() {
var original = [1,2,3];
var remainder;
return function() {
if (!(remainder && remainder.length)) {
remainder = original.slice();
}
return remainder.splice(Math.random() * remainder.length | 0, 1);
};
}());
I've got this project where I have to generate random mathematics sums...
They are all 'divide by' sums, so I want to make all numbers even.
Can anyone help me with this? just ask if I'm not clear enough =)
<script>
$(function() {
var number = document.getElementById("breuken"),
i = 1;
for (; i <= 10; i++) {
var sRandom = Math.floor(Math.random()*10 + 1),
fRandom = Math.floor(sRandom + Math.random()*(20-sRandom )),
calc = Math.abs(fRandom / sRandom),
textInput = document.createElement('input'),
span = document.createElement('span'),
p = document.createElement('p');
textInput._calc = calc;
textInput.onchange = (function(p) {
return function(ev) {
var self = ev.target;
if (self.value == self._calc) {
p.style.color = 'green';
};
};
})(p);
span.innerHTML = fRandom + " : " + sRandom + " = ";
p.appendChild(span);
p.appendChild(textInput);
number.appendChild(p);
};
});
</script>
To get an even random number just:
halve you range and multiply by 2
var range = 100;
var number = Math.floor( Math.random() * range / 2 ) * 2;
or keep getting random numbers until you get an even one
var number;
do {
number = Math.floor(Math.random()*10 + 1)
} while( number % 2 == 1 );
Get a random integer over 1/2 the range and double it.