Competitive tasks – Pro9ramming https://pro9ramming.com Software craftsman's blog Wed, 15 Apr 2020 17:51:07 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.2 Python Powerball number generator https://pro9ramming.com/python-powerball-number-generator/ Wed, 16 Aug 2017 14:51:40 +0000 http://pro9ramming.com/blog/?p=489 Continue reading Python Powerball number generator]]> http://openbookproject.net/pybiblio/practice/wilson/powerball.php

Description
To win the Powerball lottery (an extremely unlikely event so don’t waste your time) you have to pick six numbers correctly. The first five numbers are drawn from a drum containing 53 balls and the sixth is drawn from a drum containing 42 balls. The chances of doing this are 1 in 120,526,770. Write a program to generate a set of Powerball numbers by utilizing the choice function in Python’s random module.

Input
Ask the user how many sets of Powerball numbers he or she would like.

Output
The program will print each set of Powerball numbers in numeric order.

Sample session
Official (but fruitless) Powerball number generator

How many sets of numbers? 3

Your numbers: 3 12 14 26 47 Powerball: 2
Your numbers: 1 4 31 34 51 Powerball: 17
Your numbers: 10 12 49 50 53 Powerball: 35

from random import randint
def BubbleSort(l):
    e=0
    for i in range(len(l)-1):
        for j in range(len(l)-1):
            if l[j]>l[j+1]:
                e=l[j+1]
                l[j+1]=l[j]
                l[j]=e
    return l
def MyPrint(L,pb):
        BubbleSort(L)
        print "Your numbers: %d %d %d %d %d Powerball: %d"%(L[0],L[1],L[2],L[3],L[4],pb)

print "Official (but fruitless) Powerball number generator"
No=int(raw_input("How many sets of numbers? "))
for i in range(No):
    numbers=[]
    powerball=randint(1,42)
    i=0
    while (i!=5):
        numbers.append(randint(1,53))
        i+=1
    for i in range(len(numbers)-1):
        for j in range(len(numbers)-1):
            if i==j:
                j+=1
            if numbers[i]==numbers[j] or powerball==numbers[j]:
                numbers[j]=randint(1,53)
                j-=1
    MyPrint(numbers,powerball)

Few notes:
After you choose how many sets of numbers you want, the first ‘while’ loop gives some random numbers to our powerball list. After that, the 2 ‘for’ loops check if we have double numbers in our list. Because after we draw one ball, that one cannot be chosen again and it is out of the game.

Then the process repeats for the rest of the sets.

]]>
Sum of even numbers https://pro9ramming.com/sum-of-even-numbers/ Tue, 20 Dec 2016 07:53:55 +0000 http://pro9ramming.com/blog/?p=385 The task is to create a program that sums all even numbers from 1 to n. If number modulus by 2 is equal to zero than that number is even (k mod 2 = 0). n is a parameter (from standard input).

Pascal solution:

program even_nums_sum;
var i,n,s:integer;
begin
    readln(n);
    s:=0;
    for i:=1 to n do
    begin
        if i mod 2 = 0 then
        begin
            s:=s+i;
        end;
    end;
    writeln(s);
    readln();
end.

]]>
Russian peasant multiplication method https://pro9ramming.com/russian-peasant-multiplication/ Wed, 16 Dec 2015 14:37:46 +0000 http://pro9ramming.com/blog/?p=427 Continue reading Russian peasant multiplication method]]> Russian Peasant multiplication (sometimes called “Ethiopian multiplication” or “Ancient Egyptian multiplication“)  is an interesting multiplication method that can be used to multiply large numbers (without overflow).

This task is interesting because different bitwise operators can be used while writing an algorithm in C++:

int a = 86, b = 57, product = 0;
while (b)
{
if (b & 1)
product += a;
a <<= 1;
b >>= 1;
}
cout << product;
cout << "\n";

First of all “while (b)” actually means “while (b!=0)”. (b & 1) is actually a check if number is odd. And << and >> are shifting operators which effectively give the result of integer multiplication and division respectively.

The solution can be written even more short by using for loop and ternary operator:

int a,b,product = 0;
for(;b;product+=(b&1?a:0), b>>=1, a<<=1);
cout << product;
cout << "\n";

 

 

]]>
Swapping https://pro9ramming.com/swapping/ Wed, 15 Apr 2015 08:14:49 +0000 http://pro9ramming.com/blog/?p=378 Continue reading Swapping]]> One of the first algorithms to understand while learning programming (in any language) is swapping. The idea is to use additional temporary variable to hold the value while swapping (because of possible data loss).

