Saturday, December 29, 2012

Решение на задачите от Първия практически изпит по C# -2012 ( 29.12.2012)


Problem 1 – Triple Rotation of Digits

In Kaspichan we drink a lot. One evening we drunk enough so we invited an interesting game: Someone says a number. The first person after him rotates the digits of this number by moving its last digit at its start (e.g. 12345 -> 51234). The second person after that again rotates the number (e.g. 51234 -> 45123). Finally the third person after him also rotates the number (e.g. 45123 -> 34512). The obtained number then is sent by SMS to a fellow group of alcoholics who continue the game at their drink place.

Write a program that helps the Kaspichan drinkers to calculate the triple digits rotation of given number K. Note that zeroes could also take part in the play and the leading digits are lost after each rotation, e.g. the triple rotation of 180001 is 1180 (180001 -> 118000 -> 011800 -> 11800 -> 01180 -> 1180).

Input


The input data should be read from the console and consists of a single line holding an integer number K.

The input data will always be valid and in the format described. There is no need to check it explicitly.

Output


The output data should be printed on the console.

The output should consist of a single line holding the number obtained after applying a triple digits rotation of the number K.


Constraints


  • The number K is in the range [1…999 999] inclusive.
  • Allowed work time for your program: 0.1 seconds. Allowed memory: 16 MB.

Examples

Input
Output

Input
Output

Input
Output

Input
Output
51234
23451

180001
1180

443
443
53
35

Solution:
using System;

class Problem01
{
    static void Main()
    {
        //variables
        int k = int.Parse(Console.ReadLine());
        string result = null;
        string number;

        //expressions
        number = k.ToString();
        result = number;
        for (int i = 1; i <= 3; i++)
        {
            char lastChar = result[result.Length - 1];
            string trimLastChar = result.Substring(0, result.Length - 1);
            if (lastChar == '0')
            {
                result = trimLastChar;
            }
            else
            {
                result = lastChar + trimLastChar;
            }

        }
        Console.WriteLine(result);
    }
}


Problem 2 – Quadronacci Rectangle


You all know the Fibonacci sequence. Well, the Quadronacci sequence is almost the same, but it uses the last four numbers (instead of the last two) to calculate the next number in the sequence. So, we can define each element in the sequence as:


Q n = Q n-1 + Q n-2 + Q n-3 + Q n-4

where Q n is the current Quadronacci number (n is the index of the current Quadronacci number).

The Quadronacci sequence can begin with any four integer numbers – positive or negative – and continue as described by the formula above.

Now, a Quadronacci rectangle is what you probably expect – a rectangle (matrix) of numbers from the Quadronacci sequence. So we can say that the rectangle's height is actually the number of rows and the rectangle's width is the numbers of columns of numbers.

If use R for the number of rows and C for the number of columns, then the first row in the rectangle contains the first C numbers from the sequence, the second row contains the next C numbers from the sequence and so on.

Your task is to write a program, which prints to the console a Quadronacci rectangle by given the first four numbers of the Quadronacci sequence, the number of rows and the number of columns in the rectangle.

Input


The input data should be read from the console.

The first four lines will contain the values of the first four numbers of the Quadronacci sequence – each number will be on a separate line.

On the fifth line there will be the number R – the number of rows of the Quadronacci rectangle.

On the sixth line there will be the number C – the number of columns of the Quadronacci rectangle.

The input data will always be valid and in the format described. There is no need to check it explicitly.

Output


The output data should be printed on the console.

The output should contain exactly R lines with exactly C numbers per line – representing each line of the Quadronacci rectangle. Numbers should be separated by exactly one whitespace (" "), and there shouldn't be any whitespaces after the last number on a line.

Constraints


  • 1 ≤ R ≤ 20.
  • 4 ≤ C ≤ 20.
  • Any number in the Quadronacci rectangle can be stored in a 64-bit signed integer.

·         Allowed working time for your program: 0.1 seconds.

·         Allowed memory: 16 MB.



Examples

