Index Values Do Not Equal Answers - javascript

I am creating a hangman game and need the green rectangles to change to red rectangles when the inputted answer by the player is INCORRECT. The total calculating function works, the input !==answers does not work which is what I need help with.
var total = 0;
gameboard.fillStyle = 'green';
gameboard.fillRect(10, 30, 30, 30)
gameboard.fillRect(80, 30, 30, 30)
gameboard.fillRect(150, 30, 30, 30)
$('#total_score').on('click', calculate);
function calculate() {
for (var index = 0; index < 14; index = index + 1) {
if ($('#' + index).val() == answers[index]) {
total = total + 1;
}
if ($('#' + index).val() !== answers[index]) {
gameboard.fillStyle = 'red';
gameboard.fillRect(10, 30, 30, 30)
}
}
$('#display_total').html(total);
total = 0;
};

Related

Value check during iteration of a loop

So I've been sent a technical test for a job interview, I've done the vast majority of it but having an issue with one part. Effectively, it needs to check whether the health of the elephant is under 70, if it is it can no longer walk, if this is still the case on the next iteration of the interval, it needs to pronounce them dead. My code works some of the time but also allows them to go straight from healthy to dead and it also seemingly allows them to not die when the iteration happens when they can't walk.
Below is the code and a JS fiddle.
https://jsfiddle.net/Stackz18/dprk1fto/3/
var timer = 0;
var monkeyArray = [100, 100, 100, 100, 100];
var giraffeArray = [100, 100, 100, 100, 100];
var elephantArray = [100, 100, 100, 100, 100];
function feedingMonkeys() {
for (let i = 0; i < monkeyArray.length; i++) { //loop through array
var feedingNumber = parseInt(Math.floor(Math.random() * 16) + 10); //create unique random number between 10 and 25
if (monkeyArray[i] <= 100 && monkeyArray[i] >= 30) { // if between 99 and 30 run the code
monkeyArray[i] = monkeyArray[i] + feedingNumber; // add random number to array value
let TransformedArray = monkeyArray.map(item => item >= 100 ? 100 : item <= 29 ? 'Dead' : item); //remap array in new array to show status of animal
$('.m-health').each(function (i, obj) {
this.innerHTML = TransformedArray[i]; // change html value to the new mapped array values
});
}
else if (monkeyArray[i] >= 100) {
monkeyArray[i] = 100;
}
}}
function feedingGiraffes() {
for (let i = 0; i < giraffeArray.length; i++) { //loop through array
var feedingNumber = parseInt(Math.floor(Math.random() * 16) + 10); //create unique random number between 10 and 25
if (giraffeArray[i] <= 100 && giraffeArray[i] >= 30) { // if between 99 and 30 run the code
giraffeArray[i] = giraffeArray[i] + feedingNumber; // add random number to array value
let TransformedArray = giraffeArray.map(item => item >= 100 ? 100 : item <= 29 ? 'Dead' : item); //remap array in new array to show status of animal
$('.g-health').each(function (i, obj) {
this.innerHTML = TransformedArray[i]; // change html value to the new mapped array values
});
}
else if (giraffeArray[i] >= 100) {
giraffeArray[i] = 100;
}
}}
function feedingElephants() {
for (let i = 0; i < elephantArray.length; i++) { //loop through array
var feedingNumber = parseInt(Math.floor(Math.random() * 16) + 10); //create unique random number between 10 and 25
if (elephantArray[i] <= 100) { // if under 100 run the code
elephantArray[i] = elephantArray[i] + feedingNumber;
let TransformedArray = elephantArray.map(item => item >= 100 ? 100 : item <= 70 ? item + ': Can no longer walk' : item);
console.log(TransformedArray);
$('.e-health').each(function (i, obj) {
this.innerHTML = TransformedArray[i];
});
if (elephantArray[i] > 70) {
$(this).parents(".elephant").removeClass("walk");
}
}
else if (elephantArray[i] >= 100) {
elephantArray[i] = 100;
}
}
}
function feeding() {
feedingMonkeys();
feedingGiraffes();
feedingElephants();}
function monkeyHealth() {
for (let i = 0; i < monkeyArray.length; i++) {
var removeNumber = parseInt(Math.floor(Math.random() * 21));
monkeyArray[i] = monkeyArray[i] - removeNumber;
}
let TransformedArray = monkeyArray.map(item => item >= 100 ? 100 : item <= 29 ? 'Dead' : item);
$('.m-health').each(function (i, obj) {
this.innerHTML = TransformedArray[i];
if (monkeyArray[i] < 30) {
$(this).parents(".monkey").addClass("dead");
}
});}
function giraffeHealth() {
for (let i = 0; i < giraffeArray.length; i++) {
var removeNumber = parseInt(Math.floor(Math.random() * 21));
giraffeArray[i] = giraffeArray[i] - removeNumber;
}
let TransformedArray = giraffeArray.map(item => item >= 100 ? 100 : item <= 29 ? 'Dead' : item);
$('.g-health').each(function (i, obj) {
this.innerHTML = TransformedArray[i];
if (giraffeArray[i] < 30) {
$(this).parents(".giraffe").addClass("dead");
}
});}
function elephantHealth() {
for (let i = 0; i < elephantArray.length; i++) {
if (elephantArray[i] <= 70) {
let TransformedArray = elephantArray.map(item => item >= 100 ? 100 : item <= 70 ? 'Dead' : item);
$('.e-health').each(function (i, obj) {
this.innerHTML = TransformedArray[i];
if (elephantArray[i] < 70) {
$(this).parents(".elephant").removeClass("walk");
$(this).parents(".elephant").addClass("dead");
}
});
}
else {
let TransformedArray = elephantArray.map(item => item >= 100 ? 100 : item <= 70 ? item + '%: Can no longer walk': item);
$('.e-health').each(function (i, obj) {
this.innerHTML = TransformedArray[i];
if (elephantArray[i] <= 70) {
$(this).parents(".elephant").addClass("walk");
}
});
}
var removeNumber = parseInt(Math.floor(Math.random() * 21));
elephantArray[i] = elephantArray[i] - removeNumber;
}}
var intervalId = window.setInterval(function () {
timer += 1;
if (timer >= 24) {
timer = 0
}
document.getElementById("hour").innerHTML = timer;
monkeyHealth();
giraffeHealth();
elephantHealth();
}, 2000);