temp = a;
a = b;
b = temp;

If making additional variable temp is an overhead, in-place swap algorithms can be used. They are actually typical space-time trade-offs (if you want to avoid memory/space usage, a bit more processing/time is needed).

If variables that have to be swapped are numbers, swapping can be done by using addition and subtraction in the next way:

a = a + b; //a+=b
b = a - b;
a = a - b; //a-=b

Any other variable types can be swapped using XOR swap algorithm in the next way:

a = a XOR b; //a^=b
b = b XOR a; //b^=a
a = a XOR b; //a^=b

These examples are interesting when dealing with value types, with reference types, it’s a bit different.

]]>
Reversed calculation https://pro9ramming.com/reversed-calculation/ Fri, 12 Dec 2014 19:43:27 +0000 http://pro9ramming.com/blog/?p=64 Continue reading Reversed calculation]]> Task is to write a program that will add one reversed number to another and write their reversed sum. If number is 123 than reversed number is 321.
As you can see all zeros on the end of number are deleted in reversed number.
Input
Two numbers in different lines in standard input.
Output
One number that represent solution.
Sample Input
24
1
Sample Output
34
Sample Input
4358
754
Sample Output
1998
Sample Input
305
794
Sample Output
1
Pascal solution:

program reversed;
uses wincrt;
var
a,b:string;
i,s,t:integer;
begin 
  readln(a);
  readln(b);
  while length(a)<length(a) do
    a:=a+'0';
  while length(b)<length(b) do
    b:=b+'0';
  t:=0;
  for i:=1 to length(b) do
  begin
    s:=ord(a[i])+ord(b[i])-2*ord('0')+t;
    a[i]:=chr(ord('0')+(s mod 10));
    t:=s div 10;
  end;
  if t<>0 then
    a:=a+'1';
  while a[length(a)]='0' do
    delete(a,length(a),1);
  while a[1]='0' do
    delete(a,1,1);
  writeln(a);
end.

 

]]>
Herding Frosh https://pro9ramming.com/herding-frosh/ Fri, 05 Dec 2014 02:43:27 +0000 http://pro9ramming.com/blog/?p=285 Continue reading Herding Frosh]]> One day, a lawn in the center of campus became infested with frosh. In an effort to beautify the campus, one of our illustrious senior classmen decided to round them up using a length of pink silk. Your job is to compute how much silk was required to complete the task.
The senior classman tied the silk to a telephone post, and walked around the perimeter of the area containing the frosh, drawing the silk taught so as to encircle all of them. He then returned to the telephone post. The senior classman used the minimum amount of silk necessary to encircle all the frosh plus one extra meter at each end to tie it.
You may assume that the telephone post is at coordinates (0,0), where the first dimension is north/south and the second dimension is east/west. The coordinates of the frosh are given in meters relative to the post. There are no more than 1,000 frosh.
Input
The input begins with a single positive integer on a line by itself indicating the number of test cases, followed by a blank line.
Each test case consists of a line specifying the number of frosh, followed by one line per frosh with two real numbers given his or her position.
There is a blank line between two consecutive inputs.
Output
For each test case, the output consists of a single number: the length of silk in meters to two decimal places. The output of two consecutive cases will be separated by a blank line.
Sample Input
1
4
1.0 1.0
-1.0 1.0
-1.0 -1.0
1.0 -1.0
Sample Output
10.83
Solution
The key is to calculate sum of every distance. Adding (0,0) coordinates to a array makes things easier (see the picture).

herding_frosh_expl

Solution in example input is 10,83. There are 3 x 2 and 2 x sqrt(2), and remember two meters at the ends, so 4*2+2*sqrt(2)=10.83.

More about Euclidean distance on wiki.

Pascal solution:

program herding_frosh;
uses wincrt;
type
  tarray=record
  x,y:integer;
  end;
var
n,i:integer;
b:array[1..100] of real;
function euclidean_distance(x1,y1,x2,y2:integer):real;
begin
  euclidean_distance:=sqrt(sqr(x1-x2)+sqr(y1-y2));
end;
function calculate:real;
var
  i,n:integer;
  r:real;
  a:array[0..100] of tarray;
begin
r:=0;
readln(n);
with a[0] do
  begin
   x:=0;
   y:=0;
  end;
for i:=1 to n do
readln(a[i].x,a[i].y);
for i:=1 to n do
  begin
    r:=r+euclidean_distance(a[i].x,a[i].y,a[i-1].x,a[i-1].y);
  end;
