Pull to refresh
0
Spice IT Recruitment
ИТ-специализированное кадровое агентство

Выпуск#20: ITренировка — актуальные вопросы и задачи от ведущих компаний

Reading time4 min
Views8.3K
Продолжаем публиковать интересные задачи и вопросы с собеседований в различные IT-компании мира.

КДПВ
На этот раз в подборку попали вопросы для будущих инженеров-программистов в Symantec. В преддверии майский праздников, задачи выбраны не самые сложные, но требующие некоторого размышления. Просим также писать в комментариях интересные вопросы и задачи, которые встречались Вам на собеседованиях.

Вопросы


  1. Counterfeit сoins
    A box contains n coins, of which 7 of them are counterfeit with tails on both sides and the rest are fair coins. If one coin is selected from the bag and tossed, the probability of getting a tail is 17/20. Find the value of ‘n’.

    Перевод
    В коробке n монет, 7 из которых поддельные — с решкой на обеих сторонах, а остальные монеты — правильные. Если выбрать и подбросить монету из коробки — шанс выпадения решки 17/20. Найдите n.

  2. The largest unavailable number
    At McDonald’s you can order Chicken McNuggets in boxes of 6,9, and 20. What is the largest number of nuggets that you cannot order using any combination of the above?

    Перевод
    В Макдональдс Вы можете заказать куриные наггетсы в коробке на 6, 9 и 20 шт. Каким является максимальное число наггетсов, которое нельзя заказать любыми комбинациями этих коробок,
    Прим. Нет, рекламу нам не оплачивали :)


Задачи


  1. Find all combinations
    Given a set of characters and a positive integer k, print all possible strings of length from 1 to k that can be formed from the given set.

    Examples:

    Input:
    set[] = {'a', 'b'}, k = 3

    Output:
    a
    b
    aa
    ab
    ba
    bb
    aaa
    aab
    aba
    abb
    baa
    bab
    bba
    bbb

    Input:
    set[] = {'a', 'b', 'c', 'd'}, k = 1
    Output:
    a
    b
    c
    d

    Перевод
    Дан набор символов и положительное число k. Выведите все возможные строковые комбинации длиной от 1 до k, которые можно получить из этого набора.

    Примеры:

    Вход:
    set[] = {'a', 'b'}, k = 3

    Выход:
    a
    b
    aa
    ab
    ba
    bb
    aaa
    aab
    aba
    abb
    baa
    bab
    bba
    bbb

    Вход:
    set[] = {'a', 'b', 'c', 'd'}, k = 1
    Выход:
    a
    b
    c
    d

  2. Delete a node in a single-linked list
    Given a pointer to a node to be deleted in a singly linked list, delete the node. Note that we don’t have pointer to head node. Write a program to accomplish the task, pseudocode is accepted.

    Перевод
    Дан указатель на элемент односвязного списка, необходимо удалить этот элемент. Обратите внимание, что указатель на головной элемент не даётся. Напишите программу, выполняющую поставленную задачу, псевдокод приемлем.

  3. Comment remover
    Write a program to remove comments from given C/C++ code.

    Перевод
    Напишите программу, удаляющую комментарии из С/C++ кода.

Ответы будут даны в течение следующей недели — успейте решить. Удачи!

