If function javascript not working - javascript

I'm a total javascript noob and I'm just trying to bludgeon my way through this simple project. Whats supposed to happen is the script is only meant to run while y <= 3. Each time that it runs the second IF statement, it's meant to add one to y's count and if it runs the ELIF, it's meant to subtract one from y's count. The goal is so that you can only have 3 "selected" pictures at any one time. My y does definitely change, but the IF (y <= 3) does not seem to stop the program from running. Thanks in advance, Jack
<SCRIPT type="text/javascript">
var y = 4; //this is a counter
function swapRoast() { //This defines the function
var x=document.images; //this automatically creates an array of all the images in the document starting with image0 and assigns them to variable'x'
if (y <= 3); { //this should check that y <= 3 before running
if (x[0].src.match('Roast_Vegetables.png')) //This tests if the source of image0 in the array matches the script
{
x[0].src=('Roast_Vegetables_Selected.png'); //If the source matches, then it is changed
y ++; //should add 1 to the y count
}
else if (x[0].src.match('Roast_Vegetables_Selected.png')) //If the source doesn't match, then it tests a different source
{
x[0].src=('Roast_Vegetables.png'); //If the different source matches, then the script operates in reverse to the original IF
y --; //should subtract 1 from the y count
}
}
}
function swapVege(obj) {
var x=document.images;
if (y <= 3); {
if (x[1].src.match('Vegetables.png'))
{
x[1].src=('Vegetables_Selected.png');
y ++;
document.getElementById("demo").innerHTML = y;
}
else if (x[1].src.match('Vegetables_Selected.png'))
{
x[1].src=('Vegetables.png');
y --;
document.getElementById("demo").innerHTML = y;
}
}
}

