Maximum number of characters using keystrokes A, Ctrl+A, Ctrl+C and Ctrl+V

前端 未结 14 1518
忘掉有多难
忘掉有多难 2020-12-07 07:03

This is an interview question from google. I am not able to solve it by myself. Can somebody shed some light?

Write a program to print the sequence of keystrokes suc

14条回答
  •  余生分开走
    2020-12-07 07:15

    It takes 3 keystrokes to double your number of As. It only makes sense to start doubling when you have 3 or more As already printed. You want your last allowed keystroke to be a CtrlV to make sure you are doubling the biggest number you can, so in order to align it we will fill in any extra keystrokes after the first three As at the beginning with more As.

    for (i = 3 + n%3; i>0 && n>0; n--, i--) {
        print("a");
    }
    
    for (; n>0; n = n-3) {
        print("ctrl-a");
        print("ctrl-c");
        print("ctrl-v");
    }
    

    Edit:

    This is terrible, I completely got ahead of myself and didn't consider multiple pastes for each copy.

    Edit 2:

    I believe pasting 3 times is optimal, when you have enough keystrokes to do it. In 5 keystrokes you multiply your number of As by 4. This is better than multiplying by 3 using 4 keystrokes and better than multiplying by 5 using 6 keystrokes. I compared this by giving each method the same number of keystrokes, enough so they each would finish a cycle at the same time (60), letting the 3-multiplier do 15 cycles, the 4-multiplier do 12 cycles, and the 5-multiplier do 10 cycles. 3^15 = 14,348,907, 4^12=16,777,216, and 5^10=9,765,625. If there are only 4 keystrokes left, doing a 3-multiplier is better than pasting 4 more times, essentially making the previous 4 multiplier become an 8-multiplier. If there are only 3 keystrokes left, a 2-multiplier is best.

提交回复
热议问题