Sie sind auf Seite 1von 51

!

"#$%"&'"
CS 2430-l13
kyle Lrlckson
)*+,-).,
orLfollo of all asslgnmenLs compleLed for CS 2430 ulscreLe SLrucLures.










12S1S
2

!"#$% '( )'*+%*+,
Factoiial ......................................................................................................................................................... S
Soiting ............................................................................................................................................................ 6
Nouulai Exponentiation ...................................................................................................................... 12
RSA Enciyption ........................................................................................................................................ 16
RecuisionIteiation Contiast ............................................................................................................ 22
Caesai Ciphei ............................................................................................................................................ Su
Bayes Theoiem ......................................................................................................................................... SS
Bacteiia uiowth ....................................................................................................................................... S8
Eight Queens .............................................................................................................................................. 42
Tiip Thiough ueimany ......................................................................................................................... 46

/01$"#'0&
-,,./*0%*+ '#1%2+.3%4
Cieate a piogiam in youi selecteu piogiamming language that takes an
integei input fiom the usei anu calculates the factoiial of that integei.
56"+ 7'89%:;4
The basic syntax of c++ tuins out to be similai enough to the java language
that I am familiai with. I uiu not have too haiu of a time aujusting to the changes.
The factoiial algoiithm was incieuibly simple, anu only took a minute oi two to
wiite.
56"+ :.: *'+ 7'89;4
I expeiienceu some uifficulty in setting up my chosen IBE foi c++ on all of my
computeis. Also, the way the piogiam is put togethei is uiffeient, anu will take some
time to become familiai with.
)'00%*+,4
This was a goou staiting pioject. It alloweu me a chance to become familiai
with the new piogiamming language anu IBE, without spenuing too much time on
wiiting a complicateu piogiam.
4

)':%4
!"#$%&''
!"#$%&'( *"+,-.(/01

"#- "#2&-3
"#- 0/"#45
6
'+6
,-'77$+&- ** 89/$-+."/%,:8 ** ,-'77(#'% ** 8;#-(. /# "#-(<(.= >? -+
(@"-78 ** ,-'77(#'%3
,-'77$"# 11 "#2&-3
"#- .(,&%- A "#2&-3
B+. 4"#- " A "#2&-3 " 1 ?3 ">>5
.(,&%- A .(,&%- C 4" > ?53
,-'77$+&- ** 8DE( B/$-+."/% +B 8 ** "#2&- ** 8 ",7 8 ** .(,&%- **
,-'77(#'%3

FGE"%( 4"#2&- :A >?53
F
S


<=+>=+4
)*+,#$'-./

)01.,#$'-./
6
+"#$'23
-,,./*0%*+ '#1%2+.3%4
Implement (S) soiting algoiithms - quicksoit, bubblesoit anu "ioll-youi-
own". You will geneiate Su ianuom numbeis between 1 anu 1uuu, place them in a
uata stiuctuie of youi own choosing, implement all S soiting algoiithms, anu then
you N0ST timecompaie them. Bonus points if youi "own" algoiithm uoes bettei
than the othei two.

56"+ 7'89%:;4
The soiting algoiithms weie faiily simple to unueistanu. It was a simple
piocess to incluue them in my class anu pass the list to the function. All I hau to uo
then was piint the ietuineu soiteu list.

56"+ :.: *'+ 7'89;4
I hau some tiouble getting a piocess timei iunning. Theie weie many
examples I lookeu at that I coulu not get woiking, anu I uon't have enough
expeiience in c++ yet to unueistanu why. I also hau to leain how c++ uses functions
anu what steps aie necessaiy in oiuei to call them piopeily. The oiiginal list also
enueu up soiteu, anu I'm still not exactly suie wheie this is happening. I suspect it
has something to uo with the way c++ uses pointeis, but I will have to look into that
a little moie. I solveu this by ieassigning new ianuom integeis befoie I calleu each
soit function.
7

)'00%*+,4
This assignment gave me goou exeicise in c++ piogiamming. I hau to leain
many new paits of how the language woiks anu what syntax is iequiieu.
I also leaineu a little about function efficiency anu time-cost analysis. The enu
iesults show that quicksoit is slightly fastei than bubblesoit. The algoiithm I chose
to use is equivalent to, oi sometimes fastei than quicksoit in teims of time
efficiency.
8

)':%4
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
using namespace std;

class Sorting{
public:
int * bubbleSort(int list[]);
int * quickSort(int list[], int left, int right);
int * mySort(int list[]);
void printList(int list[]);
};

int * Sorting:: bubbleSort(int list[])
{
int temp, bottom, doSwitch;

for (bottom = 49; bottom >= 1; bottom--)
{
doSwitch = 1;
for ( int i = 0; i<=bottom-1; i++)
if (list[i] > list[i+1])
{
temp = list[i];
list[i] = list[i+1];
list[i+1] = temp;
doSwitch = 0;
}
if (doSwitch)
return list;
}
}

int * Sorting:: quickSort(int list[], int left, int right)
{
int l = left, r = right;
int temp;
int mid = list[(left + right) / 2];

/* partition */
while (l <= r) {
while (list[l] < mid)
l++;
while (list[r] > mid)
r--;
if (l <= r) {
temp = list[l];
list[l] = list[r];
list[r] = temp;
l++;
r--;
}
};

if (left < r)
quickSort(list, left, r);
9
if (l < right)
quickSort(list, l, right);
return list;
}

