Learning for loops in JavaScript - javascript

I'm looking for feedback/insight on using console.log instead of document.write to solve the looping triangle with a space in the CS50 Mario style problem.
Triangle loop - CS50 mario style
var str = "#";
var height = 8;
for (var i = 0; i < height; i++) {
for (var j = 0; j < height-i-1; j++) {
document.write("_");
}
{
for (var k = 0; k < i + 2; k++) {
document.write(str);
}
document.write("<br />");
}
}
//
_______##
______###
_____####
____#####
___######
__#######
_########
#########
The document.write(“_”) is because the DOM trims any white space so (“ “) won't work - took me ages to figure that out.
I can’t get the triangle to come out right aligned using console.log() instead of document.write - any thoughts?
Cheers - I'm a huge SOF fan for learning.

The reason console.log is not working for you is because console.log auto changes lines. So if you want to use console.log version, switch to the below version:
var str = "#";
var height = 8;
for (var i = 0; i < height; i++)
{
var line = "";
for (var j = 0; j < height-i-1; j++) {
line += " ";
}
for (var k = 0; k < i + 2; k++) {
line += str;
}
console.log(line);
}
Tested working with node.

Related

Why all my loops don`t work?

http://jsfiddle.net/VaAlina/oupmd0hf/
Commented code don`t work.
Area next to bomb is green. Yellow - bombs. Blue - emptiness .
I want to replace this kind of code->
var dangerItem1 = "#" + danger1;//Replace thise code to commented
var dangerItem2 = "#" + danger2;
var dangerItem3 = "#" + danger3;
var dangerItem4 = "#" + danger4;
With this->
/*
for(var j = 0; j < 4; j++){
var dangerItem+j = "#" + danger+j;
}
*/
Where is the mistake?
You can't dynamically create a variable name.
What you could do though is store them in arrays or objects.
Objects can accept dynamic property names using [] notation.
var danger =['green','red','blue','pink'];
var dangerItem = [];
for(var j = 0; j < 4; j++){
dangerItem.push( "#" + danger[j]);
}
// returns ["#green", "#red", "#blue", "#pink"]
/* or */
var dangerItem = {};
for(var j = 0; j < 4; j++){
dangerItem[ danger[j] ] = "#" + danger[j];
}
// returns {"green":"#green","red":"#red","blue":"#blue","pink":"#pink"}

Project Euler number 8

They asked me to learn JavaScript for work, so I'm doing some of the solutions on Project Euler to help me learn.
My solution for problem 8 works for the 4 number example they give, if I change the 13s to 4s, but it doesn't get the right answer for 13 digits as the question wants.
I solved this problem forever ago in C and don't remember it giving me this much trouble. Am I doing something wrong with JavaScript or is this a error with my code? In either case, please point me in the right direction.
My code:
var numbas = "\
73167176531330624919225119674426574742355349194934\
96983520312774506326239578318016984801869478851843\
85861560789112949495459501737958331952853208805511\
12540698747158523863050715693290963295227443043557\
66896648950445244523161731856403098711121722383113\
62229893423380308135336276614282806444486645238749\
30358907296290491560440772390713810515859307960866\
70172427121883998797908792274921901699720888093776\
65727333001053367881220235421809751254540594752243\
52584907711670556013604839586446706324415722155397\
53697817977846174064955149290862569321978468622482\
83972241375657056057490261407972968652414535100474\
82166370484403199890008895243450658541227588666881\
16427171479924442928230863465674813919123162824586\
17866458359124566529476545682848912883142607690042\
24219022671055626321111109370544217506941658960408\
07198403850962455444362981230987879927244284909188\
84580156166097919133875499200524063689912560717606\
05886116467109405077541002256983155200055935729725\
71636269561882670428252483600823257530420752963450";
var biggestProduct = 0;
var currentProduct = 0;
var currentNumbas = {};
function product (proddedNumbas){
var productHolda = 1;
for (var i = 0; i < 13; i++)
productHolda *= proddedNumbas[i];
return productHolda;
}
for (var j = 0; j < 1000; j++)
for (var i = 0; i < 13; i++){
currentNumbas[i] = numbas[j+i];
currentProduct = product(currentNumbas);
if (currentProduct > biggestProduct)
biggestProduct = currentProduct;
}
console.log(biggestProduct);
Your loop should be
for (var j = 0; j < 1000; j++) {
for (var i = 0; i < 13; i++) {
currentNumbas[i] = numbas[j+i];
currentProduct = product(currentNumbas);
}
if (currentProduct > biggestProduct)
biggestProduct = currentProduct;
}
You just needed to move the if clause outside of the inner loop; this compares the product after it is complete.
This gives the expected answer 23514624000.

Javascript WW2 Flag Stars

I'm having trouble and have been stuck on this program for a while. Basically I need to use for loops in order to make the stars in a flag on the webpage. The order is 48 stars going 8 across and 6 down. My pseudocode is
class WW2Flag
main()
//Declarations//
str j
str x
for j = 1 to 6
for x = 1 to 8 step 1
output "x "
endfor
output break
endClass
My program that I have currently is
var row = "&#10029";
var x = 48;
for (x=0;x<8;x+1){
document.getElementById("stars").innerHTML += row;
if (x==8){
break;
document.write("&#10029");
}
else {
j = 0;j<6;j + 1;
document.write("&#10029");
}
x++;
}
You just need to nest your column loop within your row loop, like this.
var stars = [], star = '&#10029';
for (var i=0; i<6; i++) {
for (var j=0; j<8; j++) {
stars.push(star);
}
stars.push('<br />\n');
}
document.getElementById('stars').innerHTML = stars.join('');
<div id="stars"></div>

