Simple Quiz Game JavaScript - javascript

I'm just learning now. Can you please help me, why am I not getting the correct output. This is my code:
//ask questions
var quiz = [
["When is Bulgaria established?", 681],
["What year was it before 16 years?", 2000],
["When does WWII ends?", 1945]
];
//variables
var answer = [];
var correct = [];
var wrong = [];
var correctAns = 0;
var wrongAns = 0;
var oList = "<ol>";
//function to print the result in ordered list
function printResult(result){
for(var j = 0; j < result.length; j++){
oList += "<li>" + result[i] + "</li>";
}
oList += "</ol>";
return oList;
}
function print(message) {
document.getElementById('output').innerHTML = message;
}
//looping, adding correct and wrong answeres
for(var i = 0; i < 3; i++) {
answer[i] = prompt(quiz[i][0]);
if(parseInt(answer[i]) == quiz[i][1]){
correct.push(quiz[i][0]);
correctAns++;
} else {
wrong.push(quiz[i][0]);
wrongAns++;
}
}
//print logic
if(correct.length < 1 || correct == undefined){
print("You did not guess any of the quiestions!");
} else if (correct.length >= 1){
print("You have guessed " + correctAns + " questions.");
print(printResult(correct));
print("You have " + wrongAns + " wrong answeres.");
if(wrongAns > 0){
print(printResult(wrong));
}
}
I have watched this code over and over again and I still can't understand why am I getting undefined as a result. In the debugger, after the loop I check my vars and everything seems ok.

In your printResult function you are using var i instead of j,
Also you better use innerHtml+=message;
//ask questions
var quiz = [
["When is Bulgaria established?", 681],
["What year was it before 16 years?", 2000],
["When does WWII ends?", 1945]
];
//variables
var answer = [];
var correct = [];
var wrong = [];
var correctAns = 0;
var wrongAns = 0;
//function to print the result in ordered list
function printResult(result){
//HERE:
var oList = "<ol>";
for(var j = 0; j < result.length; j++){
oList += "<li>" + result[j] + "</li>";
}
oList += "</ol>";
return oList;
}
function print(message) {
document.getElementById('output').innerHTML += message;
}
//looping, adding correct and wrong answeres
for(var i = 0; i < 3; i++) {
answer[i] = prompt(quiz[i][0]);
if(parseInt(answer[i]) == quiz[i][1]){
correct.push(quiz[i][0]);
correctAns++;
} else {
wrong.push(quiz[i][0]);
wrongAns++;
}
}
//print logic
if(correct.length < 1 || correct == undefined){
print("You did not guess any of the quiestions!");
} else if (correct.length >= 1){
print("You have guessed " + correctAns + " questions.");
print(printResult(correct));
print("You have " + wrongAns + " wrong answeres.");
if(wrongAns > 0){
print(printResult(wrong));
}
}
<div id="output">
</div>

Basically you have three problems.
reuse of oList, the variable should be inside declared and used only in printResult.
Inside of printResult, use of i where j have been used and
At print, you replace the actual content with new content.
Just a small hint with variable names for counting. It is good practise to start always with i instead of j and go on with the letters in the alphabet.
var quiz = [["When is Bulgaria established?", 681], ["What year was it before 16 years?", 2000], ["When does WWII ends?", 1945]],
answer = [],
correct = [],
wrong = [],
correctAns = 0,
wrongAns = 0;
//function to print the result in ordered list
function printResult(result) {
var oList = "<ol>"; // !!! move variable inside of the function
for (var j = 0; j < result.length; j++) {
oList += "<li>" + result[j] + "</li>"; // !!! use j indstead if i
}
oList += "</ol>";
return oList;
}
function print(message) {
document.getElementById('output').innerHTML += message; // !!! append message
}
//looping, adding correct and wrong answeres
for (var i = 0; i < 3; i++) {
answer[i] = prompt(quiz[i][0]);
if (parseInt(answer[i]) == quiz[i][1]) {
correct.push(quiz[i][0]);
correctAns++;
} else {
wrong.push(quiz[i][0]);
wrongAns++;
}
}
//print logic
if (correct.length < 1 || correct == undefined) {
print("You did not guess any of the quiestions!");
} else if (correct.length >= 1) {
print("You have guessed " + correctAns + " questions.");
print(printResult(correct));
print("You have " + wrongAns + " wrong answeres.");
if (wrongAns > 0) {
print(printResult(wrong));
}
}