int * Sorting:: mySort(int list[])
{
int sortedBuffer[1000];
for (int i = 0; i < 1000; i++)
sortedBuffer[i] = 0;
for (int i = 0; i < 50; i++)
sortedBuffer[list[i]] = 1;

int a = 0;
for (int i = 0; i < 1000; i++)
if(sortedBuffer[i] == 1)
{
list[a] = i;
a++;
}
return list;
}

void Sorting:: printList(int list[])
{
for (int i = 0; i < 50; i++)
printf("[%d] ", list[i]);
}

int main()
{

Sorting s;
srand (time(NULL));
int unsortlist[50];
for (int i = 0; i < 50; i++)
unsortlist[i] = rand() % 1000 + 1;
printf("\n******Unsorted******\n");
s.printList(unsortlist);
printf("\n*************Quicksort**************\n");
clock_t t = clock();
s.printList(s.quickSort(unsortlist, 0, 49));
t = clock() - t;
printf("\nProcess time: %f seconds.\n\n",
((double)t)/CLOCKS_PER_SEC);

for (int i = 0; i < 50; i++)
unsortlist[i] = rand() % 1000 + 1;
printf("\n******Unsorted******\n");
s.printList(unsortlist);
printf("\n*************Bubblesort**************\n");
t = clock();
s.printList(s.bubbleSort(unsortlist));
t = clock() - t;
printf("\nProcess time: %f seconds.\n\n",
((double)t)/CLOCKS_PER_SEC);

for (int i = 0; i < 50; i++)
1u
unsortlist[i] = rand() % 1000 + 1;
printf("\n******Unsorted******\n");
s.printList(unsortlist);
printf("\n*************Mysort**************\n");
t = clock();
s.printList(s.mySort(unsortlist));
t = clock() - t;
printf("\nProcess time: %f seconds.\n\n",
((double)t)/CLOCKS_PER_SEC);
}
11

<=+>=+4