The semicolon is unfortunate and terminates the if block immediately. Change (in both places)
if (y <= 3); {
to something like
if (y <= 3) {

if (y <= 3); {
take out the ";" here

Related

How to optimize code for HackerRank's Fraudulent Activity Notification problem

I have been working to solve this problem on the HackerRank site: Fraudulent Activity Notifications.
Below is the code I have written which satisfies the three sample test cases; however, it does not satisfy the larger test cases since it seems to take longer than 10 seconds.
The 10 second constraint is taken from here: HackerRank Environment.
function activityNotifications(expenditure, d) {
let notifications = 0;
let tmp = [];
let median = 0, medianEven = 0, iOfMedian = 0;
// Begin looping thru 'expenditure'
for(let i = 0; i < expenditure.length; i++) {
// slice from 'expenditure' beginning at 'i' and ending at 'i + d' where d = number of days
// sort 'tmp' in ascending order after
tmp = expenditure.slice(i, i + d);
tmp.sort();
// edge case, make sure we do not exceed boundaries of 'expenditure'
if((i + d) < expenditure.length) {
// if length of 'tmp' is divisible by 2, then we have an even length
// compute median accordingly
if(tmp.length % 2 == 0) {
medianEven = tmp.length / 2;
median = (tmp[medianEven - 1] + tmp[medianEven]) / 2;
// test if expenditures > 2 x median
if(expenditure[i + d] >= (2 * median)) {
notifications++;
}
}
// otherwise, we have an odd length of numbers
// therefore, compute median accordingly
else {
iOfMedian = (tmp.length + 1) / 2;
// test if expenditures > 2 x median
if(expenditure[i + d] >= (2 * tmp[iOfMedian - 1])) {
notifications++;
}
}
}
}
return notifications;
}
I am familiar with O notation for computing time complexity, so initially it seems the problem is either the excessive amount of variables declared or conditional statements used. Only one for loop is being used so I don't think the loop is where I should look to optimize the code. Unless, of course, we were to include the .sort() function used on 'tmp' which would definitely add to the time it takes to compute efficiently.
Is there anything I have not realized which is causing the code to take longer than expected? Any other hints would be greatly appreciated, thanks.

Looped algorithm to increment a number until it reaches a value, then decrement

I'm trying to increment a number until it reaches a value (say 100), then make it decrement until it reaches 0, and have all this run in a while loop.
The code seems correct, but the browser is freezing, so I can't check in the console if there's a flaw in the algorithm.
var ceiling = 100;
var floor = 1;
var x = 1;
var step = 1;
setInterval(function(){
while(1) {
while(x + step <= ceiling) {
x += step;
document.write(x + ' ');
}
while(x - step >= floor) {
x -= step;
document.write(x + ' ');
}
}
}, 1500);
I've used setInterval here to slow down execution and avoid some buffering issue with the browser. It shouldn't be a problem since I have 16GB of RAM, but it might depend on how the browser can use/access that too in one tab.
I've also tried wrapping the setInterval function inside another function and execute it, with the same result.
You have a while(1) loop which basically is a infinite loop, even if no code is executed, it will freeze the browser.
The other answers have already pointed out the problems with your endless loop and with using document.write.
I think this does what you want:
var ceiling = 100;
var floor = 1;
var x = 1;
var step = 1;
setInterval(function() {
console.log(x);
x += step;
if (x === ceiling || x === floor) {
step = -step;
}
}, 1500);
setInterval is essentially your while(1) loop.
document.write is only intended to be used on the first rendering of the document. since you are doing an interval, then the doc is already rendered, and you can't use document.write. instead, you need to append your text to the body or a div

setInterval dosn't work as expected

function startAutoScrolling() {
var distance = y2 - y1;
var speed = distance / dateDiff;
interval1 = setInterval(function() { doAutoScrolling(speed); }, 1);
}
here I want to decrease step on 0.1
but it dosn't work like that, and I don't know why
function doAutoScrolling(step) {
document.getElementById(CONTEINER).scrollTop += step;
if (isGoingDown) {
step = step - 0.1;
console.log("step - 1: " + step);
if (step <= 0) {
clearInterval(interval1);
}
} else { // there is continue below
here I want to increase step and if condition have to stop execution of block
but it doesn`t work also
step += 0.01;
if (step >= 0) {
clearInterval(interval1);
}
}
}
You're using the Javascript comma-operator in place where you most probably want to use a decimal, e.g.:
step = step - 0,1;
Should be:
step = step - 0.1;
More about the comma-operator:
What does a comma do in JavaScript expressions?
When is the comma operator useful?
UPDATE (after commas to dots -change)
Primitives are passed-by-value in Javascript (see: Does Javascript pass by reference?) so you're basically calling doAutoScrolling over and over again with the same value (the value of speed). You need to do one of the following:
wrap speed in an object in order to pass-by-reference
make speed a global variable or at least defined in the parent context of doAutoScrolling
Replace setInterval with setTimeout and set a new timeout in doAutoScrolling:
var newStep = /* calculate new step */
setTimeout("doAutoScrolling("+newStep+")",1);

Action Script 3. Check array if any element not Jumping, then jump

So I need to make items jumping. I have array with 6 elements (items). I need to make that they randomly jumped, but if any item jumping, other should stay.
I have code for jumping, on EnterFrame for 1 item it working normally - jumping non stop.
But here is problem that If I try to use this function once (for example as MouseEvent.CLICK), item decrease item's y by 15px. If I use this function 2nd time It decrease It's y by 15px again. So at all I need to launch this function 19 times to make full jump.
//whether or not the main guy is jumping
var mainJumping:Boolean = false;
//how quickly should the jump start off
var jumpSpeedLimit:int = 15;
//the current speed of the jump;
var jumpSpeed:Number = jumpSpeedLimit;
function updateItems(e:Event):void {
var j:Number = Math.round(Math.random()*5);
if(!mainJumping){
//then start jumping
mainJumping = true;
jumpSpeed = jumpSpeedLimit*-1;
item1[j].y += jumpSpeed;
} else {
//then continue jumping if already in the air
if(jumpSpeed < 0){
jumpSpeed *= 1 - jumpSpeedLimit/75;
if(jumpSpeed > -jumpSpeedLimit/5){
jumpSpeed *= -1;
}
}
if(jumpSpeed > 0 && jumpSpeed <= jumpSpeedLimit){
jumpSpeed *= 1 + jumpSpeedLimit/50;
}
item1.y += jumpSpeed;
//if main hits the floor, then stop jumping
//of course, we'll change this once we create the level
if(item1[j].y <= 450){
mainJumping = false;
item1[j].y = 0;
}
}
I've tried to make for loop to use function 19 times (var i = 0; i <19; i++){ ... ,but after It item not jumping at all. Have you any ideas how to make that I used function once I made full jump?
After I created var j:Number = Math.round(Math.random()*5); It working in bad case, because It starting to jump 2nd items, till 1st not completed jump.
//whether or not the main guy is jumping
var mainJumping:Boolean = false;
//how quickly should the jump start off
var jumpSpeedLimit:int = 15;
//the current speed of the jump;
var jumpSpeed:Number = jumpSpeedLimit;
// we declare the variable that will hold the random number
var randomItem:Number;
// this function will select a random number and make the item corresponding
// to that number to jump. You call it once and it continues running.
function selectRandom():void
{
randomItem = Math.round(Math.random() * 5);
this.addEventListener(Event.ENTER_FRAME, updateItems);
}
function updateItems(e:Event):void {
if(!mainJumping){
//then start jumping
mainJumping = true;
jumpSpeed = jumpSpeedLimit*-1;
item1[randomItem].y += jumpSpeed;
} else {
//then continue jumping if already in the air
if(jumpSpeed < 0){
jumpSpeed *= 1 - jumpSpeedLimit/75;
if(jumpSpeed > -jumpSpeedLimit/5){
jumpSpeed *= -1;
}
}
if(jumpSpeed > 0 && jumpSpeed <= jumpSpeedLimit){
jumpSpeed *= 1 + jumpSpeedLimit/50;
}
item1.y += jumpSpeed;
//if main hits the floor, then stop jumping
//of course, we'll change this once we create the level
if(item1[randomItem].y <= 450){
mainJumping = false;
item1[randomItem].y = 0;
// after the item is finished jumping, we remove the listener
// and make it select another number. It is basically a loop.
this.removeEventListener(Event.ENTER_FRAME, updateItems);
selectRandom();
}
}
I just copy/pasted your code and made some modifications. I believe you missed some curly braces somewhere. That aside, the idea is to declare a variable outside of the updateItems method, so the number of the item doesn't randomly change every frame. Hope this solved your problem.

Cellular automata implemented in JavaScript and HTML5 Canvas

I implemented a Conway's Game of Life in JavaScript but I'm not seeing the same patterns such as Gosper's Glider Gun. I seed the grid the ways it's depicted in the Wikipedia article but, the gun never happens.
Will someone look at my code and see if there's anything wrong with it, any suggestions to the implementation?
https://github.com/DiegoSalazar/ConwaysGameOfLife
You are not updating all of the cells simultaneously, rather sequentially. A cell that is born in the first generation will not appear alive to the calculation of other cells of the first generation (it still counts as dead).
Create a new property called willBeAlive and use that to hold the cell's new calculated alive state. Once all the calculations for that generation are done, set each cell's alive property to its willBeAlive property and redraw.
Here are the changes:
Automaton.prototype.update = function() {
for (var x = 0; x < this.w; x++) {
for (var y = 0; y < this.h; y++) {
this.grid[x][y].killYourselfMaybe();
}
}
// set the alive property to willBeAlive
for (var x = 0; x < this.w; x++) {
for (var y = 0; y < this.h; y++) {
this.grid[x][y].alive = this.grid[x][y].willBeAlive;
}
}
}
Cell.prototype.killYourselfMaybe = function(grid) {
var num = this.numLiveNeighbors();
this.willBeAlive = false;
if (this.alive) {
// 1. Any live cell with fewer than two live neighbours dies, as if caused by under-population.
if (num < 2) this.willBeAlive = false;
// 2. Any live cell with two or three live neighbours lives on to the next generation.
if (num == 2 || num == 3) { this.willBeAlive = true}
// 3. Any live cell with more than three live neighbours dies, as if by overcrowding.
if (num > 3) this.willBeAlive = false;
} else {
// 4. Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.
if (num == 3) this.willBeAlive = true;
}
}
and here is a seed array for "Gosper's Glider Gun":
[[2,6],[2,7],[3,6],[3,7],[12,6],[12,7],[12,8],[13,5],[13,9],[14,4],[14,10],[15,4],[15,10],[16,7],[17,5],[17,9],[18,6],[18,7],[18,8],[19,7],[22,4],[22,5],[22,6],[23,4],[23,5],[23,6],[24,3],[24,7],[26,2],[26,3],[26,7],[26,8],[36,4],[36,5],[37,4],[37,5]]

Categories

Resources