Input example
Output example
1
2
3
4
2
8
1 2 3 4 10 19 36 69
134 258 497 958 1847 3560 6862 13227
5
-5
1
2
3
4
5 -5 1 2
3 1 7 13
24 45 89 171



Solution:
using System;

class Problem02
{
    static void Main()
    {
        //variables
        long number1 = long.Parse(Console.ReadLine());
        long number2 = long.Parse(Console.ReadLine());
        long number3 = long.Parse(Console.ReadLine());
        long number4 = long.Parse(Console.ReadLine());
        int rows = int.Parse(Console.ReadLine());
        int columns = int.Parse(Console.ReadLine());
        long nextNumber = 0;
        long[] array = new long[rows * columns+1];
        int index = 0;

        //expressions
        array[0] = number1;
        array[1] = number2;
        array[2] = number3;
        array[3] = number4;
        for (int i = 4; i <= rows * columns; i++)
        {
            nextNumber = number1 + number2 + number3 + number4;
            array[i] = nextNumber;
            number1 = number2;
            number2 = number3;
            number3 = number4;
            number4 = nextNumber;

        }
        for (int i = 1; i <= rows; i++)
        {
            for (int n = 0; n < columns; n++)
            {
                if (n == columns - 1)
                {
                    Console.Write(array[index]);
                }
                else
                {
                    Console.Write(array[index] + " ");
                }
                index++;
            }
            Console.WriteLine();
        }
    }
}

Problem 3 – Poker

Mitko is a famous poker player. But he is not a good developer. One day he found interesting 5-card poker game which is played by a deck of 52 cards. Nothing strange here, except that the cards have no suit (color). Mitko decided to start playing this game, but he needs a program to show him the best hand that he has. Write а program to help Mitko. The program should read the cards and check each of the following conditions and display one of the messages:
• If the five cards are equal, the program outputs “Impossible”, otherwise:
• if four of them are equal, the program
outputs “Four of a Kind”, otherwise:
• if there are three equal and the another two are also equal (example: ‘2’, ‘2’, ‘10’, ‘10’, ‘2’), the program outputs “Full House”, otherwise:
• if the five are consecutive (example: ‘2’, ‘3’, ‘4’, ‘5’, ‘6’), the program outputs “Straight”, otherwise:
• if three of them are equal, the program outputs “Three of a Kind”, otherwise:
• if two pairs contain respectively equal numbers (example ‘A’, ‘K’, ‘A’, ‘K’, ‘J’), the program outputs “Two Pairs”, otherwise:
• if only two cards are equal, the program outputs “One Pair”, otherwise;
• the program outputs “Nothing”.
Cards are given with one of the following strings ‘2’, ‘3’, ‘4’, ‘5’, ‘6’, ‘7’, ‘8’, ‘9’, ‘10’, ‘J’, ‘Q’, ‘K’ or ‘A’ (without the quotes). The combination of ‘10’, ‘J’, ‘Q’, ‘K’ and ‘A’ are considered as a consecutive cards. Note that ‘A’, ‘2’, ‘3’, ‘4’ and ‘5’ are also consecutive cards so your program should output “Straight” in this case.

Input

The input data should be read from the console.
You will be given exactly 5 lines with one card per line.
The input data will always be valid and in the format described. There is no need to check it explicitly.

Output

The output data should be printed on the console.
On the only output line, write an appropriate message with the exact letters case.

Constraints

- Allowed working time for your program: 0.1 seconds. Allowed memory: 16 MB.

Examples

Example
Input
Example
output
2
7
A
J
K
Nothing
Example
input
Example
output
4
2
A
3
5
Straight

Example
input
Example
output
8
J
J
8
8
Full House



 

 

 

 

 Solution:
using System;
using System.Collections.Generic;