12
4"56&0# 789"2:2$'0$'"2
-,,./*0%*+ '#1%2+.3%4
Implement Nouulai Exponentiation.

You will neeu Algoiithms 1 & S fiom Chaptei 4.

**ALu0RITBN 1 Constiucting Base b Expansions.**
pioceuuie: base b expansion(n, b: positive integeis with b > 1)

q := n
k := u
while q = u
ak := q mou b
q := q uiv b
k := k + 1
ietuin (ak-1, . . . , a1, au) {(ak-1 . . . a1au)b is the base b expansion of n}

**ALu0RITBN S Nouulai Exponentiation.**
pioceuuie: mouulai exponentiation(b: integei, n = (ak-1ak-2 . . . a1au)2, m: positive
integeis)

x := 1
powei := b mou m
foi i := u to k - 1
if ai = 1 then x := (x . powei) mou m
powei := (powei . powei) mou m
ietuin x{x equals b^n mou m}

**Youi algoiithm will neeu to solve pioblems 2S-28 on page 2SS.**
2S. 0se Algoiithm S to finu 7^644 mou 64S.
Expecteu: 4S9
26. 0se Algoiithm S to finu 11^644 mou 64S.
Expecteu: 1
27. 0se Algoiithm S to finu S^2uuS mou 99.
Expecteu: 27
28. 0se Algoiithm S to finu 12S^1uu1 mou 1u1.
Expecteu: 22
56"+ 7'89%:;4
1S
The Algoiithms themselves weie easy to unueistanu. It uiun't take me too
long to figuie out what paiameteis my functions woulu iequiie, anu what ietuin
type was neeueu.

56"+ :.: *'+ 7'89;4
The actual couing of the piogiam took a little while to figuie out. I hau to
leain a lot about aiiays anu vectois in C++ in oiuei to get my functions to behave
piopeily. I also still have pioblems when I tiy to sepaiate my functions into
uiffeient classes. I enueu up simply incluuing them in the main class as sepaiate
functions insteau of a sepaiate class.

)'00%*+,4
This was a goou exeicise. I likeu having to figuie out how to use algoiithm 1
within algoiithm S to complete the calculation. Beteimining what paiameteis
neeueu to be passeu anu ietuineu was also goou mental exeicise. The only
fiustiation I have is with leaining the ins anu outs of a new piogiamming language.

14

)':%4

#include <QCoreApplication>
#include <iostream>
#include <math.h>
#include <vector.h>
using namespace std;

vector<int> algorithm1(int n)
{
vector<int> expansion;
int q = n;
int k = 0;
while(q != 0)
{
expansion.push_back(q % 2);
q = q / 2;
k++;

}
return expansion;
}

int algorithm5(int base, int mod, vector<int> n)
{
int x = 1;
int power = base % mod;
for( int i = 0; i < n.size(); i++)
{
if(n.at(i) == 1)
x = (x * power) % mod;
power = (power * power) % mod;
}
return x;
}

int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
printf("*****Modular Exponentiation*****\n");
int p25 = algorithm5(7, 645, algorithm1(644));
printf("Problem 25: 7^644 mod 645 = %d\n", p25);
int p26 = algorithm5(11, 645, algorithm1(644));
printf("Problem 26: 11^644 mod 645 = %d\n", p26);
int p27 = algorithm5(3, 99, algorithm1(2003));
printf("Problem 27: 3^2003 mod 99 = %d\n", p27);
int p28 = algorithm5(123, 101, algorithm1(1001));
printf("Problem 28: 123^1001 mod 101 = %d\n", p28);
}


1S

<=+>=+4

16
-+) 721#;9$'"2
-,,./*0%*+ '#1%2+.3%4
Youi assignment is to enciypt the following message "The Queen Can't Roll When Sanu is in the }ai"
using the values foi p,q anu e below.
ey geneiation

RSA involves a public key anu a piivate key. The public key can be known to eveiyone anu is useu foi
enciypting messages.
Nessages enciypteu with the public key can only be ueciypteu using the piivate key. The keys foi the
RSA algoiithm aie geneiateu
the following way:

*Choose two uistinct piime numbeis p anu q.
*Foi secuiity puiposes, the integeis p anu q shoulu be chosen at ianuom, anu shoulu be of similai
bit-length.
Piime integeis can be efficiently founu using a piimality test.
*Compute n = pq.
*n is useu as the mouulus foi both the public anu piivate keys
*Compute (n) = (p-1)(q-1), wheie is Eulei's totient function.
*Choose an integei e such that 1 < e < (n) anu gieatest common uivisoi of (e, (n)) = 1; i.e., e anu
(n) aie copiime.
*e is ieleaseu as the public key exponent.
*e having a shoit bit-length anu small Bamming weight iesults in moie efficient enciyption - most
commonly ux1uuu1 = 6S,SS7.
Bowevei, small values of e (such as S) have been shown to be less secuie in some settings.|4j
*Beteimine u as:
u \equiv e^{-1} \pmou{\vaiphi(n)}
i.e., u is the multiplicative inveise of e mou (n).
This is moie cleaily stateu as solve foi u given (ue) mou (n) = 1
This is often computeu using the extenueu Eucliuean algoiithm.
u is kept as the piivate key exponent.
so, u*e= 1 mou (n) The public key consists of the mouulus n anu the public (oi enciyption)
exponent e.
The piivate key consists of the mouulus n anu the piivate (oi ueciyption) exponent u which must
be kept seciet.
(p, q, anu (n) must also be kept seciet because they can be useu to calculate u.)




56"+ 7'89%:;4
17
I finally figuieu out how to use sepaiate classes in the same piogiam in C++.
I hau a lot moie motivation to uo so foi this assignment, since it useu a few functions
fiom the pievious assignment. 0nce I hau that pait figuieu out, tiansfeiiing the
mouulai exponentiation functions into my piogiam was veiy easy. I also quickly
leaineu how to set vaiiables anu functions to be public oi piivate.

56"+ :.: *'+ 7'89;4
I hau uifficulty figuiing out the mouulai multiplicative inveise function. It
was a little confusing at fiist with what it was actually computing. 0nce I figuieu
that pait out, it was pietty stiaightfoiwaiu to implement the algoiithm.

)'00%*+,4
This assignment was fun once I figuieu out the mouulai multiplicative
inveise poition. It woulu have been nice to have a little moie uiiection on what was
expecteu with the actual chaiactei conveision to integei value. 0thei than the initial
iequiiement, that poition of the assignment is not explaineu.
18

)':%4
#include <QCoreApplication>
#include <iostream>
#include <math.h>
#include <vector.h>
using namespace std;

class ModExponentiation{
public:
vector<int> algorithm1(int);
int algorithm5(int, int, vector<int>);
};

//returns the base 2 expansion of a power
vector<int> ModExponentiation::algorithm1(int n)
{
vector<int> expansion;
int q = n;
int k = 0;
while(q != 0)
{
expansion.push_back(q % 2);
q = q / 2;
k++;
}
return expansion;
}

//takes the base, the mod, and the power as a base 2
expansion(algorithm1 return vector)
int ModExponentiation::algorithm5(int base, int mod, vector<int> n)
{
int x = 1;
int power = base % mod;
for( int i = 0; i < n.size(); i++)
{
if(n.at(i) == 1)
x = (x * power) % mod;
power = (power * power) % mod;
}
return x;
}

class RSA{
public:
int e;
RSA();
int encrypt(int);
int decrypt(int);
private:
ModExponentiation modEx;
int p,q,n,tot,d;
int modInverse();
};

RSA::RSA()
{
19
e = 17;
p = 61;
q = 53;
n = (p*q);
tot = (p-1)*(q-1);
d = modInverse();
}

//Use public key to encrypt
int RSA::encrypt(int m)
{
int encryption = modEx.algorithm5(m, n, modEx.algorithm1(e));
return encryption;
}

//Use private key to decrypt
int RSA::decrypt(int c)
{
int decryption = modEx.algorithm5(c, n, modEx.algorithm1(d));
return decryption;
}

//return the modular multiplicative inverse of public key and totient
int RSA::modInverse()
{
int t = e % tot;
for(int x = 1; x < tot; x++)
{
if((t*x) % tot == 1) return x;
}
}

int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
RSA rsa;
char s[] = "The Queen Can't Roll When Sand is in the Jar";
printf("\nOriginal:\n%s\n", s);

printf("\n\nAfter encryption:\n");
int sE[44];
for(int i = 0; i < 44; i++)
{
sE[i] = rsa.encrypt(s[i]);
printf("%d ", sE[i]);
}

printf("\n\nAfter decryption:\n");
int sD[44];
for(int i = 0; i < 44; i++)
{
sD[i] = rsa.decrypt(sE[i]);
printf("%d ", sD[i]);
}
printf("\n");
for(int i = 0; i < 44; i++)
{
printf("%c", sD[i]);
2u
}

printf("\n\n");
}
21

<=+>=+4

22
-:16#<'"2=>$:#0$'"2 ."2$#0<$
-,,./*0%*+ '#1%2+.3%4
Compaiecontiast Recuision anu Iteiative methous. Implement Fibonacci
(Algoiithms 78) anu iepoit which one peifoims bettei. Also, implement Algoiithm
4 (pg S6S) anu ieimplement the pioblems solveu in the Nouulai Exponentiation
assignment. Wiite a paiagiaph with suppoiting uata foi each methou (hint, you
shoulu have a total of 4 paiagiaphs) compaiingcontiasting youi iesults.

56"+ 7'89%:;4
The new algoiithms weie veiy easy to implement. The mouulai
exponentiation coue was even easiei since it hau alieauy been wiitten foi oui
pievious assignments. The piogiam as a whole went togethei veiy quickly anu
without any issues.

56"+ :.: *'+ 7'89;4
I hau an issue with the function timei on the iecuisive algoiithms. When I
woulu builu the coue as a ielease veision in the QT euitoi, the timei woulu not
ieflect the actual calculation time. It woulu usually uisplay a time of u. I knew this
was incoiiect, so I tiieu it again in uebug moue. I founu that in uebug moue, the
timeis all woik fine anu ieflect the calculation time piopeily. I'm not suie what
changes between uebug anu ielease moue, anu I will have to look into it a little moie
befoie I tiy to uo moie timing in a ielease builu.
2S
)'0>"8%?)'*+8",+4
Fibonacci
Recuisive: The iecuisive algoiithm took much longei than the Iteiative
veision. This is likely uue to the continueu function calls peifoimeu. With smallei
integeis, theie is much less uiffeience in piocessing time. The iecuisive algoiithm
has the auvantage of simplicity anu a shoitei coue length. Some might consiuei the
iecuisive veision easiei to unueistanu.
Iteiative: The iteiative methou woiks fastei foi laigei integeis passeu to it. It
uoes iequiie moie memoiy since it must initialize moie vaiiables than the iecuisive
veision. The length of the wiitten coue is also much longei than that of the iecuisive
function. I peisonally finu the algoiithm itself a little less stiaightfoiwaiu anu moie
complicateu to unueistanu.
Nouulai Exponentiation
Recuisive: The iecuisive algoiithm foi mouulai exponentiation is much
shoitei than the iteiative veision. The ietuin is complicateu by multiple iecuisive
calls, but this coulu piobably be maue moie efficient with some fuithei iefinement
of the coue. The time cost of the iecuisive methou is also less than the iteiative
veision foi all of the calculations. It seems cleai that the iecuisive methou is the
bettei choice foi these pioblems.
Iteiative: Foi mouulai exponentiation, the iteiative algoiithm is significantly
moie complex in teims of the coue. It iequiies a sepaiate algoiithm to put togethei
the base expansion in oiuei to calculate the mouulai exponentiation. This makes the
iteiative function slowei than the iecuisive one. Theie may be a point with
24
incieasingly laigei numbeis wheie the iteiative veision is moie time efficient. Foi
this set of pioblems, the iteiative methou is not the best choice.
)'00%*+,4
This was a simple assignment, but uiu make me think about the uiffeient
ways an algoiithm coulu be consiueieu efficient. Foi many puiposes, it seems that
computing speeu is the most impoitant. Bowevei, it is also easy to see why memoiy
efficiency woulu be uesiieu in ceitain situations.
2S

)':%4
#include <QCoreApplication>
#include <iostream>
#include <vector.h>
#include <math.h>

class ModExponentiation{
public:
vector<int> algorithm1(int);
int algorithm5(int, int, vector<int>);
int algorithm4(unsigned int, unsigned int, int);
};

//returns the base 2 expansion of a power
vector<int> ModExponentiation::algorithm1(int n)
{
vector<int> expansion;
int q = n;
int k = 0;
while(q != 0)
{
expansion.push_back(q % 2);
q = q / 2;
k++;
}
return expansion;
}

//takes the base, the mod, and the power as a base 2
expansion(algorithm1 return vector)
int ModExponentiation::algorithm5(int base, int mod, vector<int> n)
{
int x = 1;
int power = base % mod;
for( int i = 0; i < n.size(); i++)
{
if(n.at(i) == 1)
x = (x * power) % mod;
power = (power * power) % mod;
}
return x;
}

/*
*ALGORITHM 4 Recursive Modular Exponentiation.
*procedure mpower(b, n, m: integers with b > 0 and m ! 2, n ! 0)
*if n = 0 then
* return 1
*else if n is even then
* return mpower(b, n/2,m)^2 mod m
*else
* return (mpower(b, floor(n/2),m)^2 mod m b mod m) mod m
*{output is bn mod m}
*/
int ModExponentiation::algorithm4(unsigned int base, unsigned int exp,
int mod)
{
26
if( exp == 0 )
return 1;
else if(exp % 2 == 0)
return ((algorithm4(base, (exp/2), mod))*(algorithm4(base,
(exp/2), mod)))% mod;
else
{
int sq = algorithm4(base, (exp/2), mod)*algorithm4(base,
(exp/2), mod);
return sq % mod*(base % mod)% mod;
}
}