r:=r+euclidean_distance(a[n].x,a[n].y,a[0].x,a[0].y)+2;
calculate:=r;
end;

begin
readln(n);
for i:=1 to n do
begin
   readln;
   b[i]:=calculate;
end;
for i:=1 to n do
writeln(b[i]:9:2);
end.

 

]]>
Decimal to binary converter https://pro9ramming.com/decimal-to-binary-converter/ Wed, 03 Dec 2014 21:43:27 +0000 http://pro9ramming.com/blog/?p=174 Continue reading Decimal to binary converter]]> The task is to create decimal to binary converter.
For example, to find a binary equivalent of 21, you divide by 2 in steps and take modulus.
21 / 2 = 10 remain 1
10 / 2 = 5 remain 0
5 / 2  = 2 remain 1
2 / 2 = 1 remain 0
1 / 2 = 0 remain 1
At the end, read modulus from bottom-up and you’ll get 1s and 0s.

TPW code:

program dec_to_bin;
uses wincrt;
var
  a:array[1..100] of 0..1;
  n,k,i:integer;
  label top;
begin
top:
writeln('Enter decimal number !');
readln(n);
k:=0;
while n>0 do
begin
k:=k+1;
a[k]:=n mod 2 ;
n:=n div 2;
end;
writeln('Binary number is : ');
for i:=k downto 1 do
write(a[i]);
writeln;
writeln('Press Enter if you want to try again !');
readln;
clrscr;
goto top;
end.

 

]]>
Separate digits from integer number https://pro9ramming.com/separate-digits-from-integer-number/ Tue, 25 Nov 2014 07:43:27 +0000 http://pro9ramming.com/blog/?p=91 Continue reading Separate digits from integer number]]> If you have to find sum of integer’s digits, then use this algorithm is essential. In TPW there are no standard functions as strtoint() and inttosr() as in Delphi. You can easily do this in Delphi with this functions. But in Pascal there is a way to do this without this functions with “mod” and “div” operators.
These functions can be easily understood from this example:

5 div 2 = 2
5 mod 2 = 1

If you get the modulus of a number when divided with 10, you would get last digit, than you can divide it by 10 and do modulus again till you reach zero.

Here is the implementation in TPW:

program cut_digits_out_of_number;
uses wincrt;
var
  n:longint;
  i,j:integer;
  a:array [1..100] of integer;
begin
writeln('Program for cutting digits');
writeln('out of an integer number !');
writeln('Enter integer number !');
readln(n);
i:=0;
repeat
begin
   i:=i+1;
   a[i]:=n mod 10;
   n:=n div 10;  
end;
until n=0;
writeln('Digits are : ');
for j:=i downto 1 do
writeln(a[j]);
end.

But if you want to use function like in Delphi strtoint(), you can make it in Pascal. Like i made it. And i used string cutting and i made that function, so solution looks like this:

program cut_digits_out_of_number;
uses wincrt;
var
  n:string;
  i:integer;
  a:array [1..100] of integer;
function numcheck(s: string): boolean;
var
  x:integer;
begin
numcheck:=true;
for x:=1 to length(s) do
  if (ord(s[x])<48) or (ord(s[x])>57) then
   if s[x]<>'' then
    numcheck:=false;
end;
function str_to_int(s:string):integer;
var
  check:integer;
  i:integer;
begin
   if numcheck(s) then
    val(s,i,check);
   str_to_int:=i;
end;
begin
writeln('Program for cutting digits');
writeln('out of an integer number !');
writeln('Enter integer number !');
readln(n);
for i:=1 to length(n) do
begin
a[i]:=str_to_int(n[i]);
end;
for i:=1 to length(n) do
writeln(a[i]);
end.

Or you can use val procedure, explained in Help:

valprocedure

]]>
Reverse and Add task https://pro9ramming.com/reverse-and-add-task/ Sun, 23 Nov 2014 07:43:27 +0000 http://pro9ramming.com/blog/?p=305 Continue reading Reverse and Add task]]> The reverse and add function starts with a number, reverses its digits, and adds the reverse to the original. If the sum is not a palindrome (meaning it does not give the same number read from left to right and right to left), we repeat this procedure until it does.
For example, starting with 195 as the initial number, 9,339 is the resulting palindrome after the fourth addition:

195  
591   
___
786   

786
687
___
1,473

1,473