Your main mistake is using i intead of j:
for(var j = 0; j < result.length; j++){
oList += "<li>" + result[j] + "</li>";// here was i before
}

Related

How can I use a variable in String.fromCharCode()?

I am trying to get the code below to convert the unicode into a string but have no luck, please help?
function rot13(str) {
var message = "";
for (var i = 0; i < str.length; i++) {
message += str.charCodeAt(i) + " ";
}
message = message.split(" ").filter(Boolean).join(",");
return String.fromCharCode(message);
}
console.log(rot13("Hello World"))
fromCharCode("1,1,1,1") is not the same thing as fromCharCode(1,1,1,1) you need to use apply with an array.
function rot13(str) {
var message = "";
for (var i = 0; i < str.length; i++) {
message += str.charCodeAt(i) + " ";
}
message = message.split(" ").filter(Boolean);
return String.fromCharCode.apply(String, message);
}
console.log(rot13("Hello World"))
You want something like this:
http://buildingonmud.blogspot.com/2009/06/convert-string-to-unicode-in-javascript.html
function toUnicode(theString) {
var unicodeString = '';
for (var i = 0; i < theString.length; i++) {
var theUnicode = theString.charCodeAt(i).toString(16).toUpperCase();
while (theUnicode.length < 4) {
theUnicode = '0' + theUnicode;
}
theUnicode = '\\u' + theUnicode;
unicodeString += theUnicode;
}
return unicodeString;
}
console.log(toUnicode("Hello World"));

Javascript random table td -- nooverlap vertical-horizontal

I'm trying to avoid horizontal and vertical lines.
It stopped working with the Javascript array and for the rest of it.
I don't know how to create Javascript to randomly generate the first line and don't overlap with daeumjul. Please let me know. The code has been raised to jsfiddle.
Screenshot:
Javascript
var arr_person = ["#B22222","#0000cd","#FF00FF","#DAA520","#008000","#FF69B4","#4B0082","#E6E6FA","#ADD8E6","#90EE90"];
var arr_date = ['mon', 'tue', 'wed', 'thu','fri'];
var arr_subject = ['subject1','subject2','subject3','subject4','subject5'];
var arr_subject_check = new Array();
for(m=0; m < arr_subject.length; m++){
arr_subject_check[m] = new Array();
}
var arr_time = ['morning','after'];
var str = "";
function pickFromPool() {
var r = Math.floor(Math.random() * arr_pool.length);
return arr_pool.splice(r,1)[0];
}
str += "<table>";
for(var i=0; i < arr_date.length; i++){ // arr_date
var arr_pool = arr_person.slice();
str += "<tr>";
for(var j=0; j < arr_subject.length; j++ ){ //arr_subject
var arr_subject_check_cur = arr_subject_check[j].slice();
for(var n=0; n < arr_subject_check_cur.length; n++) {
var dup_index = arr_pool.indexOf(arr_subject_check_cur[n]);
if(dup_index < 0) {
} else {
arr_pool.splice(dup_index,1);
}
}
for(var k=0; k < arr_time.length; k++ ){
var pickedValue = pickFromPool();
arr_subject_check[j].push(pickedValue);
if(k == 0){
str += "<td style='border-left:#fff 4px solid;background-color:" + pickedValue + "'></td>";
} else {
str += "<td style='background-color:" + pickedValue + "'></td>";
}
}
for(var m=0; m < arr_subject_check_cur.length; m++) {
if(arr_subject_check_cur[m] !== '') {
arr_pool.push(arr_subject_check_cur[m]);
}
}
}
str += "</tr>";
}
str += "</table>";
jQuery('body').html(str);
https://jsfiddle.net/ipadorusa/vx8t25ts/1/
I'm trying to avoid horizontal and vertical lines.

Javascript: Calculating Min/Max/Average

