2 Key keyboard problem in JavaScript

JavascriptWeb DevelopmentFront End Technology

Suppose the following situation −

Initially on a notepad only one character 'A' is present. We can perform two operations on this notepad for each step −


  • Copy All − We can copy all the characters present on the notepad (partial copy is not allowed).

  • Paste − We can paste the characters which were copied last time.

We are required to write a JavaScript function that takes in a number, let's call it num as the only argument. Our function is required to compute and return the minimum number of steps (copy all or paste) required to print 'A' num times.

For example −

If the input number is −

const num = 3;

Then the output should be −

const output = 3;

because, the steps are −

  • copy all (result: 'A')

  • paste all (result: 'AA')

  • paste all (result: 'AAA')

Example

The code for this will be −

 Live Demo

const num = 3;
const minimumSteps = (num = 1) => {
   let [curr, copy, steps] = [1, 0, 0];
   while(curr != num){
      if((copy < curr) && ((num - curr) % curr) == 0) {
         copy = curr;
      }else{
         curr += copy;
      };
      steps += 1;
   };
   return steps;
};
console.log(minimumSteps(num));

Output

And the output in the console will be −

3
raja
Published on 24-Feb-2021 06:09:30
Advertisements