class Fibonacci{
public:
int recursive(unsigned int);
int iterative(unsigned int);
};

/*
*ALGORITHM 7 A Recursive Algorithm for Fibonacci Numbers.
*procedure fibonacci(n: nonnegative integer)
*if n = 0 then return 0
*else if n = 1 then return 1
*else return fibonacci(n " 1) + fibonacci(n " 2)
*{output is fibonacci(n)}
*/
int Fibonacci::recursive(unsigned int n)
{
if( n == 0)
return 0;
else if( n == 1)
return 1;
else
return (recursive( n - 1 ) + recursive( n - 2 ));
}

/*
*ALGORITHM 8 An Iterative Algorithm for Computing Fibonacci Numbers.
*procedure iterative fibonacci(n: nonnegative integer)
*if n = 0 then return 0
*else
* x := 0
* y := 1
* for i := 1 to n " 1
* z := x + y
* x := y
* y := z
* return y
*{output is the nth Fibonacci number}
*/
int Fibonacci::iterative(unsigned int n)
{
int x;
int y;
int z;
if(n == 0)
return 0;
27
else
{
x = 0;
y = 1;
for(int i = 1;i < n; i++)
{
z = x + y;
x = y;
y = z;
}
return y;
}
}

int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
Fibonacci fib;
ModExponentiation exp;