why my javascript is showing value not founded?

I am trying to do a binary search in an array but my javascript is showing no value founded even when I entered a number that in the array in the prompt input
var array = [10, 20, 30, 40, 50, 60, 70, 80, 90, 95, 100, 102, 105, 200, 250, 300, 320, 350];
var search = parseInt(prompt("enter what you search for"));
var first = 0,
last = array.length - 1,
position = 0,
middle, flag = false;
while ((flag == false) && (first <= last)) {
middle = ((first + last) / 2);
if (array[middle] == search) {
flag = true;
position = middle;
} else
if (array[middle] > search)
last = middle - 1;
else
first = middle + 1;
}
if (flag)
document.write("</br>value founded in position " + position);
else
document.write("</br>value not founded ");
middle value calculation.
middle = Math.round(first + ((last - first) / 2));
// Your code..
var array =[10,20,30,40,50,60,70,80,90,95,100,102,105,200,250,300,320,350] ;
var search= 20; //parseInt(prompt ("enter what you search for"));
var first=0, last=array.length-1,
position=0,
middle ,
flag=false;
while((flag==false) && (first <=last)) {
middle = Math.round(first + ((last - first) / 2)); //((first+last)/2); low + (last - low)/2
if (array[middle]==search){
flag=true;
position=middle ;
}else if(array[middle]>search) {
last=middle-1 ;
}
else {
first= middle+1;
}
}
if (flag)
document.write ("</br>value founded in position "+position);
else
document.write("</br>value not founded ");
For now when you do middle = ((first + last) / 2); it puts the number with floating point to the middle. However, you need to have integer number here. In order to make it you should wrap your calculation with Math.round() or Math.floor().
So you will get:
middle = Math.round((first + last) / 2);

how to calculate the ways of a big number split by some small numbers in js

