Web Analytics Made Easy -
StatCounter Nested for loop help - CodingForum

Announcement

Collapse
No announcement yet.

Nested for loop help

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • Nested for loop help

    I've been stuck on this for a while. I used excel to visualize the final result, but I am just not understanding how to implement the "if case"
    to deduct 1 on the subsequent loops.

    Here is the question...

    It's Easter Sunday and it's showtime for the Easter Bunny. He has 100 baskets to fill. He goes through each basket and puts an egg in. Then he goes back to the beginning. He stops at every second basket and if the basket has an egg in it (all of them do, in this case), he takes the egg out. Otherwise he puts an egg in. Then he goes back to the beginning. He stops at every third basket, taking an egg out if there's an egg or putting an egg in if there isn't. He does this for every fourth basket, fifth basket, etc., all the way up to every hundredth basket. Once he's finished, which baskets have eggs in them? Write the code to solve this question.

    Here is my code so far.., step 1, no problem, subsequent loops... no success so far.

    Code:
    function easter(num){
    	var basket = {};
    	for(var i = 1; i <=num; i++){
    		for(var j = 1; j <= num; j++){
    			if(!basket[j]){
    				basket[j] = 1;
    			}else{
    				basket[j] += 1;
    			}
    			
    		}
    
    	}	
    		return basket;
    }
    I believe that on the inner loop a multiple of i * j, will specify which basket to deduct from. I have not been able to succeed so far with various attempts.

  • #2
    I don't think I'd use loops for adjusting the basket contents. Instead I use an array. When you're looking into every third basket it would be: array[3] = 1; take the egg, array[6] = 0; add an egg. Just remember array start at zero.

    Hope this helps you.
    Evolution - The non-random survival of random variants.
    Physics is actually atoms trying to understand themselves.

    Comment


    • #3
      I'm going to try it now, I suspected that I may not be getting correct object property access because my properties names are strings. Thanks

      Comment


      • #4
        A rather interesting problem easily solved with an array and one loop.

        Code:
        function easter(num){
        var baskets = Array.apply(null,Array(num)).map(function(){return 1});
        for (let i=2; i <= num; i++) {
           baskets.forEach(function(v,k,a) {if ((k+1)%i===0) a[k] = v?0:1;});
        } 
        return baskets;
        }
        For 100 baskets the end result is 10 baskets with eggs and 90 baskets without.

        In my code the a[k] = v?0:1 toggles the values to add/remove the eggs in the baskets to be processed. That is called a ternary expression and is equivalent to if (v) a[k] = 0; else a[k] = 1;
        Last edited by felgall; Sep 29, 2016, 05:50 PM. Reason: replaced map with more efficient forEach
        Stephen
        Learn Modern JavaScript - http://javascriptexample.net/
        Helping others to solve their computer problem at http://www.felgall.com/

        Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

        Comment


        • #5
          For each round you have to increase it's startposition and stepsize by 1.
          Code:
          function easter(num) {
           var baskets = new Array(num);
          
           for(var i=0, j=1; j<=baskets.length; j++){
            for(i=j-1; i<baskets.length; i+=j){
             baskets[i] = (baskets[i] == null || baskets[i] == 0 ? 1 : 0);
           console.log(i, j)
            }
           }
           return baskets
          };
          
          var baskets = easter(100);
          var filled =  baskets.reduce(function(ret, val, index){val && ret.push(index); return ret}, []);
          console.log(baskets, filled);

          Comment


          • #6
            Goos - your code would be slightly more efficient if you substituted num for baskets.length since that's the length you are setting the array to have anyway.

            I like the way you extract the list of positions that have an egg at the end (the part of the solution I didn't provide).

            You can do away with the comparison to null if you set all of the array entries to 1 at the start (which also does away with the need for the first iteration of the outer loop).

            Code:
            function easter(num){
            var baskets = Array.apply(null,Array(num)).map(function(){return 1});
            for(let i=1, j=2; j<=num; j++){
              for(i=j-1; i<num; i+=j){
               baskets[i] = baskets[i] ? 0 : 1;
              }
             }
            return baskets.reduce(function(ret, val, index){val && ret.push(index); return ret}, []);
            }
            
            var baskets = easter(100);
            console.log(baskets);
            Last edited by felgall; Sep 29, 2016, 06:35 PM.
            Stephen
            Learn Modern JavaScript - http://javascriptexample.net/
            Helping others to solve their computer problem at http://www.felgall.com/

            Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

            Comment


            • #7
              This is an updated version...
              Code:
              function easter(num){
              	var basket = [];
              	for(var i = 0; i < num; i++){
              		for(var j = 0; j < num; j++){
              				if(!basket[i]){
              					basket[i] = 1;
              				}else if(basket[i] && j%i !== 0){
              					basket[i] += 1;
              				}else if(j%i === 0){
              					basket[i] -= 1;
              				}
              			}
              		}
              	return basket;
              }
              easter(10);

              Comment


              • #8
                Maybe I am misunderstanding the problem statement. In my attempts, shouldn't the first basket have 100? Because after the first loop, we go to the beginning and remove an egg from every 2nd, 4th, 6th...etc.. basket ( the 2nd outer loop). We have 100 outer loops and for each outer loop we have 10 inner loops. That's why in my last attempt I have j % i as a condition. What is wrong with my thought process?

                Comment


                • #9
                  ...meant 100, i have been starting with a smaller number to physically see on paper what i should have.

                  Comment


                  • #10
                    The baskets either contain one egg or they are empty. No basket will ever contain more than one egg. For the baskets visited the state of the basket is toggled. If it had an egg it is now empty and if it was empty it now has an egg. You don't need to be adding and subtracting eggs, just toggle a 1 to a 0 or a 0 to a 1.

                    The inner loop should skip ahead to the next basket to be visited each time through - there is no need to even consider the ones that are not multiples of the number for the current iteration of the outer loop (unless you use a forEach in place of the inner loop in which case you then need an if statement to determine whether the basket is being visited or not - that's when you'd use % ).

                    The second visit to the baskets changes 50 values, the third visit changes 33 values, the 4th visit changes 25 values and so on until the 100th visit changes 1 value. Those are the number of times that the inner loop needs to run to make the changes.

                    For the first pass you can either check for whether the entry in the array has a value at all (as Goos did with the null test) or you can simply create the array with an egg in every basket representing the end of the fist pass.
                    Stephen
                    Learn Modern JavaScript - http://javascriptexample.net/
                    Helping others to solve their computer problem at http://www.felgall.com/

                    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

                    Comment


                    • #11
                      I made the most basic mistake ever, just not understanding the problem.

                      Comment

                      Working...
                      X