Project Euler number 8 - javascript

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.

Related

Infinite "for" loop [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I'm writing code on Javascript for a project breakout game, and right now I'm adding the bricks. Somehow, I've created myself an infinite loop. I know that this is the correct code to at least put the bricks on the screen, but the code simply won't run on my computer, it just breaks. Could someone determine where the infinite loop is created? Thanks!
//Brick Constants
var NUM_ROWS = 8;
var BRICK_TOP_OFFSET = 10;
var BRICK_SPACING = 2;
var NUM_BRICKS_PER_ROW = 10;
var BRICK_HEIGHT = 10;
var SPACE_FOR_BRICKS = getWidth() - (NUM_BRICKS_PER_ROW + 1) * BRICK_SPACING;
var BRICK_WIDTH = SPACE_FOR_BRICKS / NUM_BRICKS_PER_ROW;
//Paddle Constants
var PADDLE_WIDTH = 80;
var PADDLE_HEIGHT = 15;
var PADDLE_OFFSET = 10;
//Ball Constants
var BALL_RADIUS = 15;
var brick;
function start(){
addBricks();
}
function addBricks(){
var brickSepY = BRICK_TOP_OFFSET;
for(var i = 0 ; i < NUM_ROWS ; i++){
var brickSepX = BRICK_SPACING;
for(var j = 0 ; j < NUM_BRICKS_PER_ROW ; i++){
brick = new Rectangle(BRICK_WIDTH, BRICK_HEIGHT);
brick.setPosition(brickSepX, brickSepY);
add(brick);
}
}
}
Change:
for(var j = 0 ; j < NUM_BRICKS_PER_ROW ; i++)
// here ^^^
to:
for(var j = 0 ; j < NUM_BRICKS_PER_ROW ; j++)
// here ^^^
You are increasing the I of the first for change for j
function addBricks(){
var brickSepY = BRICK_TOP_OFFSET;
for(var i = 0 ; i < NUM_ROWS ; i++){
var brickSepX = BRICK_SPACING;
for(var j = 0 ; j < NUM_BRICKS_PER_ROW ; **i++**){
brick = new Rectangle(BRICK_WIDTH, BRICK_HEIGHT);
brick.setPosition(brickSepX, brickSepY);
add(brick);
}
}
}

Learning for loops in 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.

Javascript syntax issue in code

Can someone tell me why this bit of JavaScript is buggy?
I have HTML also, but I don't want to make this a massive code dump.
<script type = 'text/javascript'>
var playerCards = [];
var dealerCards = [];
function deal() {
var newCard = Math.random() % 12;
var newCard2 = Math.random() % 12;
playerCards += newCard;
playerCards += newCard2;
var counter = 0;
for (var i = 0; i < playerCards.length; ++i) {
counter += i;
}
document.getElementById("playerTotal").innerHTML = counter;
var dCounter = 0;
for (var j = 0; j < playerCards.length; ++j) {
dCounter += j;
}
document.getElementById("dealerTotal").innerHTML = dCounter;
}
</script>
I'm gonna assume this is a silly syntax error someplace, but I can't find it.
I'm guessing that this isn't doing what you expect it to:
playerCards += newCard;
playerCards += newCard2;
Try this instead:
playerCards.push(newCard);
playerCards.push(newCard2);
The first snippet is trying to "add" a number to an array, which doesn't exactly make sense. Through some arcane JavaScript rules, this turns the result into a string.
I'm guessing that you want to concatenate to an array instead.
Math.random returns a number between 0 and 1 - so Math.random() % 12 will probably be zero
var playerCards = [];
playerCards += newCard; //
what are you even trying to do there?
var counter = 0;
for (var i = 0; i < playerCards.length; ++i) {
counter += i;
}
if playerCards had a length, this loop would result in counter having value of 0, 1, 3, 6, 10 .. n(n+1) / 2 - probably not what you intended, but who knows

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 :)

Looping through and updating the values in a select list

I'm trying to update the options of ALL select lists on a page and implemented a solution found on Get list of all `input` objects using JavaScript, without accessing a `form` object and other pages.
This works to an extent but only the select lists which occur AFTER the one which is triggering the javascript are updated whereas I need them ALL done, regardless of their position relative to the triggering select.
Here's a simplified version of what I have:
function chooseBon(id, value) {
var bonbonsAmount = 12;
var bonbonsCurrent = 0;
var bonbonsCount = 4;
var inputs, index;
// get all the select lists
inputs = document.getElementsByTagName('select');
// loop through all the lists
for (index = 0; index < inputs.length; ++index) {
// First disable all options
for (j = 0; j<=bonbonsAmount; ++j) {
inputs[index].options[j].disabled="disabled";
}
// Then re-enable the ones we still need
for (j = 0; j<=(bonbonsAmount - bonbonsCurrent); ++j) {
inputs[index].options[j].disabled="";
}
// add up the no of chocs selected so we know how many options to re-enabled above
bonbonsCurrent += inputs[index].selectedIndex;
}
I'm an admitted newbie and am adapting a script from one ecommerce platform for another so am hamstrung in certain areas so feel free to make other suggestions.
here is one of possible solutions and the fiddle:
function chooseBon() {
var bonbonsAmount = 12;
var bonbonsCurrent = 0;
var bonbonsRemaining; //max. is bonbonsAmount
var inputs, i, j;
inputs = document.getElementsByTagName('select');
for (i = 0; i < inputs.length; i++) {
bonbonsCurrent += parseInt(inputs[i].value, 10);
}
bonbonsRemaining = bonbonsAmount - bonbonsCurrent;
for (i = 0; i < inputs.length; i++) {
for (j = 0; j <= bonbonsAmount; j++) {
inputs[i].options[j].disabled = (j < bonbonsRemaining + parseInt(inputs[i].value, 10) + 1) ? false : true;
}
}
}

Categories

Resources