I wrote this code in my html site, in Javascript, but is not working right. Most times it seems to ignore some entries and just randomly selects which is the min/max value. Also, when I tried to calculate average values, I got a string instead of a number, even though the variable is declared as 0 in the beginning. e.g performing 0+1+1+2+3+5 = 011235 instead of 12.
Here is the code, thanks in advance.
**EDIT: I added the student average code in the end, but it doesn't work, it doesn't show any results on the page, not even the "student" + [i] part. On the other hand, the parseInt() command worked, and made everything work as it should, thank you :)
<script language = "javascript">
function myFunction() {
var course0 = [];
var course1 = [];
var course2 = [];
var minstugrade = 100;
var maxstugrade = 0;
var minstugradetext = "";
var maxstugradetext = "";
var stuavgarr = [];
var minstuavg = 100;
var maxstuavg = 0;
var minstuavgtext = "";
var maxstuavgtext = "";
var mincougrade = 100;
var maxcougrade = 0;
var mincougradetext = "";
var maxcougradetext = "";
var mincouavg = 100;
var maxcouavg = 0;
var mincouavgtext = "";
var maxcouavgtext = "";
var couavg = 0;
//add form items to array
var x = document.getElementById("course0");
var i;
for (i = 0; i < x.length ;i++) {
course0.push(parseInt(x.elements[i].value));
}
var x = document.getElementById("course1");
var i;
for (i = 0; i < x.length ;i++) {
course1.push(parseInt(x.elements[i].value));
}
var x = document.getElementById("course2");
var i;
for (i = 0; i < x.length ;i++) {
course2.push(parseInt(x.elements[i].value));
}
//calculate course & student min/max
for (i = 0; i < course0.length; i++) {
if (course0[i] < mincougrade) {
mincougrade = course0[i];
mincougradetext = "course0";
}
if (course0[i] > maxcougrade) {
maxcougrade = course0[i];
maxcougradetext = "course0";
}
if (course0[i] < minstugrade) {
minstugrade = course0[i];
minstugradetext = "student" + [i];
}
if (course0[i] > maxstugrade) {
maxstugrade = course0[i];
maxstugradetext = "student" + [i];
}
}
for (i = 0; i < course1.length; i++) {
if (course1[i] < mincougrade) {
mincougrade = course1[i];
mincougradetext = "course1";
}
if (course1[i] > maxcougrade) {
maxcougrade = course1[i];
maxcougradetext = "course1";
}
if (course1[i] < minstugrade) {
minstugrade = course1[i];
minstugradetext = "student" + [i];
}
if (course1[i] > maxstugrade) {
maxstugrade = course1[i];
maxstugradetext = "student" + [i];
}
}
for (i = 0; i < course2.length; i++) {
if (course2[i] < mincougrade) {
mincougrade = course2[i];
mincougradetext = "course2";
}
if (course2[i] > maxcougrade) {
maxcougrade = course2[i];
maxcougradetext = "course2";
}
if (course2[i] < minstugrade) {
minstugrade = course2[i];
minstugradetext = "student" + [i];
}
if (course2[i] > maxstugrade) {
maxstugrade = course2[i];
maxstugradetext = "student" + [i];
}
}
//calculate course average
for (i = 0; i < course0.length; i++) {
couavg += course0[i];
}
couavg = couavg / course0.length
if (couavg < mincouavg) {
mincouavg = couavg;
mincouavgtext = "course0";
}
if (couavg > maxcouavg) {
maxcouavg = couavg;
maxcouavgtext = "course0";
}
couavg = 0;
for (i = 0; i < course1.length; i++) {
couavg += course1[i];
}
couavg = couavg / course1.length
if (couavg < mincouavg) {
mincouavg = couavg;
mincouavgtext = "course1";
}
if (couavg > maxcouavg) {
maxcouavg = couavg;
maxcouavgtext = "course1";
}
couavg = 0;
for (i = 0; i < course2.length; i++) {
couavg += course2[i];
}
couavg = couavg / course2.length
if (couavg < mincouavg) {
mincouavg = couavg;
mincouavgtext = "course2";
}
if (couavg > maxcouavg) {
maxcouavg = couavg;
maxcouavgtext = "course2";
}
//calculate student average
for (i = 0; i < course0.length; i++) {
stuavgarr[i] += course0[i];
stuavgarr[i] += course1[i];
stuavgarr[i] += course2[i];
}
for (i=0; i < stuavgarr.length; i++) {
stuavgarr[i] = stuavgarr[i] / course0.length;
if (stuavgarr[i] < minstuavg) {
minstuavg = stuavgarr[i];
minstuavgtext = "student" + [i];
}
if (stuavgarr[i] > maxstuavg) {
maxstuavg = stuavgarr[i];
maxstuavgtext = "student" + [i];
}
}
document.getElementById("studmaxgrade").innerHTML = "Student that achieved the max grade is " + maxstugradetext
document.getElementById("studmingrade").innerHTML = "Student that achieved the min grade is " + minstugradetext
document.getElementById("studmaxavg").innerHTML = "Student that achieved the max average is " + maxstuavgtext
document.getElementById("studminavg").innerHTML = "Student that achieved the min average is " + minstuavgtext
document.getElementById("courmaxgrade").innerHTML = "The course in which the max grade is scored is " + maxcougradetext
document.getElementById("courmingrade").innerHTML = "The course in which the min grade is scored is " + mincougradetext
document.getElementById("courmaxavg").innerHTML = "The course in which the max average grade is scored is " + maxcouavgtext
document.getElementById("courminavg").innerHTML = "The course in which the min average grade is scored is " + mincouavgtext
}
</script>
The value of an input is a string, thus a + b will be interpreted as appending one string to another.
If you make sure the first parameter (a in this case) is an integer a + b will result in the two being mathematically adding the two
console.log( '0' + 1 + 2 + 3 + 4 ); //* outputs 01234
console.log( parseInt( 0 ) + 1 + 2 + 3 + 4 ); //* outputs 10
JSFiddle
Ok for a start you seem very confused about
document.getElementById
This does not address a javascript variable at all......
This literally "gets the document element by its id".
Here is an example of how to use it...
<html>
<img id='my_new_selfie' src='me.jpg'>
....
....
<script>
alert (document.getElementById('my_new_selfie').src)
</script>
This would simply pop up an alert with the text that describes the src of the
document object who's id is 'my_new_selfie'
that is....
[me.txt]
The reason that document.getElementById was introduced to javascript was to save developers learning the DOM (document object model) in order to access objects.
It allows you to simply give you object an id and change things about it using the id
In the above example I could use a script or button to change the image source
an example of this might be using the onclick event of another object on the page like a button...
onclick='document.getElementById('my_new_selfie').src='new_pic_of_me.JPG'
It is not used to identify variables in a javascript

