Cassidoo Binary Queue Challenge
Given a positive number N, generate binary numbers between 1 to N using a queue-type structure in linear time.
by Jesse Rogers
JavaScript
// rendezvous with cassidoo issue #122 challenge: binary queue
// Given a positive number N, generate binary numbers between 1 to N
// using a queue-type structure in linear time
class BinaryQueue {
constructor() {
this.queue = [];
}
run(input) {
// convert input to number
input = +input;
// throw error and exit if input is not positive number
if (isNaN(+input) || +input < 1) {
const err = new Error(`Invalid input supplied to BinaryQueue print method`);
console.error(err);
throw err;
}
// return binary starting at 1, ending at input
let i = 1;
while (i <= input) {
// remove last entry from queue
this.queue.shift();
// add current entry to queue
this.queue.push(i);
this.print();
i++;
}
}
print() {
// convert to binary
const binary = this.queue[0].toString(2);
console.log(binary);
}
}
const bq = new BinaryQueue();
bq.run(10);