Filling up a 2D array with random numbers in javascript

I'm really sorry if anything like this has been posted here before but I couldn't find anything, I'm kinda new to the site still!
So for a while now I've been learning a bit about game development through html5 and javascript and I stumbled upon making tileset maps, I now have a tileset and an 2D array that I want to put certain tiles in (the number varies between 6 and 10 in this case).
I figured it could be a cool function to make the map choose between a small set of similar tiles so I don't have to specifically number every tile in the array(just define the type)
The method I have currently is probably the best for being able to define types but I want something that looks a bit cleaner and/or information to why my "cleaner" version dosen't work.
var ground = [
[tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile()],
[tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile()],
[tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile()],
[tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile()],
[tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile()],
[tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile()],
[tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile()],
[tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile()],
[tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile()]];
function tile() {
var y = (Math.random() * 5 | 0) + 6;
return y;
}
This is the code I've been using so far, I have to edit every element of the code with the tile() function to get a random number in each one, what I wanted to have was something like this:
for (var i = 0 ; i < 15; i++) {
for (var j = 0; j < 9; j++) {
ground[[i],[j]] = (Math.random() * 5 | 0) + 6;
}
}
to fill the array without having to add the function to each spot.
I have a feeling that I'm missing a return function or something along those lines but honestly I have no idea.
You were thinking in the right direction but there are some errors in your code ;)
You have to initialize the array first before you can push elements into it.
And you were counting i++ twice
Javascript
var ground = []; // Initialize array
for (var i = 0 ; i < 15; i++) {
ground[i] = []; // Initialize inner array
for (var j = 0; j < 9; j++) { // i++ needs to be j++
ground[i][j] = (Math.random() * 5 | 0) + 6;
}
}
Maybe even better (reusable)
function createGround(width, height){
var result = [];
for (var i = 0 ; i < width; i++) {
result[i] = [];
for (var j = 0; j < height; j++) {
result[i][j] = (Math.random() * 5 | 0) + 6;
}
}
return result;
}
// Create a new ground with width = 15 & height = 9
var ground = createGround(15, 9);
Here's a quick example. I've created a function that will take in a width and height parameter and generate the size requested. Also I placed your tile function inside generate ground to keep it private, preventing other script from invoking it.
var ground = generateGround(10, 10); //Simple usage
function generateGround(height, width)
{
var ground = [];
for (var y = 0 ; y < height; y++)
{
ground[y] = [];
for (var x = 0; x < width; x++)
{
ground[y][x] = tile();
}
}
return ground;
function tile()
{
return (Math.random() * 5 | 0) + 6;
}
}
http://jsbin.com/sukoyute/1/edit
Try removing the comma from...
ground[[i],[j]] = (Math.random() * 5 | 0) + 6;
...in your 'clean' version. Also, your incrementing 'i' in both for loops:
for (var i = 0 ; i < 15; i++) {
for (var j = 0; j < 9; i++) {
Hopefully these changes make it work for you :)

I am trying to set bottom of element but its value is coming up NaN

function CheckavailOnload()
{
var elems = document.getElementsByClassName('box-collateral box-related');
var av = document.getElementsByClassName('availability in-stock');
var x;
for (var i = 0; i < elems.length; i++)
{
if (getComputedStyle(elems[i]).visibility == 'visible')
{
for (var j = 0; j < av.length; j++)
{
av[j].style.visibility = 'visible';
if(elems[i].offsetTop < 0)
{
var x = (elems[i].offsetHeight + (elems[i]).offsetTop).toString() + "px";
alert(x);
}
for(m = 0;m < av.length; m++)
{
av[m].style.Bottom = (-x);
return;
}
}
}
}
for (var k = 0; k < av.length; k++)
{
av[k].style.visibility = 'hidden';
}
var divs = document.getElementsByClassName('add-to-cart');
for(var l = 0; l < divs.length; l++)
{
divs[l].style.marginTop = (-500).toString() + "px";
divs[l].style.marginLeft = (-20).toString() + "px";
}
}
window.onload = CheckavailOnload;
here i am trying to move a paragraph tag have baground image depending upon the div offsetTop and Offset height div also have bacground image i am moving para tag just below the div but addition of offsetHeight and offsetTop is coming NAN please anyone can help me
You've declared var x; at the beginning of your script. Then later you're checking:
if(elems[i].offsetTop < 0) {
var x = (elems[i]...); // var is not recommended to be here, x has been already declared once
}
If elems[i].offsetTop happens to be >= 0, x will be undefined in this line:
av[m].style.Bottom = (-x); // Notice a typo here: should be av[m].style.bottom
This last expression gives you NaN. To avoid this, you need to either assign a default value to x in the beginning of the script, or add an else statement after the if wherein some numeric value is assigned to x.
Also return in the for...m-loop seems to break your code, the loop will never finish the job and the rest of the code will be never executed.
Using (-500).toString() + "px"; feels complex, why not just use "-500px";?

Categories

Resources