jquery get the unreapeatable values - javascript

i have a array with numbers. i need that array value to be generated once i click on the button, while i click on the button i need to get the value random wise from the array, but the value should not be repeated.
ex, if i get a 2 from out of 5, then i should not get the 2 again. for this i wrote this function, but the values are repeating... any idea?
var ar = [0,1,2,3,4,5];
var ran = Math.floor(Math.random()*ar.length);
ar.splice(ran,1);
alert(ar.splice);
the array values should not be removed. because if i click the button again, i need to get the values like before.
i did my work like this : but the rand values are repeating, any one can correct this to get unrepeatable values to get?
$(document).ready(function(){
var myArray = [1,2,3,4,5];
var mySize = 5;
x = 0;
while(mySize>=1){
var rand = Math.floor(Math.random()*mySize);
mySize--;
alert(rand);
}
})

You need your array to be in an outer scope for this like:
(function(){
var ar = [0,1,2,3,4,5];
document.getElementById('thebutton').onclick = function(){
alert(ar.splice(Math.floor(Math.random()*ar.length), 1));
};
})();
JSFiddle Example
If you create your array inside the onclick function then you are just recreating the entire array every time the button is clicked.

Take a look at this demo. In this it randomizes the array values and will repeat only after all the values are utilized.
Demo
Based on the update in your question here it is take a look.
http://jsfiddle.net/MbkwK/2/

var ar = [0, 1, 2, 3, 4, 5];
document.getElementById('thebutton').onclick = function() {
var shuffle = [];
var copyarr = ar.slice(0);
var arlength = copyarr.length;
for (i = 0; i < arlength; i++) {
shuffle.push(copyarr.splice(Math.floor(Math.random() * copyarr.length), 1));
}
alert(shuffle.join(","));
};
Working demo - http://jsfiddle.net/ipr101/qLSud/1/

Related

JS - setAttribute (a function with 2 parameters) to a bidimensional array

I'm trying to make a mini-calculator for my form. My html-form is based on data-prototype, so it renders an unlimited amount of forms with 2 inputs : date and duration.
This inputs are rendered with ID-s like loan_charge_0_date , loan_charge_1_duration ; next one : loan_charge_1_date, loan_charge_1_duration` and so on.
I already wrote a code that with regex creates an array with all ids of date, and an another array with all ids of durations. So, when I click on + button that adds a new form, my dateIdsArray = [loan_charge_0_date] and durationIdArray = [loan_charge_0_duration]. When I click it again, it pushed one more element to each array, the loan_charge_1_date in dateIdsArray and loan_charge_1_duration to durationIdsArray`.
Now, I need to each pair (form) to bind a function with 2 parameters like date.value and duration.value ... and in this function to make my endingDateCalculator.
In this order, I made some easy statements that first...concat this 2 arrays, and after that make them as a pair ... so, result array is a bidimensional array :
pairValuesArray = [
[loan_charge_0_date, loan_charge_0_duration],
[loan_charge_1_date, loan_charge_1_duration],
[loan_charge_2_date, loan_charge_2_duration]
];
How can I append an function to every this pair, so when I onkeyup the duration of input, it will call the endingDateCalculator function with 2 parameters (this.date, this.duration) and perform calculations?
I tried smth like :
pairArray.forEach( x => document.getElementById(x).setAttribute('onkeyup', 'endingDateCalculator(this.value, this.value);'));
but it show me ... can not run setAttribute to a null :/
My entire script is here :
<script>
var bodyText = document.getElementsByClassName('panel-group')[0].innerHTML;
var durationIds = bodyText.match(/id="(.*duration)"/g);
var durationIdArray = durationIds.map(y => y = y.split('\"')[1]);
var dateIds = bodyText.match(/id="(.*date)"/g);
var dateIdArray = dateIds.map(x => x = x.split('\"')[1]);
var concatArray = new Array();
for (var i = 0; i < durationIds.length; i++) {
concatArray.push(dateIdArray[i]);
concatArray.push(durationIdArray[i]);
}
var pairArray = new Array ();
var i,j,temparray,chunk = 2;
for (i=0,j=concatArray.length; i<j; i+=chunk) {
temparray = concatArray.slice(i,i+chunk);
pairArray.push(temparray);
}
console.debug(pairArray);
pairArray.forEach( x => document.getElementById(x).setAttribute('onkeyup', 'endingDateCalculator(this.value, this.value);'));
//dateIdArray.forEach( x => document.getElementById(x).setAttribute('onkeyup', 'endingDateCalculator(this.value);'));
function endingDateCalculator(valueOfDate, valueOfDuration) {
alert(valueOfDate + valueOfDuration);
}
</script>

How do I move an object from one array to another?