class Problem03
{
    static void Main()
    {
        //variables
        List<int> hand = new List<int>();
        int equalCards = 1;
        int pair = 0;
        int threeOfKind = 0;
        int fourOfKind = 0;
        int consecutive = 1;
        int currentItem;
        for (int i = 0; i < 5; i++)
        {
            string card = Console.ReadLine();
            hand.Add(Cards(card));
        }

        //expressions
        //sort the cards
        hand.Sort();
        currentItem = hand[0];

        for (int i = 1; i <= hand.Count; i++)
        {
            if (i > hand.Count - 1)
            {
                if (equalCards == 2)
                {
                    pair++;
                }
                if (equalCards == 3)
                {
                    threeOfKind++;
                }
                if (equalCards == 4)
                {
                    fourOfKind++;
                }
                break;
            }
            if (hand[i] == currentItem)
            {
                equalCards++;
            }

            else
            {
                if (hand[i] == currentItem + 1)
                {
                    consecutive++;
                }
                if (equalCards == 2)
                {
                    pair++;
                    equalCards = 1;
                }
                if (equalCards == 3)
                {
                    threeOfKind++;
                    equalCards = 1;
                }
                if (equalCards == 4)
                {
                    fourOfKind++;
                    equalCards = 1;
                }

                currentItem = hand[i];
            }
        }


        if (consecutive == 5)
        {
            Console.WriteLine("Straight");
        }
        if (consecutive == 4 && currentItem == 13)
        {
            Console.WriteLine("Straight");
        }
        if (equalCards == 5)
        {
            Console.WriteLine("Impossible");
        }
        if (fourOfKind == 1)
        {
            Console.WriteLine("Four of a Kind");
        }

        if (threeOfKind == 1 && pair == 1)
        {
            Console.WriteLine("Full House");
        }
        if (threeOfKind == 1 && pair == 0)
        {
            Console.WriteLine("Three of a Kind");
        }
        if (pair == 2)
        {
            Console.WriteLine("Two Pairs");
        }
        if (pair == 1 && threeOfKind == 0)
        {
            Console.WriteLine("One Pair");
        }
        if (pair == 0 && threeOfKind == 0 && fourOfKind == 0 && consecutive < 4 && equalCards != 5)
        {
            Console.WriteLine("Nothing");
        }

        Console.WriteLine();
    }
    //put the card in List as int
    static int Cards(string card)
    {
        int result = 0;
        switch (card)
        {
            case "A":
                result = 1;
                break;
            case "2":
                result = 2;
                break;
            case "3":
                result = 3;
                break;
            case "4":
                result = 4;
                break;
            case "5":
                result = 5;
                break;
            case "6":
                result = 6;
                break;
            case "7":
                result = 7;
                break;
            case "8":
                result = 8;
                break;
            case "9":
                result = 9;
                break;
            case "10":
                result = 10;
                break;
            case "J":
                result = 11;
                break;
            case "Q":
                result = 12;
                break;
            case "K":
                result = 13;
                break;
        }
        return result;
    }
}



Problem 4 – UK Flag

Telerik Academy is considering opening a new office in Great Britain. Therefore the whole Trainers team is traveling to the United Kingdom for the important event. They’ve decided that everyone needs to bring the UK flag with him, as a token of respect to the local citizens. Please help them and print some flags in different sizes, so they will be well received. As a little reminder, here it is the flag itself:



 Input

The input data should be read from the console.
You have an integer number N (always odd number) showing the width and the height of the flag.  The flag will always be a square.
The input data will always be valid and in the format described. There is no need to check it explicitly.

Output

The output should be printed on the console.
Use the “*” (asterisk) character for the middle, the “\”, “/”, “|” (vertical dash), “-” (dash) characters for the lines and “.” (dot) for the rest.

Constraints

 - N will always be a positive odd number between 5 and 79 inclusive.
 - Allowed working time for your program: 0.1 seconds. Allowed memory: 16 MB.

Examples

Example
input
Example
output
5
\.|./
.\|/.
--*--
./|\.
/.|.\
Example input
Example output
9
\...|.../
.\..|../.
..\.|./..
...\|/...
----*----
.../|\...
../.|.\..
./..|..\.
/...|...\














Solution: 

using System;