Javascript Can't use array content as array index?

When I trird to run the js code, it always said "Uncaught TypeError: Cannot read property '_id' of undefined" for
deployedID.push(data[j]._id);
So after some thinking, I believe the problem lies in
var j = deploy[i];
Is there any way to solve it? Thanks in advance.
Below is the complete code:
var deploy = [];
var deployedID = [];
var deployedename = [];
var deployedoname = [];
var deployedrank = [];
function popularizeTable(){
$.get("/SSS/getlist", function(data){
deploy = randomunique(data.length ,100);
for (var i = 0; i < 100; i++){
var j = deploy[i];
deployedID.push(data[j]._id);
deployedename.push(data[j].ename);
deployedoname.push(data[j].oname);
deployedrank.push(data[j].rank);
}
var str = " ";
var k = 0;
for (var i = 0; i < 5; i++){
str += "<tr>";
for(var j = 0; j < 20; j++){
str += "<td><section id=\"" + deployedID[k] + "\" class=\"container\"><div class=\"card\">"
str += "<figure class=\"front\"><img src=\"images/back.jpg\"></figure>";
str += "<figure class=\"back\"><img src=\"images/Clear/" + deployedename[k] + "/001.jpg\"></figure></div></td></section>";
k++;
}
str += "</tr>";
}
$("#table").append(str);
});
}
$( document ).ready(function() {
popularizeTable();
$(document).on("mouseover", ".card", function(){
$(this).toggleClass("flipped")});
});
function randomunique(max, num){
var uniquelist = [];
for (var j = uniquelist.length; j < num; j++){
var i = parseInt(Math.random() * (max - 1) + 1);
if (uniquelist.indexOf(i) == -1){
uniquelist.push(i);
}
}
return uniquelist;
}

Mccluskey algorithm, javascript