I'm trying to move an object from one array(triviaDataArray) to another(answeredQuestions). I've replaced the actual questions with numbers to shorten code. When I run this code it seems to remove a position in the triviaDataArray, and adds one to the answeredQuestion array. But it doesn't seem to remove the correct one. When a new question is loaded it sometimes repeats itself, which is not what I want. I want it to ask a question, and then when it is answered move it to the answeredQuestion array.
I can only use JavaScript. Can someone please help me. I've been struggling with this for quite some time.
This portion is from a data reader file I have to load a random question and it's answers from an array and the second is to open the array.
TriviaDataRecords.prototype.loadRandomRecord = function () {
this.position = Math.floor(Math.random() * this.records.length);
};
function openTriviaRecords(triviaData) {
return new TriviaDataRecords(triviaData);
}
global arrays and variables
var triviaDataArray = [1, 2, 3, 4, 5, 6, 7]
var answeredQuestions = []
var triviaRecords = openTriviaRecords(triviaDataArray);
function that loads a question and files the fields of the html.
function loadQuestion(){
var randomRecord = triviaRecords.loadRandomRecord();
var buttonA = document.getElementById("answer1");
var buttonB = document.getElementById("answer2");
var buttonC = document.getElementById("answer3");
var buttonD = document.getElementById("answer4");
var buttonE = document.getElementById("answer5");
document.getElementById('question').innerHTML = triviaRecords.getQuestion();
document.getElementById('answer1').innerHTML = triviaRecords.getAnswerA();
document.getElementById('answer2').innerHTML = triviaRecords.getAnswerB();
document.getElementById('answer3').innerHTML = triviaRecords.getAnswerC();
document.getElementById('answer4').innerHTML = triviaRecords.getAnswerD();
document.getElementById('answer5').innerHTML = triviaRecords.getAnswerE();
portion where I'm trying to move the question from one array to another.
var index = triviaDataArray.indexOf(randomRecord);
if (index == -1) {
triviaDataArray.splice(randomRecord, 1);
answeredQuestions.push(randomRecord);
}

Run through for loop and randomly change values of variable within a range but satisfy all variables

So what I have is a quiz which is generated dynamically. I want the quiz questions to be ordered randomly. Basically, the i is going from 0 to the length of answerArray. I want it to do this, but not in order randomly. For instance: instead of 0,1,2,3,4,5 I want 1,0,2,3,5,4. I have tried doing this but all of my attempts failed. It would be very helpful if I could do this so the test questions would not always be in order. Thank you.
var displayAnswers = function (){
for (var i = 0; i<answerArray.length;i++){
var row1= document.createElement("div");
$(row1).addClass("row");
var colmd= document.createElement("div");
$(colmd).addClass("row");
$(colmd).addClass("text-center");
$(colmd).addClass("rowtxt");
$(colmd).attr('id',"questionTxt"+[i+1]);
$("#contain").append(row1)
$(row1).append(colmd);
var answer = answerArray[i];
}
You can use accepted answer in the following question Generate unique random numbers between 1 and 100, that will generate the random numbers first and store them in array and use them inside for loop.
Example :
var arr = [];
var answerArray = ["Answer 1", "Answer 2", "Answer 3"];
while( arr.length < answerArray.length ){
var randomnumber=Math.ceil( Math.random() * answerArray.length)
var found=false;
for(var i=0;i<arr.length;i++){
if(arr[i]==randomnumber){found=true;break}
}
if(!found)arr[arr.length]=randomnumber;
}
Now you have an array of unique numbers between 0 and answerArray length, you can use it inside the loop just by calling arr[i] :
var displayAnswers = function (){
for (var i = 0; i<answerArray.length;i++){
var row1= document.createElement("div");
$(row1).addClass("row");
var colmd= document.createElement("div");
$(colmd).addClass("row");
$(colmd).addClass("text-center");
$(colmd).addClass("rowtxt");
$(colmd).attr('id',"questionTxt"+[i+1]);
$("#contain").append(row1)
$(row1).append(colmd);
//Here you get the unique number between 0 and answers length
var random_number = arr[i];
var answer = answerArray[random_number];
}
}
Hope this helps.
I would start by thinking about what you need to do.
You want to track what numbers you have used already and getting a new number if you have already used the one generated.
Try something like this.
// The initial array
var Array = [1,2,3,4,5];
// The new array or tracking array
var Used = [];
// A function to generate the random index
// We need a function so we can call it if
// the index already exists to ensure we have
// the same amount of values as the inital
// array
function addRandomNum(array) {
var random = Math.floor((Math.random() * Array.length) + 1);
if(array.indexOf(random) === -1){
array.push(random);
} else {
addRandomNum(array);
}
};
// Loop the inital array calling the function
for(var i = 0; i < Array.length; i++){
addRandomNum(Used);
}
// Look at the new randomized array
console.log(Used);
You could shuffle the array, if that is what you want.
There are shuffle functions if you follow this link of css-tricks:
https://css-tricks.com/snippets/javascript/shuffle-array/
I like technique 2. Which uses the sort function to randomly create a negative or positive number which will sort the items according to the returned value.
If the returned value is positive, the first item will precede the second that is passed to the function. As you can see, the parameters are unused because we don't want a logic sort but a randomized based on a random number.
You could call it like this:
answerArray.sort(function(item1, item2) { return 0.5 - Math.random() });
Ok, I will assume a few things. Your answerArray looks like this:
var answerArray = [
{
"q_id": "1",
"prompt": "Is StackOverflow awesome?",
"a1": "Yes",
"a2": "No",
"correct": "a1"
}
];
First add a property like this
"random": Math.floor(Math.random() * 101)
This will create a random number that you can use to sort the array, like so:
answerArray.sort(function(a, b) {
return parseFloat(a.random) - parseFloat(b.random);
});
This way you can sort the questions randomly.

How to randomly select numbers within an arbitrary range and add together using JavaScript arrays

I am trying to write some JavaScript that will select some random numbers from an array and then add those selected numbers to make a single total value.
For example if i had var array = [1, 22, 5, 88, 3, 105, 7, 88, 987] i would then like the code to select however many numbers it wants at random(amount selected changes every time it runs) and then add them together but i am not sure if this is even possible.
I am new to JavaScript so i have only managed to write code that adds all the array elements together instead of selecting at random.
var arr = [1,2,3,4,5,6];
var total=0;
for(var i in arr) { total += arr[i]; }
My code is very basic so please excuse me for this i'm still learning. Thank You
You could use the Math.rand() function in order to create a random index. In terms of code:
// The array with your elements
var arr = [1,2,3,4,5,6];
// An array that will keep track of the elements we have selected.
var selectedIndex = [];
// The sum.
var sum=0;
// times is the number of elements we want to select from arr and sum them.
for(var i=0; i<times; i++)
{
// Get a random integer number in the range [0, arr.length]
var index = Math.floor(Math.rand()*arr.length);
// check if the index we created has been selected again.
if(selectedIndex.indexOf(index)>-1)
{
// The created index has been selected again. So we must select another one,
// in order we get an item from the array only once.
while(selectedIndex.indexOf(index)>-1)
index = Math.floor(Math.rand()*arr.length);
}
// We push the created index in the selected index array.
selectedIndex.push(index);
// We increase the sum.
sum+=arr[index];
}
update
In order the above to be executed the caller should provide a value for the variable called times. This value in order to be valid shouldn't exceed the length of the array called arr.
Another way more elegant, it would be to follow on this part the solution that deitch suggested in his post.
var times = Math.floor((Math.random() * arr.length)+1)
The above should be placed just before the for statement.
I think you are looking something like:
<code>
function randormTotal() {
var arr = [1,2,3,4,5,6];
var total=0;
var noOfData = 3;
for(var i =0; i<noOfData; i++) {
var pos = Math.floor(Math.random()*(arr.length-1)) + 1;
total += arr[pos];
}
alert(total);
}
</code>
FYI, this method actually modifies the array, so you might want to copy it.
// randomly select how many elements you will pick
var i, total = 0, elmsCount = Math.floor((Math.random() * arr.length)+1), current;
// select that many elements
for (i=0; i<elmsCount; i++) {
current = Math.floor(Math.random()*arr.length);
total += arr.splice(current,1)[0];
}
// total is now the sum

How to add dynamically growing array into another dynamic array

In my project i have arrays for date1, date2 and so on upto one month dates as shown below
var day1= [4,5,6,11];
var day2= [7,8,9,12];
var day3= [10,11,12,14];...
var day30= [1,2, 3, 4];
In the above each array exact size we dont know that may increase or decrease and i need to pass these values to the one more set of arrays like
var data1= [day1[0], day2[0], day3[0]];
var data2= [day1[1], day2[1], day3[1]];
var data3= [day1[2], day2[2], day3[2]];...
var data30= [day1[30], day2[30], day3[30]];
As per the day array size data array size will increase.
How to solve this issue any help..?
Consider using an object instead of variables:
var days = {
day1: [4,5,6,11],
day2: [7,8,9,12],
...
day30: [1,2, 3, 4]
};
Then you can do something like:
var data30 = [];
var i = 0;
while ( days.hasOwnProperty('day' + ++i) ){
data30.push(days['day' + i]);
}
Though given the sample data, data30 won't have any members because the first array has no member at index 30.
Check out JavaScript's push method.
http://www.w3schools.com/jsref/jsref_push.asp

Categories

Resources