class Problem04
{
    static void Main()
    {
        //variables
        int n = byte.Parse(Console.ReadLine());
        int middleDots = n / 2-1;

        //expressions
        Console.WriteLine(@"\" + new String('.', middleDots) + "|" + new String('.', middleDots) + "/");

        for (int i = 1; i < n/2; i++)
        {
            Console.WriteLine(new String('.', i) + @"\" + new String('.', middleDots-1)
                                + "|" + new String('.', middleDots-1) + "/" + new String('.', i));
            middleDots--;
        }

        Console.WriteLine(new String('-', n / 2) + "*" + new String('-', n / 2));

        middleDots = n / 2 - 1;
        for (int p = n / 2-1; p >= 0; p--)
        {
            Console.WriteLine(new String('.', p) + "/" + new String('.', middleDots - (n / 2 - 1))
                                + "|" + new String('.', middleDots - (n / 2 - 1)) + @"\" + new String('.', p));
            middleDots++;
        }
    }
}


оператора XOR


XOR

Да приемем, че р и q са булеви променливи. Също така да предположим, че p1, p2, ... pN са булеви променливи. Нека ^ е оператора XOR.
В този случай, ние предполагаме, че р и q са булеви стойности и се предполага, че ^ е обикновен XOR не побитово XOR. По-късно,  ще го използваме като побитово XOR.
р ^ q е истина, ако точно един от двата операнда p или q е истина. Това е традиционното определение за XOR.
p1 ^ p2 ^ ... ^ pN е истина  ако броят на променливите със стойността истина е нечетно число (и е невярно, ако броят на променливи със стойност истина е четно). Това определение игнорира променливи, на които e присвоено false.
Това може да изглежда странно с оглед на XOR. Все пак, ако смятате, че XOR е асоциативен (той е), това е просто продължение на първото определение на XOR.
Това определение има смисъл, ако прочетете Следващото определение:
p1 ^ p2 ^ ... ^ pN е същото като добавяне на mod 2. Ако Pi е истина, все едно е равно 1, в противен случай го третираме като 0. Тогава, XOR операцията е еквивалентна на:
     p1 ^ p2 ^ ... ^ pN == (p1 + p2 + ... + Pn) % 2
Така, XOR приложен върху куп от булеви променливи, е същото като сумиране на всички стойности на променливите (където истина е 1 и неистина  е 0) и разделяне на mod 2. Спомнете си, че разделянето на mod 2 е един от начините да се определи дали дадено число е четно или нечетно.  Тъй като само променливи, които имат стойност 1 допринасят за сумата, това определя колко променливи имат стойност 1.

Проверка за четност

Хората често използват XOR като средство за правене на Проверка за четност. Един bitstring има нечетен паритет, ако броя на 1-ци в низа е нечетен. Има четен паритет, ако броят на 1-ци е четен. Ако XOR-ваме битовете заедно, можем да кажем дали bitstring има нечетен или четен паритет .
Това често може да се използва за проверка на данните, изпратени през мрежата, където има някаква вероятност, някой бит да се повреди. Например, да предположим, че изпращаме N байта през мрежата от едно място до друго място.
Как може да се определи дали байтовете са изпратени правилно? Единият начин е да се използва един вид контролна сума, която използва XOR. Всеки байт може да бъде написан като b7b6...b0. За всеки байт, XOR-ваме всички битове в позиция bi.
Ако N е 10, а ние пращаме 10 байта, тогава създаваме 11 байт, където bi  е XOR е  ith bit на всички 10 байта. Този 11 байт се нарича контролна сума. Този контролна сума също се изпраща по мрежата.
В края на местоназначението, където се получават данните, може да се извърши независима проверка на контролната сума отново, и да се види, дали новополучената контролна сума съответства на изпратената контролна сума. Ако е така, тогава имате някаква увереност, че няма повредени байтове . Ако сумите не са еднакви, тогава мрежата е повредела някои байт и може да се наложи да изпрати отново данните.
Ясно е, че системата може да има грешки. Например, ако два бита бъдат обърнати, да речем, бит три от байтове 4 и 5, тогава контролна сума би била същата,все едно не са били обърнати, но пак ще има грешки. Въпреки това, тази проверка уловя някои грешки.

Свойства на XOR

Ето няколко полезни свойства на XOR. Това се отнася за обикновен XOR и побитов XOR.
х ^ 0 = x
XOR  с 0 ви дава същито число. По този начин, 0 е идентичността на XOR.

х ^ 1 = ~ x
XOR с 1 дава отрицанието на бита. Отново, това идва от таблицата на истината. За побитово XOR, свойството е  малко по-различно:  x ^ ~ 0 = ~ х. Това е, ако XOR всички с 1, резултатът ще бъде побитово отрицание на х.

х ^ х = 0
XOR х със себе си дава 0. Това е така, защото x е 0 или 1, 0 ^ 0 = 0 и 1 ^ 1 = 0.

XOR е асоциативен.
(х ^ y) ^ z = x ^ (y ^ z).
Можете да проверите това чрез използване на истината таблица.

XOR е комутативен.
х ^ y = y ^ х.
Можете да проверите това чрез използване на истината таблицa.

Побитови XOR

Свойства на XOR се прилагат и за побитово XOR. Да предположим, х и у са 32 битови думи. След това, х ^ y е същато като 32 XOR-а паралелно на масив от 32 булеви.

Размяна на 2 числа без временна променлива

Ето един от тези мозъчни закачки, които можете да дадете на вашите приятели програмисти. Един от класическите проблеми който всеки програмист трябва да бъде в състояние да реши е да се разменят две числа без временна променлива. Ето как изглежда това в C#.
  temp = x ;
  x = y ;
  y = temp ;
За да се разменят се въвежда временна променлива. Името й не трябва да бъде temp,  но въпреки това е допълнителна временна променлива.
Сега да ги разменим без временна променлива.
Как може да се направи това? Ако си мислите "може би мога да използвам побитово XOR", сте прави! Ако сте настроен приключенски, можете да помислите за това как да направите това сами, но ако ли не, отговора е следния.
  х = х ^ y;
  y = x ^ y;
  х = х ^ y;
Как може да се убедим, че това работи?
Ключът е в това да се следи първоначалната стойност на х и у. Нека А да бъде оригиналната стойност на х (това е стойността на x, точно преди тези три реда код). По същия начин, нека B е първоначалната стойност на у.
Ние можем да коментираме всеки ред код, за да видим какво се случва.

   / / x == A, y == B
  х = х ^ y;
   / / x == A ^ B, y == B
  y = x ^ y;
   / / x == A ^ B
   / / y == (A ^ B) ^ B == A ^ (B ^ B) (асоциативност)
   / /   == A ^ 0         (от z ^ z == 0 свойстото)
   / /   == A               (от z ^ 0 == Z свойстото)
  х = х ^ y;
   / / x == (A ^ B) ^ A
   / /   == (A ^ A) ^ B       (от асоциативност ​​/ комутативност)
   / /   == 0 ^ B                 (от z ^ z == 0 свойстото)
   / /   == B                       (от z ^ 0 == Z свойстото)
   / / y == A
След като втората операция е изпълнена, y = A. След третата операция , х = B.
Сега се оказва, че може да направи подобен трик с изваждане вместо XOR. Правейки размени с XOR е малко по-безопасно, отколкото размяна с изваждане, защото изваждане може да предизвика препълване. Въпреки това, обикновено overflow се случва по "добър начин", и израза все още може да работи.

Писане на побитово XOR без ^

Да предположим, че искаме да изпълним побитово XOR, но нямаме ^ оператор. Какво трябва да направим? С побитово AND (&) и побитово OR (|), можем да направим това:
 x ^ y == (~x & y) | (x & ~y)
Това е стандартната дефиниция на XOR, както е описана в логическите книги, отнасящи се за побитови операции .

Обобщение

XOR е интересен оператор. С него можем да направим проверка за паритет и размяна, без временни променливи.

източник :
http://www.cs.umd.edu/class/sum2003/cmsc311/Notes/BitOp/xor.html