printf("***Iterative Fibonacci***\n");
clock_t fIT = clock();
int fI = fib.iterative(40);
fIT = clock()-fIT;
printf("Result: %d\nProcess time: %f seconds.\n\n", fI,
((double)fIT)/CLOCKS_PER_SEC);

printf("***Recursive Fibonacci***\n");
clock_t fRT = clock();
int fR = fib.recursive(40);
fRT = clock()-fRT;
printf("Result: %d\nProcess time: %f seconds.\n\n", fR,
((double)fRT)/CLOCKS_PER_SEC);

printf("***Iterative Exponentiation***\n");
clock_t eIT = clock();
int i25 = exp.algorithm4(7, 644, 645);
int i26 = exp.algorithm4(11, 644, 645);
int i27 = exp.algorithm4(3, 2003, 99);
int i28 = exp.algorithm4(123, 1001, 101);
eIT = clock()-eIT;
printf("Problem 25: 7^644 mod 645 = %d\n", i25);
printf("Problem 26: 11^644 mod 645 = %d\n", i26);
printf("Problem 27: 3^2003 mod 99 = %d\n", i27);
printf("Problem 28: 123^1001 mod 101 = %d\n", i28);
printf("Process time: %f seconds.\n\n",
((double)eIT)/CLOCKS_PER_SEC);

printf("***Recursive Exponentiation***\n");
clock_t eRT = clock();
int r25 = exp.algorithm5(7, 645, exp.algorithm1(644));
int r26 = exp.algorithm5(11, 645, exp.algorithm1(644));
int r27 = exp.algorithm5(3, 99, exp.algorithm1(2003));
int r28 = exp.algorithm5(123, 101, exp.algorithm1(1001));
eRT = clock()-eRT;
printf("Problem 25: 7^644 mod 645 = %d\n", r25);
printf("Problem 26: 11^644 mod 645 = %d\n", r26);
printf("Problem 27: 3^2003 mod 99 = %d\n", r27);
28
printf("Problem 28: 123^1001 mod 101 = %d\n", r28);
printf("Process time: %f seconds.\n\n",
((double)eRT)/CLOCKS_PER_SEC);
}


29

<=+>=+4

Su
.0:<0# .'9?:#
-,,./*0%*+ '#1%2+.3%4
Implement a piogiam that will take ANY such foimula foi the Caesai
Ciphei. You will useneeu this foi the fiist Niuteim exam. 0se the S+P mou 26
initially foi youi assignment; make suie youi piogiam can hanule ANY foimula.

56"+ 7'89%:;4
The whole piogiam was veiy simple to figuie out. The algoiithm to shift
each lettei went togethei veiy quickly anu without issue.

56"+ :.: *'+ 7'89;4

I only hau one minoi issue when I took input fiom the usei. I founu out that the c++
function "cin" takes only the stiing up until a whitespace chaiactei.
I hau to change this to the "getline" function in oiuei to take a full stiing input fiom
the usei.

)'00%*+,4
This assignment hau veiy little in teims of uiiection. It enueu up being veiy
simple to figuie out, but it woulu have been nice to have a little moie infoimation as
to what was expecteu.
S1

)':%4
#include <QCoreApplication>
#include <iostream>
#include <string>
using namespace std;

string cipherEncrypt(string in)
{
string alphabet = "abcdefghijklmnopqrstuvwxyz";
string out = "";

int i;

for (i = 0; i < in.length(); i++)
{
if (in[i] == ' ')
out += " ";
else
out += alphabet[(3 + alphabet.find(in[i])) % 26];
}
return out;
}

int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
string in;

cout << "Input message: ";
getline(cin, in);

cout << "Encrypted message: " << cipherEncrypt(in) << endl;
return 0;
}

S2

<=+>=+4

SS
*0;:< ,?:"#:@
-,,./*0%*+ '#1%2+.3%4
You will be implementing a ueneializeu Bayes Theoiem (pg 472). It shoulu
hanule Fiench guyFinancial vius. Also, financial viu's math might be in eiioi.
Fiom the "Fiench guy" viueo: P(boy|Fiance) = 12, P(Fiance) = 29
((29)*(12))(((29)*(12))+((S9)*(1S))+((49)*(14)))
Fiom the Financial viueo: P(up|uiowth) = 8u%, P(uiowth) = 7u%
(8u*7u)((8u*7u)+(Su*Su))

56"+ 7'89%:;4
The Bayes Theoiem algoiithm initially lookeu like it might be somewhat
complicateu. Aftei implementing it howevei, I founu that it was actually veiy simple.
I enueu up making 2 veisions of the algoiithm. 0ne that takes a pie-calculateu value
foi the uenominatoi, anu one that takes a list of event objects in oiuei to calculate
the value foi the uenominatoi. The lattei is useful when theie aie seveial events
that neeu to be multiplieu anu auueu to compose the uenominatoi.

56"+ :.: *'+ 7'89;4
I uiu not have any issues wiiting this piogiam. I uiu notice a few ways that it
coulu be expanueu anu maue moie iobust. The piogiam coulu be changeu to use a
weighteu giaph uata stiuctuie with the euge weights iepiesenting the piobability.

S4
)'00%*+,4
Again this assignment lackeu cleai uiiection. Insteau of saying to implement
the pioblems in the viueos, it woulu be bettei to list the exact iequiiement.
SS

)':%4
#include <QCoreApplication>
#include <iostream>
#include <vector.h>

class Event{
public:
Event(double, double);
double pA;
double pBa;
};

Event::Event(double pA, double pBa)
{
this->pA = pA;
this->pBa = pBa;
}

class BayesTheorem{
public:
double calculate(double, double, double);
double calculate(Event, vector<Event>);
double percentage(int, int);
};

double BayesTheorem::calculate(double pA, double pBa, double pE)
{
double probability = pA * pBa / pE;

return probability;
}
double BayesTheorem::calculate(Event event, vector<Event> list)
{
double probTotal = 0;
for(unsigned int i = 0; i<list.size();i++)
probTotal += list.at(i).pA * list.at(i).pBa;
double probability = event.pA * event.pBa / probTotal;
return probability;
}

int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
BayesTheorem bT;

/*France Boy: P(boy|France) = 1/2, P(France) = 2/9
((2/9)*(1/2))/(((2/9)*(1/2))+((3/9)*(1/3))+((4/9)*(1/4)))
*/
vector<Event> french;
S6
Event fra = Event(0.22, 0.5);
Event uk = Event(0.33, 0.33);
Event can = Event(0.44, 0.25);
french.push_back(fra);
french.push_back(uk);
french.push_back(can);
//double frenchBoy = bT.calculate( 0.22, 0.5,
(0.22*0.5)+(0.33*0.33)+(0.44*0.25));
double frenchBoy = bT.calculate(fra,french);
printf("French Guy problem result: %.4f or %.2f%%\n",
frenchBoy, frenchBoy*100);