For example: There is a total number 1000, and how many ways to equal 1000 using 100/50/20/10/5/1. I have found a idea about this. But obviously, that's not good. So does anyone have some other good ideas to cover it?
total = prompt('you can input number 1-1000, but 1000 will take a LOONG time');
count = 0;
t100 = total;
function money() {
for (var i100 = Math.floor(t100 / 100); i100 >= 0; i100--) {
var t50 = t100 - i100 * 100;
for (var i50 = Math.floor(t50 / 50); i50 >= 0; i50--) {
var t20 = t50 - i50 * 50;
for (var i20 = Math.floor(t20 / 20); i20 >= 0; i20--) {
var t10 = t20 - i20 * 20;
for (var i10 = Math.floor(t10 / 10); i10 >= 0; i10--) {
var t5 = t10 - i10 * 10;
for (var i5 = Math.floor(t5 / 5); i5 >= 0; i5--) {
var t1 = t5 - i5 * 5;
count++;
console.log(i100 + ' 100' + i50 + ' 50' + i20 + ' 20' + i10 + ' 10' + i5 + ' 5' + t1 + ' 1');
}
}
}
}
}
alert('The total number ' + total + ' is ' + count);
}
money()
No idea if it's correct but a little idea that popped to my head:
You know that with the bills/coins given, you can always fill up to the amount you need (value). If at the same time, you assume that you will always chose the highest possible bill / coin for the remainder I think you could do this:
If you use 100 bills you have floor(value / 100) possibilities (You can use 1 x 100, 2 x 100... )
If you don't use 100 but 50 you have floor(value / 50) possibilities
If you don't use 50 but 20 you have floor(value /20) possibilities
and so on. Add those up and you have a total of possibilities.
Let me know if I'm missing something.
I don't know about coding in js but you could try an algorithm like this one, which should be much more performant timely speaking. I'll try to make it as clear as possible :
availableCoins = [100, 50, 20, 10, 5] // all available coins exept 1
numberCoins = availableCoins.Length
mapResults = new Map[(int,int),int]
money(int total, int indexCoin){
if ( indexCoin == numberCoins ) {
return 1 // only coin 1 is available, there is only one solution
}
elseif ( mapResults.containsKey((total,indexCoin)) ) {
return mapResults((total,indexCoin)) // if the result has already been computed
}
else {
int count = 0
int currentCoin = availableCoin[indexCoin]
int upperbound = floor(total / currentCoin) // compute it before to avoid useless computation
for (int i = 0; i <= upperbound; i++) {
count += money(total - i * currentCoin, indexCoin + 1) // we assume only i of the current coin will be use
}
mapResults((total,indexCoin)) = count
return count
}
}
money(1000, 0)
Let me know if I have missed something or if it is not clear.
I let you adapt it to js.
I have got a expression from my colleague, and here it is:
//n is the total number
Change(n,m) {
if(n===0) return 0;
if(n<0 || m === 0) return 0;
var dimes = [1, 5, 10, 20, 50, 100];
return (change(n, m-1)+change(n-dimes[m-1], m));
}

Write patterns with javascript

i'm doing a "Steve Reich - Clapping Music" kinda thing with "xoxoxoxx" with x as the clapping. but i want it to write the pattern while it keep going to the right. so you'd have this kinda writing:
xoxoxoxxxoxoxoxxxoxoxoxxxoxoxoxx
xoxoxoxxoxoxoxxxoxoxxoxoxxxoxoxo
so it prints the X or O and then goes a bit to the right and prints again. I hope this is clear, english isn't my first language, so i'm sorry if it's hard to understand. here is the full code for 2 lines because i'm bad at explaining:
var noise, env;
var seq = "o x o x o x o x o x o x o x x x";
var steps = seq.split(" ");
var speed = 8;
var count = 0;
var count2 = 0;
var count3=0;
var shift = 0;
var repeat = 1;
var sf, sf2, sf3;
var f;
function preload() {
sf = loadSound("./files/clap.wav");
sf2 = sf;
sf3 = sf;
}
function setup() {
createCanvas(400, 400);
env = new p5.Env(0.01, 1, 0.2, 0.1);
env2 = new p5.Env(0.1, 0.8, 0.01, 0.1);
env3 = new p5.Env(0.05, 0.9, 0.1, 0.1);
}
function hitMeSteve(when, env, loc) {
if (when == 'x' && frameCount % speed == 0) {
env.play();
}
}
function draw() {
if (frameCount % speed == 0) {
count++;
}
if (frameCount % (steps.length * speed * repeat) == 0) {
shift++;
count2=count2+2;
count3=count3+4;
}
if(shift==4){
shift=0;
count2=0;
count3=0;
}
shift = shift % steps.length;
shift2 = shift + 2;
var now = steps[count % steps.length];
hitMeSteve(now, sf, 10);
var canon = steps[(count + shift) % steps.length];
hitMeSteve(canon, sf2, width / 2 + 10);
var canon2 = steps[(count + shift+count2) % steps.length];
hitMeSteve(canon2, sf3, width / 2 + 20);
textSize(30);
//1
for (var i = 0; i < steps.length; i++) {
if (i == count % steps.length) {
fill(255, 180, 0);
} else {
fill(0);
}
text(steps[i],10+ ( + i) * 15,20);
//text(steps[i], 110 + (shift / 2 + i) * 15, height / 2);
}
//2
for (var i = 0; i < steps.length; i++) {
if (i == (count + shift) % steps.length) {
fill(255, 180, 0);
} else {
fill(0);
}
text(steps[i],10+( + i)*15,40);
//text(steps[i], 110 + (-shift / 2 + i) * 15, height / 2 + 20);
}
}
Just a proposal with setInterval, maybe this works for you.
var content = "oxoxoxoxoxoxoxxx",
target = document.getElementById('ticker'),
i = 0,
timer = setInterval(addChar, 800);
function addChar() {
if (i < content.length) {
target.innerHTML += ' ' + content[i];
i++;
} else {
target.innerHTML = '';
i=0;
}
}
<div id="ticker"></div>

Editing jquery-countdown to fit my HTML element

