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

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

    Here is my approach and solution with code below.

    Approach:

    There are three distinct operations that can be performed.

    1. Keystroke A - Outputs one character 'A'
    2. Keystroke (Ctrl-A) + (Ctrl-C) - Outputs nothing essentially. These two keystrokes can be combined into one operation because each of these keystrokes individually make no sense. Also, this keystroke sets up the output for the next paste operation.
    3. Keystroke (Ctrl-V) - Output for this keystroke really depends on the previous (second) operation and hence we would need to account for that in our code.

    Now given the three distinct operations and their respective outputs, we have to run through all the permutations of these operations.


    Assumption:

    Now, some version of this problem states that the sequence of keystrokes, Ctrl+A -> Ctrl+C -> Ctrl+V, overwrite the highlighted selection. To factor in this assumption, only one line of code needs to be added to the solution below where the printed variable in case 2 is set to 0

            case 2:
            //Ctrl-A and then Ctrl-C
                if((count+2) < maxKeys)
                {
                    pOutput = printed;
    
                    //comment the below statement to NOT factor 
                    //in the assumption described above
                    printed = 0;    
                }
    

    For this solution

    The code below will print a couple of sequences and the last sequence is the correct answer for any given N. e.g. for N=11 this will be the correct sequence

    With the assumption

    A, A, A, A, A, C, S, V, V, V, V, :20:

    Without the assumption

    A, A, A, C, S, V, V, C, S, V, V, :27:

    I have decided to retain the assumption for this solution.


    Keystroke Legend:

    'A' - A

    'C' - Ctrl+A

    'S' - Ctrl+C

    'V' - Ctrl+V


    Code:

    #include 
    #include 
    #include 
    
    void maxAprinted(int count, int maxKeys, int op, int printed, int pOutput, int *maxPrinted, char *seqArray)
    {
        if(count > maxKeys)
            return;
    
        if(count == maxKeys)
        {
            if((*maxPrinted) < printed)
            {
                //new sequence found which is an improvement over last sequence
                (*maxPrinted) = printed;
    
                printf("\n");
                int i;
                for(i=0; i

提交回复
热议问题