/* Economy Growth: P(up|Growth) = 80%, P(Growth) = 70%
(80*70)/((80*70)+(30*30))
*/
Event growUp = Event(0.7, 0.8);
//Event growDown = Event(0.7, 0.2);
Event slowUp = Event(0.3, 0.3);
//Event slowDown = Event(0.3, 0.7);
vector<Event> econUp;
econUp.push_back(growUp);
econUp.push_back(slowUp);
//double econGrowth = bT.calculate(0.70, 0.80,
((0.70*0.80)+(0.30*0.30)));
double econGrowth = bT.calculate(growUp, econUp);
printf("Economy problem result: %.4f or %.2f%%\n",
econGrowth, econGrowth*100);
a.quit();
}

S7

<=+>=+4

S8
*01$:#'0 A#"B$?
-,,./*0%*+ '#1%2+.3%4
You will wiite a piogiam to solve the pioblem as follows:
A ueauly bacteiium is extiemely active anu will kill a peison if they have moie than
1N bacteiia in theii bouy at any given time. Theie is a single cuie that takes 2 houis
to begin woiking to kill the bacteiia. If a peison staits out with 2 bacteiia anu
uoubles eveiy 2u minutes, how long befoie they aie ueau. When uo you neeu to
stait the cuie so the patient uoes N0T uie.

56"+ 7'89%:;4
Beteimining how to peifoim the calculation was an easy task. Theie enueu
up being seveial ways of implementing this in the piogiam that woulu have
piobably filleu the iequiiement. I enueu up solving the bacteiia giowth equation foi
the vaiiable time. This woulu give me the amount of time iequiieu foi any given size
of bacteiia population. I useu this to ueteimine the time of ueath, anu the point at
which the cuie must be auministeieu.

56"+ :.: *'+ 7'89;4
I uiu not have any issues couing this assignment. The most tiouble I hau was
looking up the cmath log anu exp functions in the c++ API.

)'00%*+,4
S9
This assignment was veiy easy. I uiu like that theie weie seveial paths to take in
oiuei to come to the enu iesult. I exploieu a few of these methous befoie ueciuing
on uoing a little math befoie implementing an algoiithm that woulu ietuin an
amount of time foi a given population level.

4u

)':%4
#include <QCoreApplication>
#include <iostream>
#include <cmath>
#define R 0.034657359

double bacteria;
//double growth = 0.034657359;
int minutes;

int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);

double t = (log(1000000/2)/R)/60;
std::cout <<"Time till death: "<< t << " hours.\nCure must be
implemented no later than " << t-2 << " hours after infection.\n";
}

41

<=+>=+4

42
7'3?$ C6::2<
-,,./*0%*+ '#1%2+.3%4
If youi S# enus in an 0BB numbei (1,S,S,7,9) you will implement the 8
Queen's pioblem.
The %./6+ @=%%*, >=AA$% is the pioblem of placing eight chess queens on an 88
chessboaiu so that no two queens attack each othei. Thus, a solution iequiies that
no two queens shaie the same iow, column, oi uiagonal.
56"+ 7'89%:;4
The piogiam uiun't iequiie leaining any new aspects of C++. The piogiam
itself went thiough a few iteiations, but all of them woikeu. It was simply a mattei
of selecting which veision to use foi this assignment.
56"+ :.: *'+ 7'89;4
I spent a shoit amount of time tiying to use a vectoi insteau of an aiiay, but
kept encounteiing issues. With moie time, I woulu change to vectois to allow foi
usei input to ueteimine the numbei of queens to solve foi. I woulu neeu to change
the size of the uata stiuctuie, as well as change the N constant of the piogiam.
)'00%*+,4
This assignment woulu have been a little moie fun if it hau iequiieu the piogiam to
be a game insteau of just solving the pioblem. I woulu have likeu to leain moie
about basic giaphics anu usei input.
4S

)':%4
#include <QCoreApplication>
#include <iostream>
using namespace std;

const int N = 8;
int position[N];
int countSolutions = 0;

bool safeCheck(int queen, int rowPosition)
{
for(int i = 0; i < queen; i++)
{
int otherRowPosition = position[i];
if(otherRowPosition == rowPosition || otherRowPosition ==
rowPosition - (queen-i) || otherRowPosition == rowPosition + (queen-i))
return false;
}
return true;
}//end isSafe

void nQueens(int q)
{
if(q == N) //Solution found
{
printf("Solution %d: ", countSolutions+1);
for(int i = 0; i < N; i++)
printf("%d ", position[i]);
cout << endl;
countSolutions++;
}
else
{
for(int i = 0; i < N; i++) //Generate combinations
{
if(safeCheck(q,i))
{
position[q] = i;
nQueens(q+1);
}
}
}
}//end solve

int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
printf("Each number represents the Queen's position in each row of
the board\n");
nQueens(0);
printf("%d total solutions.\n", countSolutions);
return 0;
}


44


<=+>=+4

4S

46
,#'9 ,?#"63? A:#@02;
-,,./*0%*+ '#1%2+.3%4
You have come into some money and would like to take your parents and grandparents on a
once-in-a-lifetime trip before the Fed completely devalues the US currency with QE3 and the
Euro is worthless. Oma and Opa live in Boston and your parents have recently moved to
Nashville, Tn. You will be taking your Mom, Dad, Oma and Opa back to Germany to visit all of
the places that were near/dear to their hearts growing up, as they have never been back since
they fled Germany after the war.
Here are the cities as follows:
Rostock
Lubeck (home of the best marzipan)
Hamburg (Oma/Opa want to drive under the river - a taxi can do this as well)
Bremen
Hannover (Consumer Electronics haven - purchase each a new iPad at 180 Euros each)
Kassel
Dusseldorf
Koln (taxi will be needed to visit the castle 10km away from the hauptbahnhof)
St. Augustine
Bonn
Wiesbaden
** Frankfurt
Mannheim
Karlsruhe
Baden Baden (Oma wants to visit a Spa here, therefore, you will need to spend the day)
** Stuttgart
** Munchen (Munich)
Nurnberg
Dresden
Leipzig
** Berlin
Basel, Switzerland (Opa and Dad want to purchase a nice watch and this is the best place for
such a purchase - you will be spending $6K Euro/watch)
You will be using Priceline.com, Travelocity.com, Orbitz.com or whatever online travel site you
would like to use. As Oma/Opa are advancing in years, you want to minimize time traveled
(Oma can basically only handle short periods of time traveling, especially with a bad back).
The cities that are starred are the only cities you are allowed as a starting point (or entry into
Germany), because your plane arrives into Germany from the US. You will have the option of
47
renting a car, or taking the ICE train http://www.raileurope.com/train-faq/european-
trains/ice/how-to-book.h...
If you take the train, you will need to take a taxi (1,2 Euros/km traveled). Most taxis can barely
accommodate 5 people comfortably.
You are not only going to calculate the optimal route based on the TSP, but you will also
need to MINIMIZE your costs. If you rent a car, it will cost roughly 300 Euros/week for Diesels
and 350 Euros/week for petrol based cars plus taxes. Normally taxes for these cars are 2x the
base rate (eg. 300 Euros because you rented this from the airport; 300 Euros German
taxes). Travel speed from point-to-point is roughly 130kmh (max). If you drive a Turbo Diesel
(Audi/BMW/VW), you can get roughly 13km/liter and petrol based cars can get a little bit better
mileage at about 22km/liter and current petrol prices can be found
here: http://www.aaireland.ie/AA/Motoring-advice/Petrol-Prices.aspx
For the database chapter you will be collecting ALL of the necessary data for this assignment
placing this data in an open source database of your own choice (MySQL, postgres, sqllite,
etc.) You will also be using this to pull and store your data for whatever algorithm you feel will
work the best below. Hint: you might want ALL of the data in your database already
calculated? Remember, I want this as km/Euros and then have your program
use http://www.xe.com/ to convert to miles/km.
For the chapters on Graphs/Trees you will be using Dijkstra, Prim or possibly Kruskal's
algorithms to solve the optimization piece of cost, time & travel. Bonus points for the one who
optimizes all of the constraints. I would like a bottom line COST, TIME and ROUTE for this
trip. As in Physics problems, omit friction and food costs.

56"+ 7'89%:;4
The gatheiing of uata foi the assignment was easy, but time consuming. The
uatabase setup was somewhat easiei than I hau thought at fiist. Builuing the
aujacency matiix in the piogiam was also an easy task, although that may be
because I have uone that befoie. Theie seemeu to have been veiy few things that
woikeu out veiy well on this assignment, anu I uiu a lot of iethinking anu iewiiting.
56"+ :.: *'+ 7'89;4
I tiieu seveial algoiithms befoie I ueciueu on one that seemeu to peifoim the
opeiation that I wanteu. When I tiieu Bjikstia's algoiithm, I noticeu that it was not
48
visiting eveiy noue, insteau simply finuing the path with the minimal uistance. The
algoiithm I enueu up with still uiu not behave exactly how I woulu like it to, but I
ian out of time to optimize it moie. I hau to figuie out many aspects of c++ couing to
complete this assignment. With moie time anu iesouices available, I woulu builu a
custom weighteu giaph to tiack my noues anu euge weights. Each noue woulu be a
custom object, which coulu be compaieu to anothei of the same type.
)'00%*+,4
I feel like this assignment is oveily complicateu in many ways. Theie aie
many small uetails incluueu in the uesciiption, but it is uncleai what the stuuent is
expecteu to uo with them. It woulu be bettei to incluue an aujacency matiix with the
assignment anu a cleai set of iules foi ueteimining the optimal path.
49

)':%4
#include <QCoreApplication>
#include <stdio.h>
#include <iostream>
#include <limits.h>

#define V 22

using namespace std;

string cities[V] = {"Rostock", "Lubeck", "Hamburg", "Bremen",
"Hannover", "Kassel", "Dusseldorf", "Koln",
"St. Augustine", "Bonn", "Wiesbaden", "Frankfurt",
"Mannheim", "Karlsruhe", "Baden-Baden",
"Stuttgart", "Munchen", "Nurnberg", "Dresden", "Leipzig",
"Berlin", "Basel, Switzerland"};

int minKey(int key[], bool mstSet[])
{
int min = INT_MAX, min_index;

for (int v = 0; v < V; v++)
if (mstSet[v] == false && key[v] < min)
min = key[v], min_index = v;

return min_index;
}

void printMinTree(int parent[], int graph[V][V])
{
printf("Path \t\t Efficiency\n");
for (int i = 0; i < V; i++)
cout << cities[parent[i]] << " -> " << cities[i] << " --- " <<
graph[i][parent[i]] << endl;
}

void optimalPath(int graph[V][V])
{
int trip[V];
int key[V];
bool visited[V];

for (int i = 0; i < V; i++)
key[i] = INT_MAX, visited[i] = false;

key[0] = 0;
trip[0] = 11; //Start point of trip

for (int count = 0; count < V-1; count++)
{
int u = count;//Start index for the path

visited[u] = true;

Su
for (int v = 0; v < V; v++)

if (graph[u][v] && visited[v] == false && graph[u][v] <
key[v])
trip[v] = u, key[v] = graph[u][v];
}

printMinTree(trip, graph);
}

int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
//Adjacency matrix of cities containing optimization calculations
int graph[V][V] =
{{0,3,4,7,7,11,13,13,14,14,15,15,17,18,19,18,17,14,9,8,5,22},
{3,0,2,4,5,8,10,11,11,11,13,12,14,15,16,16,19,15,11,10,7,19},
{4,2,0,3,3,7,9,9,10,10,12,11,13,14,15,15,17,14,11,9,6,18},
{7,4,3,0,3,6,6,7,7,8,10,10,12,13,14,14,17,13,11,8,9,17},
{7,5,3,3,0,4,6,7,7,7,8,8,10,11,12,11,14,10,8,6,6,15},
{11,8,7,6,4,0,5,5,6,6,5,4,6,7,8,8,11,7,8,6,8,11},
{13,10,9,6,6,5, 0,1,2,2,5,5,6,8,8,9,14,10,13,11,12,12},
{13,11,9,7,7,5, 1,0,1,1,4,4,6,7,8,8,13,9,13,11,13,11},
{14,11,10,7,7,6,2,1,0,0,3,4,5,6,7,8,12,8,13,11,13,10},
{14,11,10,8,7,6,2,1,0,0,4,4,5,6,7,8,12,9,13,11,13,10},
{15,13,12,10,8, 5,5,4,3,4,0,1,2,3,4,5,9,6,11,9,13,7},
{15,12,11,10,8, 4,5,4,4,4,1,0,2,3,4,5,9,5,11,9,12,7},
{17,14,13,12,10,6,6,6,5,5,2,2,0,2,2,3,8,5,12,10,14,6},
{18,15,14,13,11,7,8,7,6,6,3,3,2,0,1,2,7,6,12,12,15,4},
{19,16,15,14,12,8,8,8,7,7,4,4,2,1,0,2,7,6,13,12,16,4},
{18,16,15,14,11,8,9,8,8,8,5,5,3,2,2,0,5,5,11,11,14,6},
{17,19,17,17,14,11,14,13,12,12,9,9,8,7,7,5,0,4,10,10,13,9},
{14,15,14,13,10,7,10,9,8,9,6,5,5,6,6,5,4,0,7,6,10,10},
{9,11,11,11,8,8,13,13,13,13,11,11,12,12,13,11,10,7,0,3,4,16},
{8,10,9,8,6,6,11,11,11,11,9,9,10,12,12,11,10,6,3,0,4,16},
{5,7,6,9,6,8,12,13,13,13,13,12,14,15,16,14,13,10,4,4,0,19},
{22,19,18,17,15,11,12,11,10,10,7,7,6,4,4,6,9,10,16,16,19,0}};

optimalPath(graph);

return 0;
}


S1


<=+>=+4

Das könnte Ihnen auch gefallen