0

Each string in an array is a number, for example array1 = ["1296", "12", "27"];

For each string above, if possible to divide by 6 evenly without remainders, I want to do so at least once, then if the result is still longer than 2 characters, repeat. Then replace the string in the same position, such that the array would become ["36", "2", "27"];

so far, my code partly works.

w=0;
function divideBySix(){
            if ((array1[w] / 6) == (Math.floor(array1[w] / 6))) {
            var temp = array1[w] / 6;
            array1[w] = temp.toString();
            if (array1[w].length < 3) {
                w++;
            }
            divideBySix();
    }

The function successfully divides the first string by 6 once, and then calls itself again and again until the result is within 2 chars long. At that point, it should continue calling itself, and do the same to the next string of the array. But it doesn't do the next string. I don't know why it stops after finishing the first string. So the array looks like this ["36", "12", "27"]; Also, w successfully gets incremented. So I know its getting at least that far...

monkey blot
  • 985
  • 3
  • 10
  • 18

3 Answers3

1

i think you could just go with the modulo operator, if this is what you wanted to achieve

if(array1[w] % 6 == 0) doSomething()

and to solve your current problem you could introduce a second function ; for me it works with :

 function divideBySix(array){
     for(var i = 0; i < array.length; i++){
       array[i] = divideNumber(array[i], 0); 
     }           
}

function divideNumber(nr, ct){
    if((ct < 1 || nr > 99) && nr%6 == 0 ) return divideNumber(nr/6, ct+1);
    else return nr;            
}

var array1 = ["1296", "12", "27"];  

divideBySix(array1);

alert(array1);

  • That didn't solve this particular issue, but it does make my code a little more elegant. Thanks for noticing that! – monkey blot Mar 28 '12 at 17:27
  • @monkeyblot played around a bit, don'T know if u allready solved ur problem, but if i had to solve it i would have done it that way: (edited myanswer ;) – blackBox solutions Mar 29 '12 at 18:02
1

The function you give has unbalanced { }. When I add one at the end and run it, I get the result you say you want — ["36", "2", "27"]. There must be something else wrong, or you have not copied the code correctly.

In order to understand the operation, I added this to the beginning of divideBySix:

console.log(w, array1.toString());
Kevin Reid
  • 37,492
  • 13
  • 80
  • 108
0

When I test the code, that's what it does:

http://jsfiddle.net/Guffa/x4fNP/

Guffa
  • 687,336
  • 108
  • 737
  • 1,005