
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
2 Key keyboard problem in JavaScript
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 −
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
- Related Articles
- Meeting Rooms 2 problem in JavaScript
- Lock & Key problem using Hash-map
- 2 Keys Keyboard in C++
- How to hide the keyboard in Swift by pressing the return key?
- Snail Trail Problem in JavaScript
- Recursive Staircase problem in JavaScript
- Distributing Bananas Problem in JavaScript
- Recursion problem Snail Trail in JavaScript
- Expressive words problem case in JavaScript
- Crack Alphabets fight problem in JavaScript
- 2-Satisfiability(2-SAT) Problem in C/C++?
- The algorithm problem - Backtracing pattern in JavaScript
- Combination sum problem using JavaScript
- Two sum problem in linear time in JavaScript
- Explain Key-events in JavaScript?