I've collected a nice jQuery countdown script from here. It needs no configuration but a great opensource project. But where I want to set is a smaller place like 50%. So, now I want to make it 50% on both width and height. First of all I opened digits.png with photoshop and made it 50%, then I opened jquery.countdown.js and the code is following:
jQuery.fn.countdown = function(userOptions)
{
// Default options
var options = {
stepTime: 60,
// startTime and format MUST follow the same format.
// also you cannot specify a format unordered (e.g. hh:ss:mm is wrong)
format: "dd:hh:mm:ss",
startTime: "01:12:32:55",
digitImages: 6,
digitWidth: 67,
digitHeight: 90,
timerEnd: function(){},
image: "digits.png",
continuous: false
};
var digits = [], intervals = [];
// Draw digits in given container
var createDigits = function(where)
{
var c = 0;
// Iterate each startTime digit, if it is not a digit
// we'll asume that it's a separator
for (var i = 0; i < options.startTime.length; i++)
{
if (parseInt(options.startTime[i]) >= 0)
{
elem = $('<div id="cnt_' + c + '" class="cntDigit" />').css({
height: options.digitHeight,
float: 'left',
background: 'url(\'' + options.image + '\')',
width: options.digitWidth
});
elem.current = parseInt(options.startTime[i]);
digits.push(elem);
margin(c, -elem.current * options.digitHeight * options.digitImages);
if (options.continuous === true)
{
digits[c]._max = function(){ return 9; };
}
else
{
// Add max digits, for example, first digit of minutes (mm) has
// a max of 5. Conditional max is used when the left digit has reach
// the max. For example second "hours" digit has a conditional max of 4
switch (options.format[i])
{
case 'h':
digits[c]._max = function(pos, isStart) {
if (pos % 2 == 0)
return 2;
else
return (isStart) ? 3: 9;
};
break;
case 'd':
digits[c]._max = function(){ return 9; };
break;
case 'm':
case 's':
digits[c]._max = function(pos){ return (pos % 2 == 0) ? 5: 9; };
}
}
++c;
}
else
{
elem = $('<div class="cntSeparator"/>').css({float: 'left'})
.text(options.startTime[i]);
}
where.append(elem)
}
};
// Set or get element margin
var margin = function(elem, val)
{
if (val !== undefined)
{
digits[elem].margin = val;
return digits[elem].css({'backgroundPosition': '0 ' + val + 'px'});
}
return digits[elem].margin || 0;
};
var makeMovement = function(elem, steps, isForward)
{
// Stop any other movement over the same digit.
if (intervals[elem])
window.clearInterval(intervals[elem]);
// Move to the initial position (We force that because in chrome
// there are some scenarios where digits lost sync)
var initialPos = -(options.digitHeight * options.digitImages *
digits[elem].current);
margin(elem, initialPos);
digits[elem].current = digits[elem].current + ((isForward) ? steps: -steps);
var x = 0;
intervals[elem] = setInterval(function(){
if (x++ === options.digitImages * steps)
{
window.clearInterval(intervals[elem]);
delete intervals[elem];
return;
}
var diff = isForward ? -options.digitHeight: options.digitHeight;
margin(elem, initialPos + (x * diff));
}, options.stepTime / steps);
};
// Makes the movement. This is done by "digitImages" steps.
var moveDigit = function(elem)
{
if (digits[elem].current == 0)
{
// Is there still time left?
if (elem > 0)
{
var isStart = (digits[elem - 1].current == 0);
makeMovement(elem, digits[elem]._max(elem, isStart), true);
moveDigit(elem - 1);
}
else // That condition means that we reach the end! 00:00.
{
for (var i = 0; i < digits.length; i++)
{
clearInterval(intervals[i]);
clearInterval(intervals.main);
margin(i, 0);
}
options.timerEnd();
}
return;
}
makeMovement(elem, 1);
};
$.extend(options, userOptions);
createDigits(this);
intervals.main = setInterval(function(){ moveDigit(digits.length - 1); },
1000);
};
I tried changing some variables, digitWidth: 67 to digitWidth: 34 then digitHeight: 90 to digitHeight: 45 with no success. I want to make the countdown timer just half than the original. Can you suggest any change anywhere in the code, please?
Update: This is digits.png, 50% than original!
I also changed associated div's like #holder with no success.
Following is the current situation of the timer. The red marked places are the problems I mean misplaced.
You didn't resize digits.png correctly - it's too high, so digitHeight doesn't match your image.
See demo with an image that has 50% height (plugin code unchanged):
http://jsfiddle.net/lhoeppner/RGyPQ/
See the section with the image param:
$('#counter').countdown({
stepTime: 60,
digitWidth: 34,
digitHeight: 45,
format: 'hh:mm:ss',
startTime: "12:32:55",
timerEnd: function () {
alert('end!!');
},
image: "http://s21.postimg.org/nfgjv6b7r/digits2.png"
});

Categories

Resources