skip to Main Content

you need to make a counter like this:

0 0 0
0 0 1
0 1 0
0 1 1
1 0 0
1 0 1
1 1 1

how to implement this beautifully?

I haven’t figured out how to implement this.

2

Answers


    • Loop your counter with while(true) incrementing it.
    • Use Number.toString(2) to format the counter to the binary form where 2 is a number of bits per a character.
    • Use String.padStart(3, '0') to make strings 3 character long.
    • If the length > 3 break the cycle
    • Split the string and join with " " to add spaces between numbers.
    let count = 0;
    let result = '';
    
    while(true){
      const text = (count++).toString(2).padStart(3, '0');
      if(text.length > 3) break;
      result += text.split('').join(' ') + 'n';
    }
    
    $pre.textContent = result;
    <pre id="$pre"></pre>
    Login or Signup to reply.
  1. Binary addition is simple:

    • find the rightmost zero bit
    • set it to 1
    • set all bits right to it to 0
    a = Array(3).fill(0)
    
    while (1) {
        console.log(...a)
        let z = a.lastIndexOf(0)
        if (z < 0)
            break
        a[z] = 1
        a.fill(0, z + 1)
    }

    Homework: rewrite without builtins, using only fors and ifs.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search