This method leads to palindromes in a few steps for almost all of the integers. But there are interesting exceptions. 196 is the first number for which no palindrome has been found. It has never been proven, however, that no such palindrome exists. The task is to write a program that takes a given number and gives the resulting palindrome (if one exists) and the number of iterations it took to find it. It can be assumed that all the numbers used as test data will terminate in an answer with less than 1,000 iterations (additions), and yield a palindrome that is not greater than 4,294,967,295.
Input
The first line will contain an integer N (0 < N ≤ 100), giving the number of test cases, while the next N lines each contain a single integer P whose palindrome you are to compute.
Output
For each of the N integers, print a line giving the minimum number of iterations to find the palindrome, a single space, and then the resulting palindrome itself.
Sample Input
3
195
265
750
Sample Output
4 9339
5 45254
3 6666
Pascal code:

program reverse_and_add;
uses wincrt;
var
n,steps,p,i:longint;
a:array[1..100] of longint;
function reverse(k:longint):longint;
var
  p,i,g,f:longint;
  a:array[1..100] of 0..9;
begin
  g:=1;
  i:=0;
  f:=0;
  repeat
    begin
     i:=i+1;
     a[i]:=k mod 10;
     k:=k div 10;
    end;
  until k=0;
  for p:=1 to i-1 do
   g:=g*10;
   for p:=1 to i do
     begin
      f:=f+g*a[p];
      g:=g div 10;
     end;
     reverse:=f;
end;
function add(k:longint):longint;
var
  i:integer;
begin
  i:=0;
  repeat
    begin
      k:=k+reverse(k);
      i:=i+1;
    end;
  until reverse(k)=k;
  steps:=i;
  add:=k;
end;
begin
readln(n);
for i:=1 to n do
readln(a[i]);
for i:=1 to n do
   begin
     p:=add(a[i]);
     writeln(steps,' ',p);
   end;
end.

C++ code:

#include <iostream>
#include <cstdio>

using namespace std;

int steps,p,i;
int a [100];

int reverse(int k)
{
  int p,i,g,f;
  int a[100];
  g=1;
  i=0;
  f=0;
  do
    {
     i++;
     a[i] = k % 10;
     k = k / 10;
    }
  while (!k == 0);
  for (p=1;p<=i-1;p++)
   g=g*10;
    for (p=1;p<=i;p++)
     {
      f=f+g*a[p];
      g=g / 10;
      }
     return f;
}
int add(int k)
{
  int i;
  i=0;
  while (reverse(k)>k | reverse(k)<k)
    {
      k = k + reverse(k);
      i++;
    }
  
  steps = i;
  return k;
}
int main()
{
    int n;
    cout<<"enter number of test cases"<<endl;
cin>>n;
for (i=1;i<=n;i++)
cin>>a[i];
for (i=1;i<=n;i++)
   {
     p=add(a[i]);
     cout<<steps<<" "<<p<<endl;
   }
   system("pause");
}

 

]]>
153 Theorem https://pro9ramming.com/153-theorem/ Wed, 12 Nov 2014 17:43:27 +0000 http://pro9ramming.com/blog/?p=105 Continue reading 153 Theorem]]> Array is formed this way: First member of array is natural number that can be divided with 3. Every other member is formed by sum of digits ^3 of the member before. For example if number is 45 than next will be 4^3+5^3=64+125=189. There is an interesting theorem that last number in this array is 153. As you can see 1^3+5^3+3^3=1+125+27=153.
Your task is to find after how many members reach 153.
Input
From standard input read an unsigned integer that can be divided with 3.
Output
Output an integer that shows how many members were before.
Sample Input
876
Sample Output
13
Solution
Without an array, just use 2 loops, one for counting members and one for making sum. Here, 3 repeat loops, one for input (if number can not be divided with 3) and 2 for task itself.
TPW:

program theorem_153;
uses wincrt;
var
n,i,k:longint;
begin
repeat
readln(n);
until n mod 3 = 0;
i:=1;
repeat
begin
   k:=n;
   n:=0;
   repeat
    begin
      n:=n+(k mod 10)*(k mod 10)*(k mod 10);
      k:=k div 10;
    end;
   until k=0;
   i:=i+1;
end;
until n=153;
writeln(i);
end.

C++:

# include <iostream>
# include <cstdio>

using namespace std;

int main ()
{
  int n,i,k;
cin>>n;
i=1;
while (n>153 | n<153)
{
   k=n;
   n=0;
   while (k > 0)
    {
      n=n+(k % 10)*(k % 10)*(k % 10);
      k=k / 10;
    }
   i++;
}
cout<<i<<endl;
system("pause");
}

 

]]>