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

前端 未结 14 1512
忘掉有多难
忘掉有多难 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:21

    Using CtrlA + CtrlC + CtrlV is an advantage only after 4 'A's.

    So I would do something like this (in pseudo-BASIC-code, since you haven't specified any proper language):

    // We should not use the clipboard for the first four A's:
    FOR I IN 1 TO MIN(N, 4)
        PRINT 'CLICK A'
    NEXT
    LET N1 = N - 4
    
    // Generates the maximum number of pastes allowed:
    FOR I IN 1 TO (N1 DIV 3) DO
        PRINT 'CTRL-A'
        PRINT 'CTRL-C'
        PRINT 'CTRL-V'
        LET N1 = N1 - 3
    NEXT
    
    // If we still have same keystrokes left, let's use them with simple CTRL-Vs
    FOR I IN N1 TO N
        PRINT 'CTRL-V'
    NEXT
    

    Edit

    1. Back to using a single CtrlV in the main loop.
    2. Added some comments to explain what I'm trying to do here.
    3. Fixed an issue with the "first four A's" block.

提交回复
热议问题