<html>
<body>
<script type="text/javascript">
start();
function start() {
var val = "0,1";
var n = 5;
var chars = ['a', 'b', 'c', 'd', 'e'];
gVars = chars.slice(0, n);
for (var i = 0; i < gVars.length; i++)
document.write(gVars[i] + "<br />");
var termsStr = val.split(',');
for (var i = 0; i < termsStr.length; i++)
document.write(termsStr[i] + "<br />");
var gOrigTerms = [];
var maxterm = Math.pow(2, termsStr.length) - 1;
document.write("maxterm: " + maxterm + "<br />");
for (var i = 0; i < termsStr.length; i++) {
gOrigTerms[i] = parseInt(termsStr[i]);
document.write(gOrigTerms[i] + "<br />");
if (gOrigTerms[i] > maxterm) document.write("Invalid term in term list." + "<br />");
}
gFormula = new Formula(gVars, gOrigTerms);
document.write(gFormula);
gFormula.toString();
gFormula.reduceToPrimeImplicants(); //here the breakpoint is inserted
}
function Formula(vars, terms)
{
this.vars = vars;
this.termList = [];
for (var i = 0; i < terms.length; i++) {
this.termList[i] = new Term(Dec2Bin(terms[i], vars.length));
document.write("this.termList" + this.termList[i] + "<br />");
}
this.orginalTermList = [];
document.write("this.orginalTermList" + this.orginalTermList + "<br />");
}
function Dec2Bin(dec, size) {
var bits = [];
for (var bit = 0; bit < size; bit++)
{
bits[bit] = 0;
}
var i = 0;
while (dec > 0)
{
if (dec % 2 == 0)
{
bits[i] = 0;
} else
{
bits[i] = 1;
}
i++;
dec = (dec / 2) | 0;
// Or with zero casts result to int (who knows why...)
}
bits.reverse();
return bits;
}
function Term(varVals)
{
this.varVals = varVals;
document.write("this.varVals: " + this.varVals);
}
function reduceToPrimeImplicants() //there is some problem with this function
{
this.originalTermList = this.termList.slice(0);
var numVars = this.termList[0].getNumVars();
var table = [];
for (var dontKnows = 0; dontKnows <= numVars; dontKnows++) {
table[dontKnows] = [];
for (var ones = 0; ones <= numVars; ones++) {
table[dontKnows][ones] = [];
}
table[dontKnows][numVars + 1] = [];
}
table[numVars + 1] = [];
table[numVars + 1][numVars + 1] = [];
for (var i = 0; i < this.termList.length; i++) {
var dontCares = this.termList[i].countValues(DontCare);
var ones = this.termList[i].countValues(1);
var len = table[dontCares][ones].length;
table[dontCares][ones][len] = this.termList[i];
}
for (var dontKnows = 0; dontKnows <= numVars - 1; dontKnows++) {
for (var ones = 0; ones <= numVars - 1; ones++) {
var left = table[dontKnows][ones];
var right = table[dontKnows][ones + 1];
var out = table[dontKnows + 1][ones];
for (var leftIdx = 0; leftIdx < left.length; leftIdx++) {
for (var rightIdx = 0; rightIdx < right.length; rightIdx++) {
var combined = left[leftIdx].combine(right[rightIdx]);
if (combined != null) {
if (out.indexOf(combined) < 0) {
var len = out.length;
out[len] = combined;
}
if (this.termList.indexOf(left[leftIdx]) >= 0) {
this.termList.splice(this.termList.indexOf(left[leftIdx]), 1);
}
if (this.termList.indexOf(right[rightIdx]) >= 0) {
this.termList.splice(this.termList.indexOf(right[rightIdx]), 1);
}
if (this.termList.indexOf(combined) < 0) {
var len = this.termList.length;
this.termList[len] = combined;
}
}
}
}
}
}
}
function getNumVars()
{
return this.varVals.length;
}
function countValues(value)
{
result = 0;
for (var i = 0; i < this.varVals.length; i++) {
if (this.varVals[i] == value) {
result++;
}
}
return result;
}
function combine(term)
{
var diffVarNum = -1; // The position where they differ
for (var i = 0; i < this.varVals.length; i++) {
{
if (this.varVals[i] != term.varVals[i])
if (diffVarNum == -1) {
diffVarNum = i;
} else { // They're different in at least two places return null; }
}
}
if (diffVarNum == -1)
{
// They're identical return null;
}
resultVars = this.varVals.slice(0);
resultVars[diffVarNum] = DontCare;
return new Term(resultVars);
}
</script>
</body>
</html>
In the above code, that is not complete, but which implements quine Mccluskey algorithm. There is a problem while it is debugged.
If a breakpoint is inserted at gFormula.reducetoPrimeImplicants(); the debugger does not go into that function. This is the last function called in the code until now. But, it does go to start(), which is the first function.
There is some problem in reducetoPrimeImplicants(); function because it also gives ERROR in internet explorer.
I am not able to figure out the error. If I remove reducetoPrimeImplicants(); function from the code the works fine.
Please, can somebody tell me why the debugger does not enter reducetoPrimeImplicants();.
I am using the Firebug debugger.
Thanks in advance.
The last function in your page combine() is missing a closing brace.
If you don't mind, a suggestion: Please use http://jsbeautifier.org/ or some similar tool to indent your code better.
Your For loop has two starting braces.
for (var i = 0; i < this.varVals.length; i++) {
{
So remove one. This should solve your problem.

Categories