Решения


  1. Вопрос 1
    Верный ответ — 10, что было быстро вычислено.

  2. Вопрос 2
    43. Правильный ответ был дан в первом же комментарии и объяснен в обсуждении в этой ветке.

  3. Задача 1
    Вариант решения:
    // C# program to print all 
    // possible strings of length k
    using System;
     
    class GFG {
         
    // The method that prints all 
    // possible strings of length k.
    // It is mainly a wrapper over 
    // recursive function printAllKLengthRec()
    static void printAllKLength(char[] set, int k)
    {
        int n = set.Length; 
        for (int j=0; j<=k; j++) {
        printAllKLengthRec(set, "", n, j);
        }
    }
     
    // The main recursive method
    // to print all possible 
    // strings of length k
    static void printAllKLengthRec(char[] set, 
                                   String prefix, 
                                   int n, int k)
    {
         
        // Base case: k is 0,
        // print prefix
        if (k == 0) 
        {
            Console.WriteLine(prefix);
            return;
        }
     
        // One by one add all characters 
        // from set and recursively 
        // call for k equals to k-1
        for (int i = 0; i < n; ++i)
        {
     
            // Next character of input added
            String newPrefix = prefix + set[i]; 
             
            // k is decreased, because 
            // we have added a new character
            printAllKLengthRec(set, newPrefix, 
                                    n, k - 1); 
        }
    }
     
    // Driver Code
    static public void Main ()
    {
        Console.WriteLine("First Test");
        char[] set1 = {'a', 'b'};
        int k = 3;
        printAllKLength(set1, k);
         
        Console.WriteLine("\nSecond Test");
        char[] set2 = {'a', 'b', 'c', 'd'};
        k = 1;
        printAllKLength(set2, k); 
    }
    }
    


  4. Задача 2
    Правильный подход к решению предложил Andy_U в этом комментарии. Код:
    #include<stdio.h>
    #include<assert.h>
    #include<stdlib.h>
     
    /* Link list node */
    struct Node
    {
        int data;
        struct Node* next;
    };
     
    /* Given a reference (pointer to pointer) to the head
        of a list and an int, push a new node on the front
        of the list. */
    void push(struct Node** head_ref, int new_data)
    {
       /* allocate node */
       struct Node* new_node =
                 (struct Node*) malloc(sizeof(struct Node));
     
       /* put in the data  */
       new_node->data  = new_data;
     
       /* link the old list off the new node */
       new_node->next = (*head_ref);
     
       /* move the head to point to the new node */
       (*head_ref)    = new_node;
    }
     
    void printList(struct Node *head)
    {
       struct Node *temp = head;
       while(temp != NULL)
       {
          printf("%d  ", temp->data);
          temp = temp->next;
       }
    }
     
    void deleteNode(struct Node *node_ptr)   
    {
       struct Node *temp = node_ptr->next;
       node_ptr->data    = temp->data;
       node_ptr->next    = temp->next;
       free(temp);
    }
     
    /* Drier program to test above function*/
    int main()
    {
        /* Start with the empty list */
        struct Node* head = NULL;
     
        /* Use push() to construct below list
        1->12->1->4->1  */
        push(&head, 1);
        push(&head, 4);
        push(&head, 1);
        push(&head, 12);
        push(&head, 1);
     
        printf("Before deleting \n");
        printList(head);
     
        /* I m deleting the head itself.
            You can check for more cases */
        deleteNode(head);
     
        printf("\nAfter deleting \n");
        printList(head);
        getchar(); 
        return 0;
    }
    


  5. Задача 3
    Вариант решения:
    // C++ program to remove comments from a C/C++ program
    #include <iostream>
    using namespace std;
     
    string removeComments(string prgm)
    {
        int n = prgm.length();
        string res;
     
        // Flags to indicate that single line and multpile line comments
        // have started or not.
        bool s_cmt = false;
        bool m_cmt = false;
     
     
        // Traverse the given program
        for (int i=0; i<n; i++)
        {
            // If single line comment flag is on, then check for end of it
            if (s_cmt == true && prgm[i] == '\n')
                s_cmt = false;
     
            // If multiple line comment is on, then check for end of it
            else if  (m_cmt == true && prgm[i] == '*' && prgm[i+1] == '/')
                m_cmt = false,  i++;
     
            // If this character is in a comment, ignore it
            else if (s_cmt || m_cmt)
                continue;
     
            // Check for beginning of comments and set the approproate flags
            else if (prgm[i] == '/' && prgm[i+1] == '/')
                s_cmt = true, i++;
            else if (prgm[i] == '/' && prgm[i+1] == '*')
                m_cmt = true,  i++;
     
            // If current character is a non-comment character, append it to res
            else  res += prgm[i];
        }
        return res;
    }
     
    // Driver program to test above functions
    int main()
    {
        string prgm = "   /* Test program */ \n"
                      "   int main()  \n"
                      "   {           \n"
                      "      // variable declaration \n"
                      "      int a, b, c;    \n"
                      "      /* This is a test  \n"
                      "          multiline     \n"
                      "          comment for   \n"
                      "          testing */      \n"
                      "      a = b + c;       \n"
                      "   }           \n";
        cout << "Given Program \n";
        cout << prgm << endl;
        cout << " Modified Program ";
        cout << removeComments(prgm);
        return 0;
    }
    


Tags:
Hubs:
+6
Comments26

Articles

Change theme settings

Information

Website
www.spiceit.ru
Registered
Founded
2009
Employees
31–50 employees
Location
Россия