My script is causing the browser to freeze and asking me to stop the script. Using firebug I can see the for loop is endlessly looping and not making any progress. Here's the loop:
for (var x = 1; x < 7; x++) {
var y = x; //to stop the value of x being altered in the concat further down
var questionidd = "mcq_question_id";
console.log("1 = " + questionidd);
var questionid = questionidd.concat(y); // mcq_question_id$ctr the question number
console.log("2 = " + questionid);
var mcqid = form[questionid].value; // the questions id on db
console.log("3 = " + mcqid);
var answerr = "mcq_question";
var answer = answerr.concat(y); // mcq_question$ctr the questions chosen answer
var chosenanswer = form[answer].value; // the answers value
console.log("4 = " + chosenanswer);
var amp = "&";
var equal = "=";
var questionide = questionid.concat(equal); // "mcq_question_id$ctr="
var questionida = amp.concat(questionide); // "&mcq_question_id$ctr="
var answere = amp.concat(answer, equal); // "&mcq_question$ctr="
if (x = 1) {
send.push(questionide, mcqid, answere, chosenanswer);
}
else {
send.push(questionida, mcqid, answere, chosenanswer);
}
}
Update - Fixed! Silly mistakes are the worst
if (x = 1) {
should be
if (x === 1) {
The === operator compares while the assignment operator = assigns. Many people make this mistake. :)
When the first loop runs, it sets x to zero, and does so infinitely until the process is terminated. That's why the loop doesn't stop.
if (x = 1) { should be if (x === 1) {
Consider switching to an IDE that catches simple programming errors like this.
Looks like you should have "if (x == 1)" instead of "if (x = 1)".
Your code repeatedly sets x to the value 1, rather than checking that it is equivalent to 1.
Related
So I'm using JavaScript to make something to solve simple algebraic expressions. I've got everything for the math part done but I need to run a line of code again. So I've used a conditional branch to determine if the first side of the equation is equal to the second side. If it's equal then the value of the variable is given but if it isn't the same, then the variable is increased by one.
function Command() {
var FirstSide = document.getElementById("FirstLine").value;
var SecondSide = document.getElementById("SecondLine").value;
var evalLineOne = FirstSide;
var evalLineTwo = SecondSide;
var X = 1;
var MathLineOne = eval(evalLineOne);
var MathLineTwo = eval(evalLineTwo);
if (MathLineOne == MathLineTwo)
document.getElementById("Reply").innerHTML = X;
else {
X + 1;
}
So this is the code I've used. When using an algebraic expression where the value of X is not 1 the code simply doesn't work. I was assuming this was because I would need to rerun the code from the line of code which defines the value of "X". How would I go back to run this code?
Without making a lot of changes to your code, you could call the same function recursively like so:
var max = 9999999; //set this to whatever you want
function Command(X) {
if (typeof X === 'undefined') X = 1;
if (X > max) return;
var FirstSide = document.getElementById("FirstLine").value;
var SecondSide = document.getElementById("SecondLine").value;
var evalLineOne = FirstSide;
var evalLineTwo = SecondSide;
var MathLineOne = eval(evalLineOne);
var MathLineTwo = eval(evalLineTwo);
if (MathLineOne == MathLineTwo)
document.getElementById("Reply").innerHTML = X;
else {
Command(X+1);
}
}
I need to create a program that asks the user for a value to store in an array and continues to keep asking for values to add till they have no more numbers they want to enter into the array. Afterwards I must output the array containing no zeros (Which they're allowed to enter zeros so I have to filter them out from the output) and return the sum of the array. My current issue with my program is that arr.push(x) is currently trying to push an undefined value in the function arrin. I feel as if there's a much better way of going about this than I'm currently trying so I'm all ears for improvement.
var x = parseInt(prompt("Enter a number, to exit enter NaN", "0"), 10);
var y = arrin(x);
var arr = [];
var s;
function arrin(x) {
if(x != NaN){
arr.push(x)
x = parseInt(prompt("Enter a number, to exit enter NaN", "0"), 10);
y = arrin(x);
}else{
document.write("<p>"+arr.toString()+"</p>");
s = sum(arr);
doucment.write("<p> The sum of all elements in the array is "+s+"</p>");
}
}
x != NaN will not work.
!isNaN(x) will check if the var is a number.
x != "NaN" will check if the text is literally "NaN"
either of the last two will work.
var arr = [];
var y = arrin(0);
var s;
function arrin(x) {
if (!isNaN(x)) {
if (x != 0) arr.push(x)
x = parseInt(prompt("Enter a number, to exit enter NaN", "0"), 10);
y = arrin(x);
} else {
document.write("<p>" + arr.toString() + "</p>");
s = sum();
document.write("<p> The sum of all elements in the array is " + s + "</p>");
}
}
function sum() {
var t = 0;
for (var i = arr.length; i--;) t += parseInt(arr[i]);
return t;
}
I have a while loop that's working fine. Inside it is an array push. yes this part works perfectly until the while loops completes. All of this is inside another while loop what has an increment change. the increment affects the array in hopes to re-write it completely. what ends up happening is that it stays stuck on the first version of the array, and everything else in later coding can't call on the second version of the array.
var arrayname = [];
var increment = 0;
var var1 = 0;
var x = 0;
var y = 0;
var z = 0;
outerloop == 0;
while(outerloop == 0){
endloop = 0;
while (endloop == 0) {
arrayname.length = 0;
randomFunctionThatCreatesThe123variables();//in here 'increment' changes output.
x = (1 + 2 + 3); //above function's summed result
y = 25; //static base number
alert(increment);
z = (increment + y);
if (x == z)
arrayname[array.length] = [1,2,3];
if (x == 500)
endloop = 1;
}
testloop = 0;
while (testloop == 0){
otherRandomFunctionsThatTestArray();//this loops the same functions on each subarray
if (var1 == arrayname.length) {
testloop = 1;
var1 = 0;
tar = ++increment;
}
}
if((increment + y) == 700)
outerloop = 1;
}
my goal is that the testloop functions test the array, then when endloop recreates the array on the next cycle, it will use the newly incremented affected array. but all that happens is:
if array not cleared:it keeps cycling the tests throught the same array.
if cleared with arrayname.length = 0; the tests use the new increment to find the new array and but finds it undefined.
the alert proves the increment is being properly read.
I'm building a game currently but I have a small problem with keeping the score. Basically I have an textfield that gets a random word input, then if someone clicks on the field or symbol containing the field then I want to check the random word input, if it's a correct word I want to update score textfield, if it's incorrect I want to update errors textfield.
For this I am using an if/else construction, the problem I have with it is that in my game every click only goes either in the if statement or if I change code then only the else, but it's not checking symbol for symbol, every time I click to see if it's an correct word or not. Here is the code I am using on the symbol.click symbol. My question is, am I doing anything wrong in the if/else statements or are my variable calling methods wrong. I have source files on request.
symbol.click:
var y = sym.getVariable("lijst");
var x = "bommen";
// if variables are a match then update score with 1
if (sym.getVariable("x") == sym.getVariable("y"))
{var score3 = sym.getComposition().getStage().getVariable("score1");
score3= score3 +=1;
sym.getComposition().getStage().$ ("scoreTxt").html(score3);
sym.getComposition().getStage().setVariable("score1", score3);
}
// else update error textfield with 1
else {
var fouten= sym.getComposition().getStage().getVariable("fouten1");
fouten= fouten +=1;
sym.getComposition().getStage().$ ("hpTxt").html(fouten);
sym.getComposition().getStage().setVariable("fouten1", fouten);
}
symbol.creationComplete
var words = ['bommen',
'dammen',
'kanonnen',
'dollen',
'bomen',
'feesten',
'lampen',
'voeten',
];
var lijst = words[Math.floor(Math.random() * words.length)];
sym.$("dynamicText").html(lijst);
//And my stage:
stage.creationComplete
// some different variables declarations
sym.setVariable("score1", 0);
sym.setVariable("fouten1", 0)
//var game = sym.getComposition().getStage();
var cirkels = [];
var test1 = "bommen";
var score2 = sym.getComposition().getStage().getVariable("score1");
var fouten = sym.getComposition().getStage().getVariable("fouten1");
var cirkelStart = {x:180,y:190};
var cirkelSpacing = {x:170,y:170};
function init(){
initPlayer();
spawnCirkels();
}
//this is for score and error updating
function initPlayer(){
sym.$("scoreTxt").html(score2);
sym.$("hpTxt").html(fouten);
}
// create symbols on a grid
function spawnCirkels(){
var cirkel;
var el;
var i;
var xPos = cirkelStart.x;
var yPos = cirkelStart.y;
var col = 0;
for(i = 0;i < 15;i++){
cirkel = sym.createChildSymbol("Cirkel", "Stage");
cirkel.play(Math.random() * 1000);
cirkels.push(cirkel);
el = cirkel.getSymbolElement();
el.css({"position":"absolute", "top":yPos + "px", "left":xPos + "px"});
xPos += cirkelSpacing.x;
col++;
if(col === 5){
col = 0;
yPos += cirkelSpacing.y;
xPos = cirkelStart.x;
}
}
}
init();
If anyone sees what I am doing wrong let me know!
Thanks for your help anyway!
I want to create an array of random/pseudo-random numbers using a seed. I want the very same array to be created when the same seed is used and I want to have little or no visible pattern in the array. I'm working in JavaScript.
This is the random function I'm using, which I'm quite happy with (sorry, I forgot who the original author is):
function random(seed) {
if (!seed) seed = new Date().getTime();
seed = (seed*9301+49297) % 233280;
return seed/(233280.0);
}
This is the array generation:
var superSeed = random();
var nRandom = 100;
var randomArray = new Array();
for (var i = 0 ; i < nRandom ; i++){
randomArray.push(random((superSeed*10)+ (i)));
}
Somehow the pattern seems to be quite similar, no matter how often I run it. This question seems to be similar, but since it's about matrixes, I don't understand what's being said.
Thanks!
Having worked on similar things before I think we can use a fairly simple series, which takes two initial values and then you can get a lot more.
var a1,b1;
function InitSequence(v1, v2) {
a1 = Math.pow(v1, 5) / Math.pow(v1, 3);
b1 = Math.pow(v2, 8);
lastrand = (a1 + b1) & 0x7fffffff;
}
function SequenceNext() {
var alast = a1;
var nextVal = (a1 + b1) & 0x7fffffff;
b1 = alast;
a1 = nextVal;
return nextVal;
}
Then use it like this:
InitSequence(75, 21);
for (var i = 0; i < 99; i++) {
v = SequenceNext();
}
I tested it like this:
var used = new Array();
InitSequence(75, 21); // any two values will do.
// fill 10k into array.
for (var i = 0; i < 9999; i++) {
v = SequenceNext();
if (undefined != used[v]) {
used[v]++;
} else used[v] = 1;
//document.write(i+": "+v+"<br>");
}
// see if there any duplicates.
var tdup = 0;
for (xx in used) {
ndup = used[xx];
if (ndup > 1) {
document.write("duplicated " + xx + " :" + ndup + "<br>");
tdup += ndup;
}
}
document.write("Total dups " + tdup + "<br>");
This is using the Fibonacci series, which in mathematical terms, the sequence Fn of Fibonacci numbers is defined by the recurrence relation
. I'm starting with different values - (v1^5) / (v1^3) and v2 ^ 8; otherwise it would only ever be identical.
I like the "Super 7" PRNG. It is simple, fast (although the other answer with the fib. sequence is fast as well), and has the interesting property:
In the entire range -- albeit of a meager of 32k -- there are no duplicates using the "Super 7" PRNG.
Multiple 7's can be joined to increase the number of bits and/or provide multiple seeds. This non-duplication property can exposed or folded.
(The sequence of a PRNG is always the same given a starting seed: it's the distribution and cycle lengths that are interesting -- it is these properties that may make them ideal in different cases where "true randomness" isn't desired).
Happy coding.
Maybe you should try this
function s_random() {
s_random.m = 71402523; s_random.a = 409647; s_random.c = 1508892;
s_random.seed = (s_random.seed*s_random.a + s_random.c) % s_random.m;
return s_random.seed / s_random.m;
}
/*
generate IV
s_random.seed = Math.floor((new Date).getTime()/10000);
*/
s_random.seed = 130324232;
var CheckRandom = 4999999;
var PrintSamples = 100;
var used = new Array();
for (var i = 0; i < CheckRandom; i++) {
v = (Math.ceil(Math.sqrt(s_random())* 1000000000) * 8);
if (undefined != used[v]) {
used[v]++;
} else used[v] = 1;
if ( i< PrintSamples) document.write(i+": "+v+"");
}
/* see if there are any duplicates. */
var tdup = 0;
for (xx in used) {
ndup = used[xx];
if (ndup > 1) {
if (ndup < PrintSamples) document.write("duplicated " + xx + " :" + ndup + "");
tdup += ndup;
}
}
document.write("Total generated " + CheckRandom + "");
document.write("Total duplicates " + tdup + "");
Just got 5 million seeded, repeatable random numbers and no duplicates. Tested several times on Mac OS X with Safari.
Cheers,
Karl