Compititive Programming - I Manual
Compititive Programming - I Manual
Compititive Programming - I Manual
PRN NO:-1951711245058
Names of Practical’s:
1. The 3n+1 Problem
2. Minesweeper
3. Interpreter
Theory:
Consider the following algorithm to generate a sequence of numbers. Start with an integer n. If
n is even, divide by 2. If n is odd, multiply by 3 and add 1. Repeat this process with the new value of n,
terminating when n = 1.
For example, the following sequence of numbers will be generated for n = 22:
22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1
It is conjectured (but not yet proven) that this algorithm will terminate at n = 1 for every integer n. Still,
the conjecture holds for all integers up to at least 1,000,000. For an input n, the cycle-length of n is the
number of numbers generated up to and including the 1.
In the example above, the cycle length of 22 is 16.
Given an integer i determine the cycle length .
Input Format
An integer n
Output Format
22
Sample Output
16
Explanation
for n = 22:
22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1
Cycle length = 16
Source Code:
#include<stdio.h>
int main ()
{
int n, m,i,k,j,c,s;
while (scanf("%d %d",&n,&m)==2)
{
s=0;
printf ("%d %d", n,m);
if(n>m)
{
k=m
;
m=n
;
n=k;
}
for(i=n;i<=m; i++)
{
c=1;
j=i;
while(j > 1)
{
if(j % 2==0)
j=j/2;
else
j=(3*j)+1;
c++;
}
if(c>=s)
s=c;
}
printf ("%d",s);
}
return 0;
}
Output:
Conclusion:-
PRN NO:-1951711245058
2: Minesweeper:
Theory:
Minesweeper is a single- player puzzle computer game. The objective of the game is to clear a
rectangular board containing hidden "mines" or bombs without detonating any of them, with help from
clues about the number of neighboring mines in each field.
Rule:
1. If neighbor cells' total flag count equals to this multi-clicked cell's count and predicted
mine locations are true, all closed and unflagged neighbor cells are opened
automatically.
2. If neighbor cells' total flag count equals to this multi-clicked cell's count and at least one
predicted mine location is wrong, game ends with FAIL.
6. If all cells (without mines) are opened using left clicks and/or multi-clicks, game ends with
success.
Source Code:
#include<stdio.h>
#include<stdlib.h>
void welcome();
void rand_mines(char msweep[12][12]);
void printmatrix(char msweep[12][12],int r,char user_chart[12][12]);
int process(char msweep[12][12],int r,int c,charuser_chart[12][12]);
int main()
msweep[12][12] = {{'0'}};
int i,r,c;
char user_chart[12][12] = {{'0'}};
// welcome();
rand_mines(mswep;
printmatrix(msweep,12,user_chart);
while(i == 1)
{
printf("Lucky BRAT, live on for another step\n"); printf("
%c Surrounding MINEs\n\n",msweep[r][c]);
printmatrix(msweep,12,user_chart);
i = process(msweep,r,c,user_chart);
if(i==0)
printf("Game OVER, ta ta. you stepped on a MINE !!\n"); return 0;
void welcome()
{
if(op == 'i')
{
printf("OH DEAR, what a shock you are unfortunatly in the midst of a "); printf("mine
field.\n");
printf("Enter the coordinates of the x and y plane between 1 to 11\n"); printf("Are you
destined to DIE or live ?\n");
printf("HA ha ha hah, GOOD LUCK\n\n");
}
else
returrn;
}
int r,c,m;
//srand(12);
{
r = rand() % 13; // this is mine planting
// so can be at the edges aswell c = rand()
% 13; // so 0 to 13 is APPROPRIATE.
msweep[r][c] = '9';
printf("%d %d \n",r,c);
return;
int i,j;
printf(" .-.-.-.-.-.-.-.-.-.-.-.\n");
for(i=1;i<r;i++)
{
printf("./.");
for(j=1;j<12;j++) //printing 1 to 11
{
printf("%c ",user_chart[i][j]);//to refer to mines use msweep[i][j]
}
printf(".\\.");
printf("\n");
printf(".-.-.-.-.-.-.-.-.-.-.-.-.\n\n");
return;
}
if(msweep[r][c] == '9')
{ k=0;
return k;
}
else
{
if(msweep[i-1][j-1] == '9') b++;
if(msweep[i-1][j] == '9') b++;
if(msweep[i-1][j+1] == '9') b++;
if(msweep[i][j-1] == '9') b++;
if(msweep[i][j+1] == '9') b++;
if(msweep[i+1][j-1] == '9') b++;
if(msweep[i+1][j] == '9') b++;
if(msweep[i+1][j+1] == '9') b++;
return 1;
}
Output:
Conclusion:-
PRN NO:-1951711245058
3: Interpreter:
Theory:
class Token(object):
def init (self, type, value):
self.type = type
self.value = value
def get_next_token(self):
text = self.text
if self.pos > len(text) - 1:
return Token(EOF, None)
current_char = text[self.pos]
if current_char.isdigit():
token = Token(INTEGER, int(current_char))
self.pos += 1
return token
if current_char == '+':
token = Token(PLUS, current_char)
self.pos += 1
return token
self.error()
def expr(self):
self.current_token = self.get_next_token()
left = self.current_token
op = self.current_token
self.eat(PLUS)
right = self.current_token
result = left.value + right.value
return result
def main():
while True:
try:
text =
input('>>> ') except
EOFError:
break
if not text:
continue
interpreter = Interpreter(text)
result = interpreter.expr()
print(result)
Output:
Conclusion:-
09-2020
Name:-Shaikh Musaib Raees
PRN NO:-1951711245058
Names of Practical’s:
1. Jolly
2. Poker Hand
3. Crypt Kicker
4. Contest Scoreboard
1.Jolly:
Title: Write a program on jolly jumper.
Theory:
Jolly jumper:
A sequence of n>0 integer is called a jolly jumper if the absolute values of the difference between
successive elements take on all the values 1 through n-1 . for instance,
1423
Is a jolly jumper, because the absolute difference are 3, 2, and 1 respectively? The defination implies that any
sequence of a single integer is a jolly jumper. You are to write a program to determine whether or not each of a
number of sequence is a jolly.
Input
Each line of input contain an integer n <= 3000 followed by n integers representing the sequence.
Output
For each line of input, generate a line of output saying “Jolly” or “Not jolly”. Sample Input
41423
5 1 4 2 -1 6
Sample Output
JOLLY
NOT JOLLY
Program:
J = N-1;
J = 1;
break;
if(J)
printf("Jolly\n"); else
printf("Not jolly\n");
return 0;
}
Output:
Conclusion:-
10-2020
Name:-Shaikh Musaib Raees
PRN NO:-1951711245058
2.Poker Hand:
Theory:
Stud Poker
The stud poker takes place with a deck of 52 cards. Every card has a value and a color (Spades, Hearts, Clubs,
Diamonds). The values are ordered as follows from the weaker to the stronger: from 2 to 10, then Jack, Queen, King, Ace
(which is also 1).
In the stud poker, every player has five cards in hand. Five cards of the hand of a player form a combination.
Here are the various combinations, classified in increasing order by value.
Program:
#define TRUE 1
#define FALSE 0
typedef struct {
int face; /* FACES map to 0..12 respectively */ char suit;
} card;
card cards[5];
int compare_card(const
void *a, const void *b)
Card c1 =
*(card*)a; card c2 =
*(card*)b; return c1.face –
c2.face
bool are_distinct()
{
int i, j;
for (i = 0; i < 4; ++i) for (j =
i + 1; j < 5; ++j)
if (equals_card(cards[i], cards[j])) return FALSE; return TRUE;
}
bool is_straight()
{
int i;
qsort(cards, 5, sizeof(card), compare_card);
if (cards[0].face + 4 == cards[4].face) return TRUE; if (cards[4].face ==
12 && cards[0].face == 0 && cards[3].face == 3) return TRUE;
return FALSE;
}
bool is_flush()
{
int i;
char suit = cards[0].suit;
for (i = 1; i < 5; ++i) if (cards[i].suit != suit) return FALSE; return TRUE;
}
int main()
{
int i;
const char *type;
const char *hands[10] = { "2h 2d
2c kc qd",
"2h 5h 7d 8c 9s", "ah
2d 3c 4c 5d", "2h 3h 2d
3c 3d", "2h 7h 2d 3c
3d", "2h 7h 7d 7c 7s",
"th jh qh kh ah", "4h
4s ks 5d ts", "qc tc 7c
6c 4c", "ah ah 7c 6c
4c"
};
for (i = 0; i < 10; ++i) {
type = analyze_hand(hands[i]); printf("%s: %s\
n", hands[i], type);
}
return 0;
}
Output:
Conclusion:-
10-2020
Name:-Shaikh Musaib Raees
PRN NO:-1951711245058
3.Crypt Kicker:
Theory:
A common but insecure method of encrypting text is to permute the letters of the alphabet. In other words,
each letter of the alphabet is consistently replaced in the text by some other letter. To ensure that the encryption is
reversible, no two letters are replaced by the same letter. Your task is to decrypt several encoded lines of text,
assuming that each line uses a different set of replacements, and that all words in the decrypted text are from a
dictionary of known words.
Input:
The input consists of a line containing an integer n, followed by n lowercase words, one per line, in
alphabetical order. These n words compose the dictionary of words which may appear in the decrypted text.
Following the dictionary are several lines of input. Each line is encrypted as described above. There are no more than
1,000 words in the dictionary. No word exceeds 16 letters. The encrypted lines contain only lower case letters and
spaces and do not exceed 80 characters in length.
Output:
Decrypt each line and print it to standard output. If there are multiple solutions, any one will do. If there
is no solution, replace every letter of the alphabet by an asterisk.
Source Code:
#include <cstdio> #include
<iostream> #include <vector>
#include <string> #include
<stack> using namespace std;
// dicionario
vector<string> dicio[20][20]; // numero de letras, letras repetidas vector<string> answer;
return true;
}
// repeated_letters()
// devolve o numero de letras repetidas inline int
repeated_letters(string str)
{
int i, cnt[30], sum = 0;
return sum;
}
// backtrack()
// Backtracking - retorna true se achou solucao bool
backtrack(char *line, int deep)
{
// volta if(*line ==
'\0')
return true;
// enumerando candidatos
for(i=0; i<(int)dicio[ word.length() ][rep].size(); i++) { stack<char> st;
string decoded;
string candidate = dicio[word.length()][rep][i]; // candidato a ser traducao de
word
for(j=0; j<(int)word.length(); j++) {
if(get_translation(word[j]) == 0) {
if(nothing_translates_to(candidate[j]))
{ set_translation(word[j], candidate[j]);
st.push(word[j]);
}
else
break;
}
decoded += get_translation(word[j]);
}
// impossible()
// retorna true se estiver na cara que nao tem resposta bool impossible(char
*str)
{
char *p; int n,
i;
char word[100]; bool
imp = true;
for(p=str; sscanf(p, "%s%n", word, &n)>0 && imp; p+=n) { for(i=0; i<20 &&
imp; i++)
imp = dicio[string(word).length()][i].empty();
}
return imp;
}
// main()
// funcao principal int
main()
{
int i, n; char c;
string line;
// inicio answer.clear();
for(c='a'; c<='z'; c++)
set_translation(c, 0);
// backtracking
if(impossible((char*)line.c_str()) || !backtrack((char*)line.c_str(), 0)) { for(i=0; i<(int)line.length(); i+
+)
putchar((line[i]>='a'&&line[i]<='z') ? '*' : ' ');
}
else if(answer.size() > 0){ printf("%s",
answer[0].c_str()); for(i=1;
i<(int)answer.size(); i++)
printf(" %s", answer[i].c_str());
}
putchar('\n');
}
return 0;
}
Output:
6
And
Dick Jane
Puff
Spot
Yertle
bjvg xsb hxsn xsb qymm xsb rqat xsb pnetfn xxxx yyy zzzz
www yyyy aaa bbbb ccc dddddd
Conclusion:-
10-2020
Name:-Shaikh Musaib Raees
PRN NO:-1951711245058
4.Contest Scoreboard:
Theory:
Think the contest score boards are wrong? Here’s your chance to come up with the right rankings.
Contestants are ranked first by the number of problems solved (the more the better), then by decreasing amounts of
penalty time. If two or more contestants are tied in both problems solved and penalty time, they are displayed in
order of increasing team numbers. A problem is considered solved by a contestant if any of the submissions for that
problem was judged correct. Penalty time is computed as the number of minutes it took for the first correct submission
for a problem to be received plus 20 minutes for each incorrect submission received prior to the correct solution.
Unsolved problems incur no time penalties.
Input:
The input begins with a single positive integer on a line by itself indicating the number of the cases
following, each of them as described below. This line is followed by a blank line, and there is also a blank line
between two consecutive inputs. Input consists of a snapshot of the judging queue, containing entries from some or all
of contestants 1 through 100 solving problems 1 through 9. Each line of input will consist of three numbers and a
letter in the format contestant problem time L where L can be ‘C’, ‘I’, ‘R’, ‘U’ or ‘E’. These stand for Correct,
Incorrect, clarification Request, Unjudged and Erroneous submission. The last three cases do not affect scoring.
Lines of input are in the order in which submissions were received.
Output:
For each test case, the output must follow the description below. The outputs of two consecutive cases
will be separated by a blank line. Output will consist of a scoreboard sorted as previously described. Each line of
output will contain a contestant number, the number of problems solved by the contestant and the time penalty
accumulated by the contestant. Since not all of contestants 1-
100 are actually participating, display only the contestants that have made a submission.
Source Code:
#include<stdio.h> struct cricketer
{
int runs,wickets; char
name[25];
}player[100];
int main()
{
int i,n;
printf("Enter the no of cricket players\n"); scanf("%d",&n);
printf("Enter player info as name , runs scored , wickets taken\n"); for(i=0;i<n;i++)
{
scanf("%s %d %d",player[i].name,&player[i].runs,&player[i].wickets);
}
printf("\nNAME\t\tRUNS\t\tWICKETS\n");
for(i=0;i<n;i++)
{
printf("%s\t\t%d\t\t%d\n",player[i].name,player[i].runs,player[i].wickets);
}
return 0;
}
Output: 1
1 2 10 I
3 1 11 C
1 2 19 R
1 2 21 C
1 1 25 C
1 2 66
3 1 11
Conclusion:-
PRN NO:-1951711245058
Name of Practical’s:
1. WERTYU
2. Common permutation
3. Automated Judge Script
4. File Fragmentation
1: WERTYU:
Theory:
Problem:WERTYU
Create a program that will give a result of transferring one row to the right of the correct position of
keys. For example, when the user entered “Q” or “q” the result will give the user “W” or “w” and
so on so forth. The program must be able to decode a message in this sequence.
Inputs may contain numbers,spaces,upper and lower case,punctuations (except a back quote (‘)),
but, shift,ctrl, and alt keys are not included.
Sample Input
O S, GOMR YPFSU/
Sample Output
I AM FINE TODAY
Source Code:
#include <stdio.h>
#include <conio.h>
#include <string.h>
int main()
{
char input[100];
gets(input);
int i, l = strlen(input);
strupr(input);
for (i = 0; i < l; i++)
{
int j;
for (j = 0; j < 47; j++)
{
if (set[j] == input[i] &&
input[i] != '`' &&
input[i] != 'Q' &&
input[i] != 'A' &&
input[i] != 'Z')
{
printf("%c", set[j - 1]);
}
else if (input[i] == ' ')
{
printf(" ");
break;
}
}
}
getch();
}
Output:
Conclusion:-
PRN NO:-1951711245058
2: Common Permutation
n Pk = n! / (n – k)!
Algorithm:
This algorithm only focuses on permutation without going into details of factorial −
START
Step 1 → Define values for n and r
Syntax:
procedure permutation()
Define n and r
P = factorial(n) / factorial(n-r)
DISPLAY P
end procedure.
Source Code:
#include <stdio.h>
int factorial(int n) {
int f;
return factorial(n)/factorial(n-r);
int main()
{
int n, r;
n = 4;
r = 3;
printf("%dp%d = %d \n", n, r, npr(n,r));
return 0;
Output:
PRN NO:-1951711245058
Theory:
The judges from the programming contests are known to be very mean and very lazy. We,
judges, want less work and more Wrong Answers! So, we'd like you to help us and write an
automated judge script to judge solution runs from teams all over the world. All you have to do is
write a program which receives the standard solution and a team output and gives as answer one of
the following messages: "Accepted", "Presentation Error" or "Wrong Answer". We define each one
as:
Accepted:
As we are very mean judges, we only want you to give "Accepted" as answer if the team
output matches the standard solution integrally. That is, ALL characters must match and must be in
the same order.
Presentation Error:
We want you to give "Presentation Error" if all NUMERIC characters match (and in the same
order) but there is at least one non-numeric character wrong (or in wrong order). For instance, "15 0"
and "150" would receive a "Presentation Error", whereas "15 0" and "1 0" would not (it would receive
"Wrong Answer", see bellow).
Wrong Answer:
If the team output could not be classified as any of the two above, then you have no option
but to give "Wrong Answer" as an answer!
Input File:
The input will consist of an arbitrary number of input sets. Each input set begins with a
positive integer n < 100, alone in a line, which describes the number of lines of the standard solution.
The next n lines contain the standard solution. Then there is a positive integer m < 100, alone in a line,
which describes the number of lines of the team output. The next m lines contain the team output. The
input is terminated by the end of file character. No line will have more than 120 character.
Output File:
For each set you should output one of the following lines: Run #x: Accepted Run #x: Presentation Error
Run #x: Wrong Answer
Where x stands for the number of the input set (starting from 1).
Source Code:
#include<stdio.h>
//#include<conio.h>
#include<stdlib.h>
#include<string.h>
#define MAX 13000
int main()
{
int run=1,m,n,i,j,k;
char ans[MAX],out[MAX],num[20],line[130],flag;
// clrscr();
while(fgets(num ,20 , stdin)) // replace all time 'fgats(line, 200, stdin)' with 'gets(num)' for
turbo c++
{
n=atoi(num);
if(!n) break;
memset(ans,0,sizeof(ans));
memset(out,0,sizeof(out));
for(i=0;i<n;i++)
{ fgets(line ,200 , stdin); strcat(ans,line); }
fgets(num, 30, stdin); m=atoi(num);
for(i=0;i<m;i++)
{ fgets(line, 200, stdin); strcat(out,line); }
if(!strcmp(ans,out)&&m==n) flag=1;
else
{
for(i=j=0;ans[i]&&out[j];i++)
if(ans[i]>='0'&&ans[i]<='9')
{
while(out[j]&&(out[j]<'0'||out[j]>'9')) j++;
if(ans[i]!=out[j]) { flag=-1; goto zap; } j+
+;
}
flag=0;
}
zap:
printf("Run #%d: ",run++);
if(flag>0) printf("Accepted\n");
else if(flag==0) printf("Presentation Error\n");
else printf("Wrong Answer\n");
}
// getch();
return 0;
}
Output:
3
123
123
123
123123123
123
123
12312
Conclusion:-
PRN NO:-1951711245058
4: File Fragmentation:
Theory:
File fragmentation:
File fragmentation is a term that describes a group of files that are scattered throughout a hard
drive platter instead of one continuous location. Fragmentation is caused when information is deleted
from a hard drive and small gaps are left behind to be filled by new data. As new data is saved to the
computer it is placed in these gaps, if the gaps are too small the remainder of what needs to be saved is
stored in remaining gaps.
Fragmentation causes slow access time because read/write head accessing the data must find all
fragments of a file before it can be opened or executed. If the hard drive has to do this for dozens or
hundreds of different files as a program is opened, it can greatly decrease the overall performance of
the computer. In the picture below is an example of file fragmentation, as can be seen the second
example has other files and gaps in-between the continuous blue section.
Source Code:
#include <stdio.h>
#include <string.h>
int main()
Char ch;
int i=0,cnt=0; FILE
*fp; Clrscr();
fp=fopen(“in.txt”,”r”);
ch=fgetc(fp);
192.168.1.1,10.1.1.1,Hello”,cnt++);
Printf(“\n 1 192.168.1.1,10.1.1.1,Student”,cnt++);
Printf(“\n 2 192.168.1.1,10.1.1.1,How”,cnt++);
Printf(“\n 4 192.168.1.1,10.1.1.1,Y”,cnt++);
Printf(“\n 5 192.168.1.1,10.1.1.1,ou”,cnt++);
While(ch != EOF)
Printf(“%c”, ch);
i++;
if(i%5==0)
Printf(“\n”);
Ch=fgetc(fp);
getch();
return 0;
}
Output:
Conclusion:-
PRN NO:-1951711245058
Name of Practical’s:
1. Vito’s Family
2. Stacks of Flapjacks
3. Bridge
4. ShellSort
1: Vito’s Family:
Theory:
Vito’s Family:
The world-known gangster Vito Dead stone is moving to New York. He has a very big family there,
all of them living in Lamafia Avenue. Since he will visit all his relatives very often, he is trying to find a
house close to them.
Problem:
Vito wants to minimize the total distance to all of them and has blackmailed you to write a
program that solves his problem.
Input:
The input consists of several test cases. The first line contains the number of test cases.
Note that several relatives could live in the same street number.
Output:
For each test case your program must write the minimal sum of distances from the optimal
Vito's house to each one of his relatives. The distance between two street numbers si and sj is dij=
|si-sj|.
Source Code:
#include<stdio.h>
#include<algorithm>
using namespace std;
int s[505];
int main(){ int
t,n,i,k,add;
scanf("%d",&t);
while(t--){
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&s[i]);
sort(s,s+n);
k=s[n/2];
add=0;
for(i=0;i<n;i++)
add+=abs(s[i]-k);
printf("%d\n",add);
}
}
Output:
Conclusion:-
PRN NO:-1951711245058
2: Stacks of Flapjacks:
Theory:
Stack of Flapjack:
Stacks and Queues are often considered the bread and butter of data structures and find use in
architecture, parsing, operating systems, and discrete event simulation. Stacks are also important in the
theory of formal languages.
This problem involves both butter and sustenance in the form of pancakes rather than bread in addition to
a finicky server who flips pancakes according to a unique, but complete set of rules.
Given a stack of pancakes, you are to write a program that indicates how the stack can be sorted
so that the largest pancake is on the bottom and the smallest pancake is on the top. The size of a pancake is
given by the pancake's diameter. All pancakes in a stack have different diameters
Sorting a stack is done by a sequence of pancake ``flips''. A flip consists of inserting a spatula
between two pancakes in a stack and flipping (reversing) the pancakes on the spatula (reversing the sub-
stack). A flip is specified by giving the position of the pancake on the bottom of the sub-stack to be flipped
(relative to the whole stack). The pancake on the bottom of the whole stack has position 1 and the pancake
on the top of a stack of n pancakes has position n.
A stack is specified by giving the diameter of each pancake in the stack in the order in which the
pancakes appear. For example, consider the three stacks of pancakes below (in which pancake 8 is the top-
most pancake of the left stack):
8 7 2
4 6 5
6 4 8
7 8 4
5 5 6
2 2 7
The stack on the left can be transformed to the stack in the middle via flip(3). The middle stack
can be transformed into the right stack via the command flip(1).
Source Code:
#include <stdio.h>
#include <stdlib.h>
else
};
};
void swap1(int a, int b)
{
int aux; aux=pancakes[a];
pancakes[a]=pancakes[b];
pancakes[b]=aux;
};
void inverte(int a)
{
int i, j;
for (i=0,j=a; i<j; i++,j--)
{
swap1(i,j);
};
};
void calcula()
{
int i;
int j;
int t;
for(i=0; i<(n-1); i++)
{
if(pancakes[0]==pancakes2[i])
{
inverte(n-1-i);
printf("%d ",i+1);
}
else
{ j=1
; t=-
1;
while((j< pancakes[j]==pancakes2[i])
(n-1-i))) {
{ t=j;
if( break;
};
j++;
};
if(t!=-1)
{
inverte(t);
inverte(n-1-i);
printf("%d ",n-t);
printf("%d ",i+1);
};
};
};
};
n++;
}
{
I++;
};
void heapsort()
{
int i;
for(i=0; i<n; i++)
{
heapify(i,1,n-i);
};
};
int main()
{
Char*a;
Int I;
A=(char*)malloc(sizeof(char
)*
100);
A=fgets(a,100,stdin);
While(a)
{
Prenche(a);
For(i=0;i<n;i++)
{
If(i>0)
{
Printf(“ “);
};
Printf(“%d”,pancake[i]);
Pancakes2[i]=pancake[i];
};
Printf(“\
n”);heapsort();calcula();print
f(“0\n”);
A=fgets(a,100,stdin);
};
Return 0;
}
Output:
Conclusion:-
PRN NO:-1951711245058
3: Bridge:
Theory:
The Bridge design pattern allows you to separate the abstraction from the implementation. It is a structural
design pattern.
There are 2 parts in Bridge design pattern :
1. Abstraction
2. Implementation
This is a design mechanism that encapsulates an implementation class inside of an interface class.
The bridge pattern allows the Abstraction and the Implementation to be developed
independently and the client code can access only the Abstraction part without
being concerned about the Implementation part.
The abstraction is an interface or abstract class and the implementor is also an
interface or abstract class.
The abstraction contains a reference to the implementor. Children of the abstraction
are referred to as refined abstractions, and children of the implementor are concrete
implementors. Since we can change the reference to the implementor in the
abstraction, we are able to change the abstraction’s implementor at run-time.
Changes to the implementor do not affect client code.
“In this C++ program, we’ll see how to print reverse triangle bridge pattern in C+
+ using nesting of loops.”
Source Code:
#include<iostream.h>
#include<conio.h> int
main()
{
int i,j,n;
cout<<"Enter Largest Alphabet Value(e.g c=3):"; cin>>n;
for (i=0;i<n;i++)
{
for(j=65;j<64+(2*n);j++)
{
if(j>=(64+n)+i) cout<<(char)((64+n)-(j
%(64+n))); else if(j<=(64+n)-i)
cout<<(char)j;
else
cout<<" ";
}
cout<<endl;
}
getch();
return 0;
}
Output:
Conclusion:-
PRN NO:-1951711245058
4:Shell Sort
Theory:
The idea of shellSort is to allow exchange of far items. In shellSort, we make the array h-sorted for a
large value of h. We keep reducing the value of h until it becomes 1. An array is said to be h-sorted if all
sublists of every h’th element is sorted.
Shell sort is the generalization of insertion sort which overcomes the drawbacks of insertion sort by
comparing elements separated by a gap of several positions. In general, Shell sort performs the following
steps
Step 1: Arrange the elements in the tabular form and sort the columns by using insertion
sort.
Step 2: Repeat Step 1; each time with smaller number of longer columns in such a way
that at the end, there is only one column of data to be sorted.
Algorithm
Shell_Sort(Arr, n)
arr[k+i] = tmp;
}
}
}
}
}
int main()
{
int arr[30];
int k, num;
printf("Enter total no. of elements : ");
scanf("%d", &num);
printf("\nEnter %d numbers: ", num);
Output:
Conclusion:-
.
Godavari College of Engineering, Jalgaon
Subject Name: Competitive Programming
Practical No: 16 ` Date:23-11-2020
PRN NO:-1951711245058
Name of Practical’s:
1. Primary Arithmetic
2. Reverse and Add
3. A Multiplication Game
4. Polynomial Coefficients
1: Primary Arithmetic:
Theory:
Children are taught to add multi-digit numbers from right to left, one digit at a time. Many find the
“carry” operation, where a 1 is carried from one digit position to the next, to be a significant challenge.
Your job is to count the number of carry operations for each of a set of addition problems so that educators
may assess their difficulty.
Source Code:
#include <stdio.h>
#include <string.h>
int main(){
long x, y, carry;
while(1){
scanf("%ld %ld", &x,&y); if(x ==
0 && y == 0) break; carry =
NumCarryAdd(x, y);
if(carry == 0) printf("No carry operation.n"); else
if(carry==1)printf("1 carry operation.n"); else
printf("%ld carry operations.n", carry);
}
return 0;
}
Output:
Conclusion:-
PRN NO:-1951711245058
Theory:
C program to reverse and add a number. This program reverses and add a number entered by a user
and then print it on the screen. For example, if a user will enter 123 as input then 321 will be printed and
sum the numbers and display the output.
Source code:
#include<stdio.h>
#include<conio.h>
int main()
{
int num, rev=0, n, digit;
clrscr();
printf("\n\t Enter the number: ");
scanf("%d", &num);
n = num;
while(n != 0)
{
digit = n % 10;
rev = rev*10 + digit;
n = n/10;
}
printf("\n\t Reverse of entered number: %d", rev); printf("\n\
t sum = %d", rev + num);
getch();
return 0;
}
Output:
Conclusion:-
PRN NO:-1951711245058
3: A Multiplication Game:
Stan and Ollie play the game of multiplication by multiplying an integer p by one of the
numbers 2 to 9. Stan always starts with p = 1, does his multiplication, then Ollie multiplies the
number, then Stan and so on. Before a game starts, they draw an integer 1 < n < 4294967295
and the winner is who first reaches p $/l n.
Input and Output
Each line of input contains one integer number n. For each line of input output one line either
Stan wins.
or
Ollie wins.
Sample input
162
17
34012226
Sample Output
Stan wins.
Ollie wins.
Stan wins.
Source Code:
#include<iostream>
using namespace std;
long long n;
int ret=0;
ret= ret | !func(cur*2);
ret= ret | !func(cur*9);
return ret;
}
int main()
{
//ios_base::sync_with_stdio(0);cin.tie(0);
int tc, kk=1;
string s;
while(cin>>n)
{
if(func(1))
cout<<"Stan wins.\n";
else cout<<"Ollie wins.\n";
}
return 0;
}
Output:
Conclusion:-
PRN NO:-1951711245058
4: Polynomial Coefficients:
Source code:-
#include<stdio.h>
#include<math.h>
#include<conio.h>
int main()
{
Output:
Conclusion:-
PRN NO:-1951711245058
Names of Practical’s:
1. How Many Fibs?
2. Counting
3. Expressions
4. Self-describing Sequence
Theory:
A series of whole numbers in which each number is the sum of the two preceding numbers. Beginning with 0 and
1, the sequence of Fibonacci numbers would be 0,1,1, 2, 3, 5, 8, 13, 21, 34, etc. using the formula n = n(-1) + n(-2),
where the n(-1) means "the last number before n in the series" and n(-2) refers to "the second last one before n in
the series."
Explanation
Fibs number = 0,1,1,2,3,5,8,13,21,34.
formula n = n(-1) + n(-2), where the n(-1) means "the last number before n in the series" and n(-2) refers to "the
second last one before n in the series."
Sourse Code:
#include <stdio.h>
#include <conio.h> int
main()
{
int i, n, t1 = 0, t2 = 1, nextTerm; printf("Enter
the number of terms: "); scanf("%d", &n);
printf("Fibonacci Series: "); for (i =
1; i <= n; ++i)
{
printf("%d”,& t1);
nextTerm = t1 + t2; t1 =
t2;
t2 = nextTerm;
}
getch(); return 0;
}
Output:
Conclusion:-
PRN NO:-1951711245058
2: Counting:
Theory:
C program to find the frequency of characters in a string: This program counts the frequency of characters in a
string, i.e., which character is present how many times in the string. For example, in the string "code" each of the
characters 'c,' 'd,' 'e,' and 'o' has occurred one time. Only lower case alphabets are considered, other
characters (uppercase and special characters) are ignored. You can easily modify this program to handle uppercase and
special symbols.
Source Code:
#include<stdio.h>
/* #include<conio.h>*/
#include<stdlib.h>
#include<string.h>
int main()
{
char string[100];
int c = 0, count[26] = {0}, x;
//clrscr();
printf("Enter a string\n");
gets(string);
c++;
}
for (c = 0; c < 26; c++)
printf("%c occurs %d times in the string.\n", c + 'a', count[c]);
//getch();
return 0;
}
Output:
Conclusion:-
PRN NO:-1951711245058
3: Expressions:
Theory:
A regular expression is a special string that describes a search pattern. Many of you have surely seen and used them
already when typing expressions like ls(or dir)
*.txt , to get a list of all the files with the extension txt. Regular expressions are very useful not only for pattern
matching, but also for manipulating text. In SRMs regular expressions can be extremely handy. Many problems that
require some coding can be written using regular expressions on a few lines, making your life much easier.
Many Topcoders believe that regular expressions are one of Java’s main strengths over C++ in the arena. C++
programmers don’t despair, regular expressions can be used in C++ too.There are several regular expression parsing
libraries available for C+
+, unfortunately they are not very compatible with each other. Fortunately as a Topcoder in the arena one does not
have to cope with all this variety of “not so compatible with one another” libraries. If you plan to use regular
expressions in the arena you have to choose between two flavors of regex APIs: POSIX_regex and GNU_regex. To
use these APIs the header file “regex.h” must be included. Both of these work in two steps – first there is a
function call that compiles the regular expression, and then there is a function call that uses that compiled regular
expression to search or match a string.
Source Code:
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<stdio.h> int
main()
{
char expr1[] = "1+2*5+3"; int res =
evaluate(expr1);
(res == -1)? cout << expr1 << " is " << "Invalid\n":
cout << "Value of " << expr1 << " is " << res << endl;
Output:
Conclusion:-
PRN NO:-1951711245058
4: Self-describing Sequence:
Theory:
Source Code:
#include<stdio.h> int
check(int,int);
int getNumDigits(int); int main()
{
int num=0,temp=0, digit=0,count=0; printf("enter the
number\n"); scanf("%d",&num);
temp=num; int flag
= 1;
int numDigit = getNumDigits(temp);
while(temp>0)
{
digit=temp%10;
int count=check(num,numDigit); if(count!= digit)
{
printf("\tNumber is not a self descriptive"); flag = 0;
break;
}
temp=temp/10;
numDigit--;
}
if(flag)
{
printf("\tNumber is a self descriptive");
}
}
Output:
Conclusion:-