Add second year

This commit is contained in:
2023-12-07 01:19:12 +00:00
parent 3291e5c79e
commit 3d12031ab8
1168 changed files with 431409 additions and 0 deletions

View File

@ -0,0 +1,95 @@
import java.util.*;
import java.io.*;
public class Alphabet {
// initialising a String containing all the letters of the alphabet and turning it into a character array (to save typing)
public static String alphabetString = "abcdefghijklmnopqrstuvwxyz";
public static char alphabet[] = alphabetString.toCharArray();
// declaring a Scanner object to use to scan in the user input
public static Scanner scanner = new Scanner(System.in);
public static void main(String args[]) {
System.out.println("Type the alphabet in order (lowercase).");
// prompting the user to enter 'f' or 'b' and scanning in the input (only scanning the 0th character of input)
System.out.println("Forwards or Backwards? (f/b): ");
char fb = scanner.next().charAt(0);
// switch statement to determine forward or backwards, or exit
switch(fb) {
case 'f':
System.out.println("Time taken: " + forwards() + "s");
break;
case 'b':
System.out.println("Time taken: " + backwards() + "s");
break;
default:
System.out.println("Invalid input!. You must enter either 'f' or 'b' to start.");
System.exit(1);
}
}
// method for going through the alphabet forwards
private static long forwards() {
// getting the time when the user started
long start = System.currentTimeMillis();
// looping for each of the 26 letters
int i = 0;
while (i < 26) {
// checking if the scanned in character was the correct one
// if the it was not, then i will not be incremented, and it will loop again on the same letter.
if (scanner.next().charAt(0) == alphabet[i]) {
if (i == 25) { // checking if it's the last letter, and if so, printing a special message
System.out.println("Correct! Well done!");
i++;
}
else { // otherwise, prompting the user to enter the next letter
System.out.println("[" + alphabet[i] + ": Correct! Now type '" + alphabet[++i] + "']"); // i gets incremented
}
}
}
// calculating the total time taken
long total = System.currentTimeMillis() - start;
// returning the total time taken in seconds (by dividing by 1000)
return total / 1000;
}
// method for going through the alphabet backwards
private static long backwards() {
// getting the time when the user started
long start = System.currentTimeMillis();
// looping for each of the 26 letters
int i = 25;
while (i >= 0) {
// checking if the scanned in character was the correct one
// if the it was not, then i will not be decremented, and it will loop again on the same letter.
if (scanner.next().charAt(0) == alphabet[i]) {
if (i == 0) { // checking if it's the last letter, and if so, printing a special message
System.out.println("Correct! Well done!");
i--;
}
else { // otherwise, prompting the user to enter the next letter
System.out.println("[" + alphabet[i] + ": Correct! Now type '" + alphabet[--i] + "']"); // i gets decremented
}
}
}
// calculating the total time taken
long total = System.currentTimeMillis() - start;
// returning the total time taken in seconds (by dividing by 1000)
return total / 1000;
}
}

View File

@ -0,0 +1,107 @@
import java.util.*;
import java.io.*;
public class Alphabet {
// declaring a Scanner object to use to scan in the user input
public static Scanner scanner = new Scanner(System.in);
public static void main(String args[]) {
System.out.println("Type the alphabet in order (lowercase).");
// prompting the user to enter 'f' or 'b' and scanning in the input (only scanning the 0th character of input)
System.out.println("Forwards or Backwards? (f/b): ");
char fb = scanner.next().charAt(0);
// switch statement to determine forward or backwards, or exit
switch(fb) {
case 'f':
boolean forwards = true;
break;
case 'b':
boolean forwards = false;
break;
default:
System.out.println("Invalid input!. You must enter either 'f' or 'b' to start.");
System.exit(1);
}
if (forwards) {
char c = 'a';
while (c < 'z') {
// checking if the scanned in character was the correct one
// if the it was not, then c will not be incremented, and it will loop again on the same letter.
if (scanner.next().charAt(0) == c) {
if (c == 'z') { // checking if it's the last letter, and if so, printing a special message
System.out.println("Correct! Well done!");
c++;
}
else { // otherwise, prompting the user to enter the next letter
System.out.println("[" + c + ": Correct! Now type '" + ++c + "']"); // c gets incremented
}
}
}
}
// method for going through the alphabet forwards
private static long forwards() {
// getting the time when the user started
long start = System.currentTimeMillis();
// looping for each of the 26 letters
int i = 0;
while (i < 26) {
// checking if the scanned in character was the correct one
// if the it was not, then i will not be incremented, and it will loop again on the same letter.
if (scanner.next().charAt(0) == alphabet[i]) {
if (i == 25) { // checking if it's the last letter, and if so, printing a special message
System.out.println("Correct! Well done!");
i++;
}
else { // otherwise, prompting the user to enter the next letter
System.out.println("[" + alphabet[i] + ": Correct! Now type '" + alphabet[++i] + "']"); // i gets incremented
}
}
}
// calculating the total time taken
long total = System.currentTimeMillis() - start;
// returning the total time taken in seconds (by dividing by 1000)
return total / 1000;
}
// method for going through the alphabet backwards
private static long backwards() {
// getting the time when the user started
long start = System.currentTimeMillis();
// looping for each of the 26 letters
int i = 25;
while (i >= 0) {
// checking if the scanned in character was the correct one
// if the it was not, then i will not be decremented, and it will loop again on the same letter.
if (scanner.next().charAt(0) == alphabet[i]) {
if (i == 0) { // checking if it's the last letter, and if so, printing a special message
System.out.println("Correct! Well done!");
i--;
}
else { // otherwise, prompting the user to enter the next letter
System.out.println("[" + alphabet[i] + ": Correct! Now type '" + alphabet[--i] + "']"); // i gets decremented
}
}
}
// calculating the total time taken
long total = System.currentTimeMillis() - start;
// returning the total time taken in seconds (by dividing by 1000)
return total / 1000;
}
}

View File

@ -0,0 +1,152 @@
\documentclass[11pt]{article}
\usepackage{report}
\usepackage[utf8]{inputenc} % allow utf-8 input
\usepackage[T1]{fontenc} % use 8-bit T1 fonts
\usepackage[colorlinks=true, linkcolor=black, citecolor=blue, urlcolor=blue]{hyperref} % hyperlinks
\usepackage{url} % simple URL typesetting
\usepackage{booktabs} % professional-quality tables
\usepackage{amsfonts} % blackboard math symbols
\usepackage{nicefrac} % compact symbols for 1/2, etc.
\usepackage{listings}
\usepackage{microtype} % microtypography
\usepackage{lipsum} % Can be removed after putting your text content
\usepackage{graphicx}
\graphicspath{ {./images/} }
\usepackage{natbib}
\usepackage{doi}
\setcitestyle{aysep={,}}
\usepackage{array}
\usepackage{xcolor}
\definecolor{codegreen}{rgb}{0,0.6,0}
\definecolor{codegray}{rgb}{0.5,0.5,0.5}
\definecolor{codeorange}{rgb}{1,0.49,0}
\definecolor{backcolour}{rgb}{0.95,0.95,0.96}
\lstdefinestyle{mystyle}{
backgroundcolor=\color{backcolour},
commentstyle=\color{codegray},
keywordstyle=\color{codeorange},
numberstyle=\tiny\color{codegray},
stringstyle=\color{codegreen},
basicstyle=\ttfamily\footnotesize,
breakatwhitespace=false,
breaklines=true,
captionpos=b,
keepspaces=true,
numbers=left,
numbersep=5pt,
showspaces=false,
showstringspaces=false,
showtabs=false,
tabsize=2,
xleftmargin=10pt,
}
\lstset{style=mystyle}
\title{CT2109 - Object-Oriented Programming: Data Structures \& Algorithms}
\author{Andrew Hayes\\
\AND
\AND
\AND
\AND
Student ID: 21321503 \\
\AND
2BCT\\
\AND
University of Galway\\
}
% Uncomment to remove the date
% \date{February 2022}
% Uncomment to override the `A preprint' in the header
\renewcommand{\undertitle}{Assignment 01}
\renewcommand{\headeright}{CT2109 Assignment 01}
\renewcommand{\shorttitle}{}
%%% Add PDF metadata to help others organize their library
%%% Once the PDF is generated, you can check the metadata with
%%% $ pdfinfo template.pdf
% \hypersetup{
% pdftitle={A template for the arxiv style},
% pdfsubject={q-bio.NC, q-bio.QM},
% pdfauthor={David S.~Hippocampus, Elias D.~Striatum},
% pdfkeywords={First keyword, Second keyword, More},
% }
\begin{document}
\maketitle
\newpage
\setcounter{page}{1}
\section{Problem Statement with Analysis \& Design Notes}
At its most basic, this assignment will require an array of all the letters of the alphabet, and two methods:
one to loop through the array in alphabetical order, and the other to loop it in counter-alphabetical order.
There will be a choice presented to the user whether to loop through the alphabet \textit{forwards} (alphabetical order)
or \textit{backwards} (counter-alphabetical) order.
To choose between these two options there will be a case statement.
A \verb|char| will be scanned in from the user.
If the \verb|char| is equal to \verb|'f'|, then the \verb|forwards()| method will be executed, and the time taken will be printed out.
If the \verb|char| is equal to \verb|'b'|, then the \verb|backwards()| method will be executed, and the time taken will be printed out.
The \verb|default| of the case statement will be to print an error message and exit with code \verb|1|.
While the use of two separate methods for the alphabetical \& counter-alphabetical versions is not the absolute most efficient option in terms of lines of code,
the use of separate functions enhances the readability of the code and allows for a cleaner implementation, at the cost of repeating only two or three lines of code.
It also reduces the need for nested if statements, which are both inefficient and often difficult to read.
The \verb|forwards()| \& \verb|backwards()| methods will be essentially the same.
They will both return the \verb|long| data type, which will be the time taken in seconds.
To calculate the time taken in seconds, before the ``game'' begins, the start time will be recorded with \verb|System.currentTimeMillis()|.
The end time will be recorded in a similar manner at the end, and the total will be calculated from subtracting one from the other.
This total will then be divided by 1000 (to convert from milliseconds to seconds) and then returned, where it will then be printed out.
The game itself will work in a similar manner in both methods: the array of the letters of the alphabet will be looped through using a \verb|while| loop
A character will be scanned in from the user.
If the character is correct, a success message will be printed and the index variable incremented or decremented as appropriate for the method.
Otherwise, the loop will be executed again on the same character, effectively ignoring the input, until the appropriate character is entered.
If the index is at the last character of either sequence (alphabetical or counter-alphabetical), a special message will be printed out if the answer is correct.
The only real difference between the two methods will be the way in which they loop through the alphabet array.
\verb|forwards()| will loop through the array in alphabetical order, starting at index \verb|0| and incrementing the index for each correct answer, with the loop condition \verb|while (i < 26)|.
\verb|backwards()| will loop the array in counter-alphabetical order, starting at index \verb|25| and decrementing the index for each correct answer, with the loop condition \verb|while (i >= 0)|.
\section{Code}
\lstinputlisting[language=Java, breaklines=true, caption={Alphabet.java}]{../code/Alphabet.java}
\section{Testing}
There are two main scenarios that must be tested for both the \verb|forwards()| \& \verb|backwards()| methods: correct input \& incorrect input.
Of these two main scenarios, we should test them at the first character of the sequence, the last character of the sequence, and some of the middle characters.
The main reason for this is that the first \& last characters are in a sense special, particularly the last one, so what may work for the ``middle'' characters may not work for the others.
Furthermore, the case statement to choose between forwards \& backwards should be tested with input \verb|f|, \verb|b|, and some incorrect, third option.
\begin{center}
\begin{figure}[htp]
\centering
\includegraphics[width=0.7\textwidth]{invalid_input.png}
\caption{Testing invalid input to the case statement}
\end{figure}
\end{center}
\begin{center}
\begin{figure}[htp]
\centering
\includegraphics[width=0.3\textwidth]{forwards.png}
\caption{Testing forwards with valid \& invalid, first, middle, \& last input}
\end{figure}
\end{center}
\begin{center}
\begin{figure}[htp]
\centering
\includegraphics[width=0.3\textwidth]{backwards.png}
\caption{Testing backwards with valid \& invalid, first, middle, \& last input}
\end{figure}
\end{center}
\end{document}

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 58 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

View File

@ -0,0 +1,264 @@
\NeedsTeXFormat{LaTeX2e}
\ProcessOptions\relax
% fonts
\renewcommand{\rmdefault}{ptm}
\renewcommand{\sfdefault}{phv}
% set page geometry
\usepackage[verbose=true,letterpaper]{geometry}
\AtBeginDocument{
\newgeometry{
textheight=9in,
textwidth=6.5in,
top=1in,
headheight=14pt,
headsep=25pt,
footskip=30pt
}
}
\widowpenalty=10000
\clubpenalty=10000
\flushbottom
\sloppy
\newcommand{\headeright}{Ph.D. Confirmation Report}
\newcommand{\undertitle}{Ph.D. Confirmation Report}
\newcommand{\shorttitle}{\@title}
\usepackage{fancyhdr}
\fancyhf{}
\pagestyle{fancy}
\renewcommand{\headrulewidth}{0.4pt}
\fancyheadoffset{0pt}
\rhead{\scshape \footnotesize \headeright}
\chead{\shorttitle}
\cfoot{\thepage}
%Handling Keywords
\def\keywordname{{\bfseries \emph{Keywords}}}%
\def\keywords#1{\par\addvspace\medskipamount{\rightskip=0pt plus1cm
\def\and{\ifhmode\unskip\nobreak\fi\ $\cdot$
}\noindent\keywordname\enspace\ignorespaces#1\par}}
% font sizes with reduced leading
\renewcommand{\normalsize}{%
\@setfontsize\normalsize\@xipt\@xiipt
\abovedisplayskip 7\p@ \@plus 2\p@ \@minus 5\p@
\abovedisplayshortskip \z@ \@plus 3\p@
\belowdisplayskip \abovedisplayskip
\belowdisplayshortskip 4\p@ \@plus 3\p@ \@minus 3\p@
}
\normalsize
\renewcommand{\small}{%
\@setfontsize\small\@xpt\@xipt
\abovedisplayskip 6\p@ \@plus 1.5\p@ \@minus 4\p@
\abovedisplayshortskip \z@ \@plus 2\p@
\belowdisplayskip \abovedisplayskip
\belowdisplayshortskip 3\p@ \@plus 2\p@ \@minus 2\p@
}
\renewcommand{\footnotesize}{\@setfontsize\footnotesize\@ixpt\@xpt}
\renewcommand{\scriptsize}{\@setfontsize\scriptsize\@viipt\@viiipt}
\renewcommand{\tiny}{\@setfontsize\tiny\@vipt\@viipt}
\renewcommand{\large}{\@setfontsize\large\@xiipt{14}}
\renewcommand{\Large}{\@setfontsize\Large\@xivpt{16}}
\renewcommand{\LARGE}{\@setfontsize\LARGE\@xviipt{20}}
\renewcommand{\huge}{\@setfontsize\huge\@xxpt{23}}
\renewcommand{\Huge}{\@setfontsize\Huge\@xxvpt{28}}
% sections with less space
\providecommand{\section}{}
\renewcommand{\section}{%
\@startsection{section}{1}{\z@}%
{-2.0ex \@plus -0.5ex \@minus -0.2ex}%
{ 1.5ex \@plus 0.3ex \@minus 0.2ex}%
{\large\bf\raggedright}%
}
\providecommand{\subsection}{}
\renewcommand{\subsection}{%
\@startsection{subsection}{2}{\z@}%
{-1.8ex \@plus -0.5ex \@minus -0.2ex}%
{ 0.8ex \@plus 0.2ex}%
{\normalsize\bf\raggedright}%
}
\providecommand{\subsubsection}{}
\renewcommand{\subsubsection}{%
\@startsection{subsubsection}{3}{\z@}%
{-1.5ex \@plus -0.5ex \@minus -0.2ex}%
{ 0.5ex \@plus 0.2ex}%
{\normalsize\bf\raggedright}%
}
\providecommand{\paragraph}{}
\renewcommand{\paragraph}{%
\@startsection{paragraph}{4}{\z@}%
{1.5ex \@plus 0.5ex \@minus 0.2ex}%
{-1em}%
{\normalsize\bf}%
}
\providecommand{\subparagraph}{}
\renewcommand{\subparagraph}{%
\@startsection{subparagraph}{5}{\z@}%
{1.5ex \@plus 0.5ex \@minus 0.2ex}%
{-1em}%
{\normalsize\bf}%
}
\providecommand{\subsubsubsection}{}
\renewcommand{\subsubsubsection}{%
\vskip5pt{\noindent\normalsize\rm\raggedright}%
}
% float placement
\renewcommand{\topfraction }{0.85}
\renewcommand{\bottomfraction }{0.4}
\renewcommand{\textfraction }{0.1}
\renewcommand{\floatpagefraction}{0.7}
\newlength{\@abovecaptionskip}\setlength{\@abovecaptionskip}{7\p@}
\newlength{\@belowcaptionskip}\setlength{\@belowcaptionskip}{\z@}
\setlength{\abovecaptionskip}{\@abovecaptionskip}
\setlength{\belowcaptionskip}{\@belowcaptionskip}
% swap above/below caption skip lengths for tables
\renewenvironment{table}
{\setlength{\abovecaptionskip}{\@belowcaptionskip}%
\setlength{\belowcaptionskip}{\@abovecaptionskip}%
\@float{table}}
{\end@float}
% footnote formatting
\setlength{\footnotesep }{6.65\p@}
\setlength{\skip\footins}{9\p@ \@plus 4\p@ \@minus 2\p@}
\renewcommand{\footnoterule}{\kern-3\p@ \hrule width 12pc \kern 2.6\p@}
\setcounter{footnote}{0}
% paragraph formatting
\setlength{\parindent}{\z@}
\setlength{\parskip }{5.5\p@}
% list formatting
\setlength{\topsep }{4\p@ \@plus 1\p@ \@minus 2\p@}
\setlength{\partopsep }{1\p@ \@plus 0.5\p@ \@minus 0.5\p@}
\setlength{\itemsep }{2\p@ \@plus 1\p@ \@minus 0.5\p@}
\setlength{\parsep }{2\p@ \@plus 1\p@ \@minus 0.5\p@}
\setlength{\leftmargin }{3pc}
\setlength{\leftmargini }{\leftmargin}
\setlength{\leftmarginii }{2em}
\setlength{\leftmarginiii}{1.5em}
\setlength{\leftmarginiv }{1.0em}
\setlength{\leftmarginv }{0.5em}
\def\@listi {\leftmargin\leftmargini}
\def\@listii {\leftmargin\leftmarginii
\labelwidth\leftmarginii
\advance\labelwidth-\labelsep
\topsep 2\p@ \@plus 1\p@ \@minus 0.5\p@
\parsep 1\p@ \@plus 0.5\p@ \@minus 0.5\p@
\itemsep \parsep}
\def\@listiii{\leftmargin\leftmarginiii
\labelwidth\leftmarginiii
\advance\labelwidth-\labelsep
\topsep 1\p@ \@plus 0.5\p@ \@minus 0.5\p@
\parsep \z@
\partopsep 0.5\p@ \@plus 0\p@ \@minus 0.5\p@
\itemsep \topsep}
\def\@listiv {\leftmargin\leftmarginiv
\labelwidth\leftmarginiv
\advance\labelwidth-\labelsep}
\def\@listv {\leftmargin\leftmarginv
\labelwidth\leftmarginv
\advance\labelwidth-\labelsep}
\def\@listvi {\leftmargin\leftmarginvi
\labelwidth\leftmarginvi
\advance\labelwidth-\labelsep}
% create title
\providecommand{\maketitle}{}
\renewcommand{\maketitle}{%
\par
\begingroup
\renewcommand{\thefootnote}{\fnsymbol{footnote}}
% for perfect author name centering
\renewcommand{\@makefnmark}{\hbox to \z@{$^{\@thefnmark}$\hss}}
% The footnote-mark was overlapping the footnote-text,
% added the following to fix this problem (MK)
\long\def\@makefntext##1{%
\parindent 1em\noindent
\hbox to 1.8em{\hss $\m@th ^{\@thefnmark}$}##1
}
\thispagestyle{empty}
\@maketitle
\@thanks
%\@notice
\endgroup
\let\maketitle\relax
\let\thanks\relax
}
% rules for title box at top of first page
\newcommand{\@toptitlebar}{
\hrule height 2\p@
\vskip 0.25in
\vskip -\parskip%
}
\newcommand{\@bottomtitlebar}{
\vskip 0.29in
\vskip -\parskip
\hrule height 2\p@
\vskip 0.09in%
}
% create title (includes both anonymized and non-anonymized versions)
\providecommand{\@maketitle}{}
\renewcommand{\@maketitle}{%
\vbox{%
\hsize\textwidth
\linewidth\hsize
\vskip 0.8in
\@toptitlebar
\centering
{\LARGE\sc \@title\par}
\@bottomtitlebar
\vskip 0.5in
\textsc{\Large\undertitle}\\
\vskip 2.0in
\def\And{%
\end{tabular}\hfil\linebreak[0]\hfil%
\begin{tabular}[t]{c}\bf\rule{\z@}{24\p@}\ignorespaces%
}
\def\AND{%
\end{tabular}\hfil\linebreak[4]\hfil%
\begin{tabular}[t]{c}\bf\rule{\z@}{24\p@}\large\ignorespaces%
}
\begin{tabular}[t]{c}\bf\rule{\z@}{24\p@}\Large\@author\end{tabular}%
\vskip 1.0in \@minus 0.1in \center{\large\@date} \vskip 0.2in
}
}
% add conference notice to bottom of first page
\newcommand{\ftype@noticebox}{8}
\newcommand{\@notice}{%
% give a bit of extra room back to authors on first page
\enlargethispage{2\baselineskip}%
\@float{noticebox}[b]%
\footnotesize\@noticestring%
\end@float%
}
% abstract styling
\renewenvironment{abstract}
{
\centerline
{\large \bfseries \scshape Abstract}
\begin{quote}
}
{
\end{quote}
}
\endinput

View File

@ -0,0 +1,63 @@
/** Array implementation of Stack ADT */
import javax.swing.JOptionPane;
public class ArrayStack implements Stack
{
protected int capacity; // The actual capacity of the stack array
protected static final int CAPACITY = 1000; // default array capacity
protected Object S[]; // array used to implement the stack
protected int top = -1; // index for the top of the stack
public ArrayStack() {
// default constructor: creates stack with default capacity
this(CAPACITY);
}
public ArrayStack(int cap) {
// this constructor allows you to specify capacity of stack
capacity = (cap > 0) ? cap : CAPACITY;
S = new Object[capacity];
}
public void push(Object element) {
if (isFull()) {
JOptionPane.showMessageDialog(null, "ERROR: Stack is full.");
return;
}
top++;
S[top] = element;
}
public Object pop() {
Object element;
if (isEmpty()) {
JOptionPane.showMessageDialog(null, "ERROR: Stack is empty.");
return null;
}
element = S[top];
S[top] = null;
top--;
return element;
}
public Object top() {
if (isEmpty()) {
JOptionPane.showMessageDialog(null, "ERROR: Stack is empty.");
return null;
}
return S[top];
}
public boolean isEmpty() {
return (top < 0);
}
public boolean isFull() {
return (top == capacity-1);
}
public int size() {
return (top + 1);
}
}

View File

@ -0,0 +1,13 @@
/** Abstract Stack interface */
public interface Stack
{
// most important methods
public void push(Object n); // push an object onto top of the stack
public Object pop(); // pop an object from top of the stack
// others
public Object top(); // examine top object on stack without removing it
public boolean isEmpty(); // true if stack is empty
public boolean isFull(); // true if stack is full (if it has limited storage)
}

View File

@ -0,0 +1,205 @@
import java.util.*;
import java.util.regex.*;
public class StackCalculator {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in); // creating a new scanner to read in expressions from the user
String expr; // creating a String to hold the expression read in.
boolean invalidInput; // boolean to tell whether the user's input was invalid
// will only loop if invalidInput is set to true
do {
// default false, meaning we assume valid input
invalidInput = false;
// prompting the user to enter expression & scanning it in
System.out.println("Enter an infix numerical expression between 3 & 20 characters:");
expr = sc.nextLine();
// regex that will be used to match expressions that contain illegal characters
Pattern illegalchars = Pattern.compile("(?=[^\\^\\*\\/\\+\\-\\(\\)])(?=[^0-9])"); // this is confusing-looking because in java, one has to escape the backslashes for one's regex escape sequences
Matcher illegalcharsMatcher = illegalchars.matcher(expr);
// regex that will be used to match numbers that are double-digit or more
Pattern doubledigit = Pattern.compile("[0-9][0-9]"); // just checking if a digit is ever followed by another digit
Matcher doubledigitMatcher = doubledigit.matcher(expr);
// checking that the input length is correct
if (expr.length() > 20 || expr.length() < 3) {
System.out.println("Invalid input. Please ensure that the length of the input is between 3 and 20 characters");
invalidInput = true;
}
// checking for invalid characters using a regular expression which matches strings that contain characters that are neither operands or digits
else if (illegalcharsMatcher.find()) {
System.out.println("Invalid input. Please use only the operators '^, *, /, +, -, (, )' and the operand digits 0-9");
invalidInput = true;
}
// checking for numbers that are not single-digit
else if (doubledigitMatcher.find()) {
System.out.println("Invalid input. Please only use single-digit numbers.");
invalidInput = true;
}
} while (invalidInput);
// converting the expression to postfix
String postexpr = in2post(expr);
// evaluating the postfix expression & printing the result
System.out.println(expr + " = " + evalpost(postexpr));
}
// method to evaluate postfix expressions
public static double evalpost(String str) {
ArrayStack stack = new ArrayStack(); // arraystack to be used during calculations
char[] chars = str.toCharArray(); // turning the str expression into a character array to make iterating over it easy
// iterating over the postfix expression
for (char c : chars) {
// if the element is an operand, pushing it to the stack
if (Character.isDigit(c)) {
stack.push(c);
}
// if the character is not a digit, then it must be an operator
// popping two operands from the stack for the operator & evaluating them, then pushing the result to the stack
else {
// converting the operands to doubles for simplicity's sake if division is encountered
// using an if statement to detect if the top is a Character or a Double.
// if it's a Character, casting to char and subtracting the value of the character '0' to get the character's numeric value
// else, casting it to double
double operand2 = stack.top() instanceof Character ? (double) ((char) stack.pop() - '0') : (double) stack.pop(); // what would normally be operand 2 in infix will be the first on the stack
double operand1 = stack.top() instanceof Character ? (double) ((char) stack.pop() - '0') : (double) stack.pop();
// switch statement on the operator to see which operator it is
// evaluating the expression and pushing the result to the stack
switch (c) {
// exponentiation
case '^':
stack.push(Math.pow(operand1, operand2));
break;
// multipication
case '*':
stack.push(operand1 * operand2);
break;
// division
case '/':
stack.push(operand1 / operand2);
break;
// addition
case '+':
stack.push(operand1 + operand2);
break;
// subtraction
case '-':
stack.push(operand1 - operand2);
break;
// printing an error and exiting with code 1 if an unknown operator is somehow encountered
default:
System.out.println("The postfix expression contained an unrecognised operator! Exiting...");
System.exit(1);
}
}
}
// returning the final answer - the number on the stack
return (double) stack.pop();
}
// method to convert infix to postfix
public static String in2post(String str) {
ArrayStack stack = new ArrayStack();
char[] chars = str.toCharArray(); // converting str to a character array to make it easier to iterate over
String output = ""; // output string to be returned
// looping through each character in the array
for (char c : chars) {
// if the scanned character is a '(', pushing it to the stack
if (c == '(') {
stack.push(c);
}
// if the scanned character is a ')', popping the stack & appending to the output until a '(' is encountered
else if (c == ')') {
while (!stack.isEmpty()) {
// if a ( is encountered, popping it & breaking
if (stack.top().equals('(')) {
stack.pop();
break;
}
// otherwise, popping the stack & appending to the output
else {
output += stack.pop();
}
}
}
// appending the character to the output string if it is an operand (digit)
else if (Character.isDigit(c)) {
output += c;
}
// if the stack is empty or contains '(' or the precedence of the scanned operator is greater than the precedence of the operator in the stack
// important that stack.isEmpty() comes first - the rest of the if condition will not be evaluated if this is true as we are using OR
// this prevents any NullPointerExceptions from being thrown if we try to access the top of an empty stack
else if (stack.isEmpty() || stack.top().equals('(') || precedence(c) > precedence((char) stack.top())) {
// pushing the scanned operator to the stack
stack.push(c);
}
else {
// popping all the operators from the stack which are >= to in precedence to that of the scanned operator & appending them to the output string
while (!stack.isEmpty() && precedence((char) stack.top()) >= precedence(c)) {
// if parenthesis is encountered, popping it, stopping, and pushing the scanned operator
if (stack.top().equals('(') || stack.top().equals(')')) {
stack.pop();
break;
}
// otherwise, popping the stack and appending to output
else {
output += stack.pop();
}
}
// after that, pushing the scanned operator to the stack
stack.push(c);
}
}
// popping and appending to output any remaining content from the stack
while (!stack.isEmpty()) {
output += stack.pop();
}
// returning the generated postfix expression
return output;
}
// method to get the precedence of each operator - the higher the returnval, the higher the precedence. -1 indicates no precedence (invalid char)
public static int precedence(char c) {
switch (c) {
// exponentiation
case '^':
return 2;
// multiplication
case '*':
return 1;
// division
case '/':
return 1;
// addition
case '+':
return 0;
// subtraction
case '-':
return 0;
// default - invalid operator
default:
return -1;
}
}
}

View File

@ -0,0 +1,15 @@
public class Test {
public static void main(String[] args) {
ArrayStack stack = new ArrayStack();
stack.push('a');
String str = "";
str += stack.top();
System.out.println(str);
char c = 'a';
if (c.equals('a')) {
System.out.println("nice");
}
}
}

View File

@ -0,0 +1,85 @@
<?xml version="1.0" standalone="yes"?>
<!-- logreq request file -->
<!-- logreq version 1.0 / dtd version 1.0 -->
<!-- Do not edit this file! -->
<!DOCTYPE requests [
<!ELEMENT requests (internal | external)*>
<!ELEMENT internal (generic, (provides | requires)*)>
<!ELEMENT external (generic, cmdline?, input?, output?, (provides | requires)*)>
<!ELEMENT cmdline (binary, (option | infile | outfile)*)>
<!ELEMENT input (file)+>
<!ELEMENT output (file)+>
<!ELEMENT provides (file)+>
<!ELEMENT requires (file)+>
<!ELEMENT generic (#PCDATA)>
<!ELEMENT binary (#PCDATA)>
<!ELEMENT option (#PCDATA)>
<!ELEMENT infile (#PCDATA)>
<!ELEMENT outfile (#PCDATA)>
<!ELEMENT file (#PCDATA)>
<!ATTLIST requests
version CDATA #REQUIRED
>
<!ATTLIST internal
package CDATA #REQUIRED
priority (9) #REQUIRED
active (0 | 1) #REQUIRED
>
<!ATTLIST external
package CDATA #REQUIRED
priority (1 | 2 | 3 | 4 | 5 | 6 | 7 | 8) #REQUIRED
active (0 | 1) #REQUIRED
>
<!ATTLIST provides
type (static | dynamic | editable) #REQUIRED
>
<!ATTLIST requires
type (static | dynamic | editable) #REQUIRED
>
<!ATTLIST file
type CDATA #IMPLIED
>
]>
<requests version="1.0">
<internal package="biblatex" priority="9" active="0">
<generic>latex</generic>
<provides type="dynamic">
<file>CT2109-Assignment-02.bcf</file>
</provides>
<requires type="dynamic">
<file>CT2109-Assignment-02.bbl</file>
</requires>
<requires type="static">
<file>blx-dm.def</file>
<file>blx-compat.def</file>
<file>biblatex.def</file>
<file>standard.bbx</file>
<file>numeric.bbx</file>
<file>numeric.cbx</file>
<file>biblatex.cfg</file>
<file>english.lbx</file>
</requires>
</internal>
<external package="biblatex" priority="5" active="0">
<generic>biber</generic>
<cmdline>
<binary>biber</binary>
<infile>CT2109-Assignment-02</infile>
</cmdline>
<input>
<file>CT2109-Assignment-02.bcf</file>
</input>
<output>
<file>CT2109-Assignment-02.bbl</file>
</output>
<provides type="dynamic">
<file>CT2109-Assignment-02.bbl</file>
</provides>
<requires type="dynamic">
<file>CT2109-Assignment-02.bcf</file>
</requires>
<requires type="editable">
<file>ecl.bib</file>
</requires>
</external>
</requests>

View File

@ -0,0 +1,229 @@
\documentclass[a4paper]{article}
\usepackage{listings}
\usepackage{xcolor}
\definecolor{codegreen}{rgb}{0,0.6,0}
\definecolor{codegray}{rgb}{0.5,0.5,0.5}
\definecolor{codeorange}{rgb}{1,0.49,0}
\definecolor{backcolour}{rgb}{0.95,0.95,0.96}
\lstdefinestyle{mystyle}{
backgroundcolor=\color{backcolour},
commentstyle=\color{codegray},
keywordstyle=\color{codeorange},
numberstyle=\tiny\color{codegray},
stringstyle=\color{codegreen},
basicstyle=\ttfamily\footnotesize,
breakatwhitespace=false,
breaklines=true,
captionpos=b,
keepspaces=true,
numbers=left,
numbersep=5pt,
showspaces=false,
showstringspaces=false,
showtabs=false,
tabsize=2,
xleftmargin=10pt,
}
\lstset{style=mystyle}
\input{head}
\begin{document}
%-------------------------------
% TITLE SECTION
%-------------------------------
\fancyhead[C]{}
\hrule \medskip % Upper rule
\begin{minipage}{0.295\textwidth}
\begin{raggedright}
\footnotesize
Andrew Hayes \hfill\\
21321503 \hfill\\
a.hayes18@nuigalway.ie
\end{raggedright}
\end{minipage}
\begin{minipage}{0.4\textwidth}
\begin{centering}
\large
CT2109 Assignment 2\\
\normalsize
\end{centering}
\end{minipage}
\begin{minipage}{0.295\textwidth}
\begin{raggedleft}
\footnotesize
\today \hfill\\
\end{raggedleft}
\end{minipage}
\medskip\hrule
\medskip
\begin{centering}
Solving Expressions in Postfix Notation Using Stacks\\
\end{centering}
\medskip\hrule
\bigskip
\section{Problem Statement}
The problem here is a reasonably basic one.
We want to create a program that allows a user to enter an arithmetic expression in conventional algebraic form (infix
notation), calculates the answer to the expression using a Stack, and displays the results to the user.
The precedence rules outlined in the assignment specification are the well-known BIMDAS (sometimes PEMDAS), meaning that
Brackets have the highest precedence, followed by Indices, followed by Multiplication \& Division, followed by Addition
\& Subtraction.
\\\\
To use a Stack to perform the calculations, the expression must first be converted from infix notation to postfix notation.
This allows a much simpler way of evaluating the expressions.
If infix was used on the stack, with one symbol per ``slot'' or index in the stack, the symbol at the top of the stack would
be an operand.
Our program would need to pop the stack several times before it could determine what it was actually supposed to do with said
operand.
If postfix notation was used, our program knows exactly what to do because the first symbol on the stack will be an operator.
When an operator is encountered, the program will know that the operator requires two operands and pop them from the stack,
avoiding any amount of guesswork or confusion that infix notation would've caused.
\section{Analysis \& Design Notes}
Firstly, we want to scan in the expression from the user using a \verb|Scanner| object and a \verb|String|.
There are some rules about valid \& invalid expressions, and if the expression is invalid, we want to prompt the user to re-enter
their expression.
The criteria for validity are as follows: the expression must be between 3 \& 20 characters, and it must only contain single
digits 1-9 and the symbols \verb|^|, \verb|*|, \verb|/|, \verb|+|, \verb|-|, \verb|(|, \& \verb|)|.
In a do-while loop, we'll prompt the user to enter an expression and scan it in.
The expression will first be checked to ensure that it is of the appropriate length.
If not, the loop will repeat.
If the expression is of the appropriate length, it will then be checked using a regular expression to see if it contains any
characters that are not the allowed characters.
If so, the loop will repeat.
If the expression does not contain any illegal characters, it will finally be checked using a regular expression to see if it
contains numbers that have two or more digits (essentially just checking if a digit is ever followed by another digit).
If so, the loop will repeat.
Otherwise, the loop will end, and the program will proceed.
\\\\
If the expression is valid, it will then be converted to postfix notation using the algorithm outlined in the assignment
specification.
The user's input String will be passed to a method that will convert it to a character array and loop over it,
implementing the algorithm as follows:
\begin{enumerate}
\item If the character is a ``\verb|(|'', it will be pushed to the stack.
\item Else, if the character is a ``\verb|)|'', a loop will be entered wherein the stack is popped and the results appended
to the output String until a ``\verb|(|'' is encountered and the stack is not empty (to prevent errors).
If a ``\verb|(|'' is encountered, it will be popped from the stack and discarded.
\item Else, if the character is a digit (operand), it will be appended to the output String.
\item Else, if the stack is empty, or contains a ``\verb|(|'', or the precedence of the scanned operator is greater than
the precedence of the operator on the stack, the scanned operator will be pushed to the stack. (We know at this point
that it is an operator, as it's not a digit).
It's important that the \verb|stack.isEmpty()| condition comes first, as if true, it will prevent the rest of the
condition being evaluated (in Java, logical OR is such that if the first part of the condition is true, Java won't bother
to evaluate the rest, as the whole condition must be true if part of it is true).
This is important because if the subsequent \verb|stack.top()| operations were called on an empty stack, an error
would occur.
\item Else, all the operators in the stack which are greater than or equal to the scanned operator will be popped from
the stack using a while loop (again, ensuring that the stack isn't empty first), and appended to the output String.
If a ``\verb|(|'' or ``\verb|)|'' is encountered while poppung, it will be popped from the stack and the loop will break.
After that, the scanned operator will be pushed to the stack.
\item Finally, any remaing content in the stack will be popped and appended to the output String, which will subsequently
be returned.
\end{enumerate}
A utility to determine the precedence of an operator will be required for the above method, so one will be implemented as a
method with the signature \verb|public static int precedence(char c)|.
This method will return an integer value; The higher the value of the returned integer, the higher the precedence of the operator
that was passed to the method.
This will be implemented with a simple \verb|switch (c)| statement, with \verb|default| returning \verb|-1| to indicate no
precedence (invalid operator).
\\\\
Once the postfix expression has been returned from the converter method in String form, it will then be passed to a method
which will convert it to a character array and will evaluate it using the algorithm outlined in the assignment specification,
which it will implement as follows, by iterating over each character in the postfix expression:
\begin{enumerate}
\item If the character is a digit (operand), it will be pushed to the stack.
\item Else, as it must be an operator, two operands will be popped from the stack to be evaluated using that operator.
We will want these operands to be \verb|double|s, as there may be division involved, and it's more simple if only
one numeric type is used.
Operand 2 will be the one above operand 1 on the stack, as the expression is in postfix, but because Java works in
infix, we will have to treat it as an infix expression.
There is some difficulty involved, as the ArrayStack contains type \verb|Object|.
These \verb|Object|s will be of two types: \verb|Character| \& \verb|Double| (autoboxed from \verb|char| \& \verb|double|).
Since we are assigning these elements from the stack to variables of type \verb|double|, we will need to cast them to type
\verb|double| first.
\\\\
If the element is an \verb|instanceof Character|, it must first be converted to a \verb|char| (unboxed) and then
the value of the \textit{character} ``\verb|0|'' subtracted from it.
This will give the numeric value of the character.
Else, the element must be of type \verb|Double| which can easily be cast to \verb|double| to unbox it.
\\\\
Finally, a \verb|switch (c)| statement will be used on the operator to determine how to evaluate it.
There will be a case for each operator, and in it, the result of operand 1 combined with operand 2 using that operator
will be pushed to the stack.
\item When each character in the character array has been looped over, the element at the top of the stack is the answer.
This will be popped, cast to type \verb|double|, and returned to be printed out \& displayed to the user.
\end{enumerate}
\section{Code}
\lstinputlisting[language=Java, breaklines=true, title={StackCalculator.java}]{../code/StackCalculator.java}
\section{Testing}
The first series of tests that we'll want to perform are testing that the program rejects invalid inputs.
The testing that it accepts valid inputs will come later.
We expect that the program will prompt us to re-enter our expression in the following circumstances:
\begin{itemize}
\item If the expression is not between 3 \& 20 characters in length.
\item If the expression entered contains a character other than the digits 0-9 and the symbols \verb|^|, \verb|*|,
\verb|/|, \verb|+|, \verb|-|, \verb|(|, \& \verb|)|.
\item If the expression contains any double-digit numbers.
\end{itemize}
The screenshots below show that the expected output for the scenarios outlined above match the real output:
\begin{figure}[h]
\centering
\includegraphics[width=0.7\textwidth]{images/illegallength.png}
\caption{Testing Expressions of Illegal Length}
\end{figure}
\begin{figure}[h]
\centering
\includegraphics[width=0.7\textwidth]{images/illegalcharacters.png}
\caption{Testing Expressions which Contain Illegal Characters}
\end{figure}
\begin{figure}[h]
\centering
\includegraphics[width=0.7\textwidth]{images/doubledigit.png}
\caption{Testing Expressions which Contain Double-Digit Numbers}
\end{figure}
Of course, the next thing that we must ensure is that the program accepts valid inputs.
However, for the sake of convenience \& concision, these tests can be bundled with tests ensuring that the calculations
work properly.
Assuming that the program passes the tests which check if the program calculates expressions correctly, then we know
that the program must also be accepting valid inputs.
\\\\
The next series of tests that we'll want to perform are checking that the program calculates the correct answer to the
expressions that are entered.
We'll want to test each operator both individually and in concert with other operators.
We expect that the program obeys the standard BIMDAS rules, and that the results match the results you would get from
any other calculator.
\begin{figure}[h]
\centering
\includegraphics[width=0.7\textwidth]{images/individualoperators.png}
\caption{Testing Each Operator Individually}
\end{figure}
\begin{figure}[h]
\centering
\includegraphics[width=0.7\textwidth]{images/inconcert.png}
\caption{Testing Combinations of Operators}
\end{figure}
These screenshots demonstrate that the program behaved as expected in each potential situation.
The program rejects invalid input, accepts valid input, and calculates the correct answer for each valid input,
regardless of which operators or which numbers are combined together.
\end{document}

View File

@ -0,0 +1,49 @@
\addtolength{\hoffset}{-2.25cm}
\addtolength{\textwidth}{4.5cm}
\addtolength{\voffset}{-3.25cm}
\addtolength{\textheight}{5cm}
\setlength{\parskip}{0pt}
\setlength{\parindent}{0in}
%----------------------------------------------------------------------------------------
% PACKAGES AND OTHER DOCUMENT CONFIGURATIONS
%----------------------------------------------------------------------------------------
\usepackage{blindtext} % Package to generate dummy text
\usepackage{charter} % Use the Charter font
\usepackage[utf8]{inputenc} % Use UTF-8 encoding
\usepackage{microtype} % Slightly tweak font spacing for aesthetics
\usepackage[english]{babel} % Language hyphenation and typographical rules
\usepackage{amsthm, amsmath, amssymb} % Mathematical typesetting
\usepackage{float} % Improved interface for floating objects
\usepackage[final, colorlinks = true,
linkcolor = black,
citecolor = black]{hyperref} % For hyperlinks in the PDF
\usepackage{graphicx, multicol} % Enhanced support for graphics
\usepackage{xcolor} % Driver-independent color extensions
\usepackage{marvosym, wasysym} % More symbols
\usepackage{rotating} % Rotation tools
\usepackage{censor} % Facilities for controlling restricted text
\usepackage{listings, style/lstlisting} % Environment for non-formatted code, !uses style file!
\usepackage{pseudocode} % Environment for specifying algorithms in a natural way
\usepackage{style/avm} % Environment for f-structures, !uses style file!
\usepackage{booktabs} % Enhances quality of tables
\usepackage{tikz-qtree} % Easy tree drawing tool
\tikzset{every tree node/.style={align=center,anchor=north},
level distance=2cm} % Configuration for q-trees
\usepackage{style/btree} % Configuration for b-trees and b+-trees, !uses style file!
\usepackage[backend=biber,style=numeric,
sorting=nyt]{biblatex} % Complete reimplementation of bibliographic facilities
\addbibresource{ecl.bib}
\usepackage{csquotes} % Context sensitive quotation facilities
\usepackage[yyyymmdd]{datetime} % Uses YEAR-MONTH-DAY format for dates
\renewcommand{\dateseparator}{-} % Sets dateseparator to '-'
\usepackage{fancyhdr} % Headers and footers
\pagestyle{fancy} % All pages have headers and footers
\fancyhead{}\renewcommand{\headrulewidth}{0pt} % Blank out the default header
\fancyfoot[L]{} % Custom footer text
\fancyfoot[C]{} % Custom footer text
\fancyfoot[R]{\thepage} % Custom footer text
\newcommand{\note}[1]{\marginpar{\scriptsize \textcolor{red}{#1}}} % Enables comments in red on margin
%----------------------------------------------------------------------------------------

Binary file not shown.

After

Width:  |  Height:  |  Size: 50 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 86 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 43 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 74 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 79 KiB

View File

@ -0,0 +1,165 @@
% avm.sty -- for attribute-value matrices -- mar 29, 1992; rev. dec 6, 1993
% (c) 1992 christopher manning (manning@csli.stanford.edu) -- see avm.doc.tex
\newif\ifavmactive\newif\ifavmsorted\newif\ifavmlabeled
\newif\ifavmcenter\newif\ifavmbottom
\newif\ifavmbottomright\newif\ifavmtopleft\newif\ifavmtopright
\newdimen\avmdimen
\newbox\avmboxone\newbox\avmboxthree
\def\avmoptions#1{\avmactivefalse\avmsortedfalse\avmlabeledfalse
\avmcenterfalse\avmbottomfalse
\avmbottomrightfalse\avmtopleftfalse\avmtoprightfalse
\def\more{#1}\ifx\more\empty\else\avmjoptions#1,\@nil\fi}
\def\avmjoptions#1,#2\@nil{\def\more{#2}\csname avm#1true\endcsname
\ifx\more\empty\else\avmjoptions#2\@nil\fi}
\def\avmfont#1{\def\avmjfont{#1}}
\def\avmjfont{}
\def\avmvalfont#1{\def\avmjvalfont{#1}}
\def\avmjvalfont{}
\def\avmsortfont#1{\def\avmjsortfont{#1}}
\def\avmjsortfont{}
\def\avmhskip#1{\def\avmjhskip{#1}}
\def\avmjhskip{1em}
\def\avmbskip#1{\def\avmjbskip{#1}}
\def\avmjbskip{0em}
\def\avmvskip#1{\def\avmjvskip{#1}}
\def\avmjvskip{0.385ex}%was .3875
\def\avmjprolog#1{$\mskip-\thinmuskip
\left#1\hskip\avmjbskip\vcenter\bgroup\vskip\avmjvskip
\ialign\bgroup\avmjfont
\strut ##\unskip\hfil
&&\hskip\avmjhskip\avmjvalfont ##\unskip\hfil\cr}
\def\avmjpostlog#1{\crcr\egroup\vskip\avmjvskip\egroup
\hskip\avmjbskip\right#1\mskip-\thinmuskip$\ignorespaces}
\def\avmjcatcode{\let\lparen=(\let\rparen=)\catcode`\[=13\catcode`\]=13
\catcode`\<=13\catcode`\@=13\catcode`\(=13\catcode`\)=13
\catcode`\>=13\catcode`\|=13}
{\avmjcatcode % new group: redefine above catcodes as active
\gdef\specialavm{\avmjcatcode
\def({\avmjprolog\lparen}%
\def){\avmjpostlog\rparen}%
\def<{\avmjprolog\langle}%
\def>{\avmjpostlog\rangle}%
\ifavmsorted
\def[##1{\setbox\avmboxthree=\hbox{\avmjsortfont##1\/}\setbox2=\hbox
\bgroup\avmjprolog\lbrack}%
\def]{\avmjpostlog\rbrack\egroup\avmjsort}%
\else\ifavmlabeled
\def[##1{\def\more{##1}\setbox2=\hbox\bgroup\avmjprolog[}%
\def]{\avmjpostlog]\egroup\node{\more}{\box2}}%
\else
\def[{\avmjprolog\lbrack}%
\def]{\avmjpostlog\rbrack}%
\fi\fi
%
\def\<{$\langle$}\def\>{$\rangle$}%
\def\({\lparen}\def\){\rparen}%
\def\[{\lbrack}\def\]{\rbrack}%
\def|{$\,\vert\,$}%
\def@##1{\avmbox{##1}}%
} % end defn of \specialavm
} % restore active catcodes
\long\def\avm{\begingroup
\ifavmactive\specialavm
\else
\def\({\avmjprolog(}%
\def\){\avmjpostlog)}%
\def\<{\avmjprolog\langle}%
\def\>{\avmjpostlog\rangle}%
%
\ifavmsorted
\def\[##1{\setbox\avmboxthree=\hbox{\avmjsortfont##1\/}\setbox
2=\hbox\bgroup\avmjprolog[}%
\def\]{\avmjpostlog]\egroup\avmjsort}%
\else\ifavmlabeled
\def\[##1{\def\more{##1}\setbox2=\hbox\bgroup\avmjprolog[}%
\def\]{\avmjpostlog]\egroup\node{\more}{\box2}}%
\else
\def\[{\avmjprolog[}%
\def\]{\avmjpostlog]}%
\fi\fi
%
\def\|{$\,\vert\,$}%
\def\@##1{\avmbox{##1}}%
\fi % end not active
%
\ifx\LaTeX\undefined\def\\{\cr}% running under TeX
\else \def\\{\@tabularcr}% Leverage off LaTeX's \\*[dimen] options
\fi
\def\!{\node}%
\long\def\avmjsort{\dimen2=\ht2\advance\dimen2 by -.25\baselineskip
\global\dimen\avmdimen=\wd\avmboxthree
\ifavmtopleft \raise\dimen2\llap{\box\avmboxthree}\box2%
\else\ifavmtopright \box2\raise\dimen2\box\avmboxthree%
\else\ifavmbottomright \box2\lower\dimen2\box\avmboxthree%
\else \lower\dimen2\llap{\box\avmboxthree}\box2%
\fi\fi\fi}%
\long\def\sort##1##2{\setbox2=\hbox{##2}\setbox
\avmboxthree=\hbox{\avmjsortfont##1\/}\dimen2=\ht2
\advance\dimen2 by -.25\baselineskip
\ifavmtopleft \raise\dimen2\box\avmboxthree\box2%
\else\ifavmtopright \box2\raise\dimen2\box\avmboxthree%
\else\ifavmbottomright \box2\lower\dimen2\box\avmboxthree%
\else \lower\dimen2\box\avmboxthree\box2%
\fi\fi\fi}%
\long\def\osort##1##2{\setbox2=\hbox{##2}\setbox
\avmboxthree=\hbox{\avmjsortfont ##1\/}\avmjsort}%
\def\avml{\avmjprolog.}%
\def\avmr{\avmjpostlog.}%
\def\avmb##1{\node{##1}{\lbrack\;\rbrack}}%
\def\avmd##1{\node{##1}{---}}%
\def\q##1{\ifx ##1\{$\lbrace$\else
\ifx ##1\}$\rbrace$\else
\ifx ##1<$\langle$\else
\ifx ##1>$\rangle$\fi \fi \fi \fi}%
\def\{{\avmjprolog\lbrace}%
\def\}{\avmjpostlog\rbrace}%
\def\;{\hskip\avmjhskip}%
\def\avmspan##1{\multispan2\strut ##1\expandafter\hfil}%
\avmjfont
\openup\avmjvskip
\setbox\avmboxone=\hbox\bgroup\ignorespaces
} % end defn of \avm
\def\endavm{\egroup\ifvmode\leavevmode\fi % this if is useful!
\ifavmsorted\null\hskip\dimen\avmdimen\fi
\ifavmcenter
\box\avmboxone
\else \ifavmbottom
\lower.575\baselineskip\hbox{\vbox{\box\avmboxone\null}}%
\else
% the next bit is ripped off from Emma's \evnup in lingmacros.sty
\dimen2=\ht\avmboxone\advance\dimen2 by -.725\baselineskip
\lower\dimen2\box\avmboxone
\fi \fi \endgroup}
% based on TeXbook exercise 21.3
\def\avmbox#1{\setbox2=\hbox{$\scriptstyle #1$}\lower.2ex\vbox{\hrule
\hbox{\vrule\kern1.25pt
\vbox{\kern1.25pt\box2\kern1.25pt}\kern1.25pt\vrule}\hrule}}
% ============ COSTOM CONFIGURATION =============
\avmfont{\sc}
\avmoptions{sorted,active}
\avmvalfont{\rm}
\avmsortfont{\scriptsize\it}
% ===============================================

View File

@ -0,0 +1,131 @@
%% Last Modified: Thu Oct 18 18:26:25 2007.
\NeedsTeXFormat{LaTeX2e}
\ProvidesPackage{style/btree}
\typeout{Document Style `weiw_BTree - Support drawing B+-Tree (ver 0.999)}
\RequirePackage{tikz}
\RequirePackage{ifthen}
% use libraries
\usetikzlibrary{arrows,shapes,decorations,matrix}
%% global declaration
\tikzstyle{btreeptr} = [draw, semithick, minimum height=2em]
\tikzstyle{btreeval} = [draw, semithick, minimum size=2em]
\tikzstyle{btreevale} = [draw,semithick, minimum size=2em]
\tikzstyle{btlink} = [draw, semithick, ->, >=triangle 45]
%% macro
%% helper macros
\newcommand{\suppressemptystr}[1]{% leave blank for entries in leaf nodes
\ifthenelse{\equal{#1}{}}%
{%
\relax%
}%
% Else
{%
#1\textsuperscript{*}%
}%
}%
\newcommand{\xyshift}[3]{% help to place the nodes
\begin{scope}[xshift=#1, yshift=#2]
#3
\end{scope}%
}
%% Common btree macros
\newcommand{\btreelink}[2]{% #1: src node; #2: dest node;
\draw[btlink] ([yshift=3pt] #1.south) -- (#2-b.north);
}
\newcommand{\btreelinknorth}[2]{% #1: src node; #2: dest node;
\draw[btlink] ([yshift=3pt] #1.south) -- (#2.north);
}
\newcommand{\btreetriangle}[2]{% #1: node name; #2 text inside
\node[anchor=north, regular polygon, regular polygon sides=3, draw] (#1) {#2};
}
%%======================================================================
%% btree with capacity = 4
\newcommand{\btreeinodefour}[5]{%
\matrix [ampersand replacement=\&] (#1)
{
\node[btreeptr] (#1-1) {\vphantom{1}}; \& \node[btreeval] (#1-a) {#2}; \&
\node[btreeptr] (#1-2) {\vphantom{1}}; \& \node[btreeval] (#1-b) {#3}; \&
\node[btreeptr] (#1-3) {\vphantom{1}}; \& \node[btreeval] (#1-c) {#4}; \&
\node[btreeptr] (#1-4) {\vphantom{1}}; \& \node[btreeval] (#1-d) {#5}; \&
\node[btreeptr] (#1-5) {\vphantom{1}}; \\
};
}
\newcommand{\btreelnodefour}[5]{%
\matrix [ampersand replacement=\&, outer sep=0pt, matrix anchor=north] (#1)
{
\node[btreevale] (#1-a) {\suppressemptystr{#2}}; \&
\node[btreevale] (#1-b) {\suppressemptystr{#3}}; \&
\node[btreevale] (#1-c) {\suppressemptystr{#4}}; \&
\node[btreevale] (#1-d) {\suppressemptystr{#5}}; \\
};
}
%%======================================================================
%% btree with capacity = 3
\newcommand{\btreeinodethree}[4]{%
\matrix [ampersand replacement=\&] (#1)
{
\node[btreeptr] (#1-1) {\vphantom{1}}; \& \node[btreeval] (#1-a) {#2}; \&
\node[btreeptr] (#1-2) {\vphantom{1}}; \& \node[btreeval] (#1-b) {#3}; \&
\node[btreeptr] (#1-3) {\vphantom{1}}; \& \node[btreeval] (#1-c) {#4}; \&
\node[btreeptr] (#1-4) {\vphantom{1}}; \\
};
}
\newcommand{\btreelnodethree}[4]{%
\matrix [ampersand replacement=\&, outer sep=0pt, matrix anchor=north] (#1)
{
\node[btreevale] (#1-a) {\suppressemptystr{#2}}; \&
\node[btreevale] (#1-b) {\suppressemptystr{#3}}; \&
\node[btreevale] (#1-c) {\suppressemptystr{#4}}; \\
};
}
%%======================================================================
%% btree with capacity = 2
\newcommand{\btreeinodetwo}[4]{%
\matrix [ampersand replacement=\&] (#1)
{
\node[btreeptr] (#1-1) {\vphantom{1}}; \& \node[btreeval] (#1-a) {#2}; \&
\node[btreeptr] (#1-2) {\vphantom{1}}; \& \node[btreeval] (#1-b) {#3}; \&
\node[btreeptr] (#1-3) {\vphantom{1}}; \\
};
}
\newcommand{\btreelnodetwo}[3]{%
\matrix [ampersand replacement=\&, outer sep=0pt, matrix anchor=north] (#1)
{
\node[btreevale] (#1-a) {\suppressemptystr{#2}}; \&
\node[btreevale] (#1-b) {\suppressemptystr{#3}}; \\
};
}
%%======================================================================
%% simple example
% \begin{center}
% \scalebox{0.7}{
% \begin{tikzpicture}
% %
% \btreeinodefour{root}{13}{17}{24}{30};
% \xyshift{-40mm}{-20mm}{\btreelnodefour{n1}{2}{3}{5}{7}}
% \xyshift{-0mm}{-20mm}{\btreelnodefour{n2}{14}{16}{}{}}
% \xyshift{40mm}{-20mm}{\btreelnodefour{n3}{19}{20}{22}{}}
% \xyshift{80mm}{-20mm}{\btreelnodefour{n4}{24}{27}{29}{}}
% \xyshift{120mm}{-20mm}{\btreelnodefour{n5}{33}{34}{38}{39}}
% %
% \foreach \x in {1,2,...,5} { \btreelink{root-\x}{n\x} }
% \end{tikzpicture}
% }
% \end{center}

Binary file not shown.

After

Width:  |  Height:  |  Size: 66 KiB

View File

@ -0,0 +1,38 @@
% Source: ss17_wissschreib (Eva)
\lstset{
basicstyle=\ttfamily\scriptsize\mdseries,
keywordstyle=\bfseries\color[rgb]{0.171875, 0.242188, 0.3125},
identifierstyle=,
commentstyle=\color[rgb]{0.257813, 0.15625, 0},
stringstyle=\itshape\color[rgb]{0.0195313, 0.195313, 0.0117188},
numbers=left,
numberstyle=\tiny,
stepnumber=1,
breaklines=true,
frame=none,
showstringspaces=false,
tabsize=4,
backgroundcolor=\color[rgb]{0.98,0.98,0.98},
captionpos=b,
float=htbp,
language=Python,
xleftmargin=15pt,
xrightmargin=15pt
}
%(deutsche) Sonderzeichen
\lstset{literate=%
{Ä}{{\"A}}1
{Ö}{{\"O}}1
{Ü}{{\"U}}1
{ä}{{\"a}}1
{ö}{{\"o}}1
{ü}{{\"u}}1
{ß}{{\ss}}1
}
%Verwendung im Text:
%-> \begin{lstlisting}[language=Python,firstnumber=27] ... \end{lstlisting}
%-> \begin{lstlisting}[language=Python,numbers=none] ... \end{lstlisting}
%-> \lstinline[language=JAVA]{...}

View File

@ -0,0 +1,69 @@
import javax.swing.JOptionPane;
/**
* Array implementation of Queue ADT
*/
public class ArrayQueue implements Queue
{
protected Object Q[]; // array used to implement the queue
protected int rear = -1; // index for the rear of the queue
protected int capacity; // The actual capacity of the queue array
public static final int CAPACITY = 1000; // default array capacity
public ArrayQueue() {
// default constructor: creates queue with default capacity
this(CAPACITY);
}
public ArrayQueue(int cap) {
// this constructor allows you to specify capacity
capacity = (cap > 0) ? cap : CAPACITY;
Q = new Object[capacity];
}
public void enqueue(Object n)
{
if (isFull()) {
JOptionPane.showMessageDialog(null, "Cannot enqueue object; queue is full.");
return;
}
rear++;
Q[rear] = n;
}
public Object dequeue()
{
// Can't do anything if it's empty
if (isEmpty())
return null;
Object toReturn = Q[0];
// shuffle all other objects towards 0
int i = 1;
while (i <= rear) {
Q[i-1] = Q[i];
i++;
}
rear--;
return toReturn;
}
public boolean isEmpty() {
return (rear < 0);
}
public boolean isFull() {
return (rear == capacity-1);
}
public Object front()
{
if (isEmpty())
return null;
return Q[0];
}
}

View File

@ -0,0 +1,63 @@
/** Array implementation of Stack ADT */
import javax.swing.JOptionPane;
public class ArrayStack implements Stack
{
protected int capacity; // The actual capacity of the stack array
protected static final int CAPACITY = 1000; // default array capacity
protected Object S[]; // array used to implement the stack
protected int top = -1; // index for the top of the stack
public ArrayStack() {
// default constructor: creates stack with default capacity
this(CAPACITY);
}
public ArrayStack(int cap) {
// this constructor allows you to specify capacity of stack
capacity = (cap > 0) ? cap : CAPACITY;
S = new Object[capacity];
}
public void push(Object element) {
if (isFull()) {
JOptionPane.showMessageDialog(null, "ERROR: Stack is full.");
return;
}
top++;
S[top] = element;
}
public Object pop() {
Object element;
if (isEmpty()) {
JOptionPane.showMessageDialog(null, "ERROR: Stack is empty.");
return null;
}
element = S[top];
S[top] = null;
top--;
return element;
}
public Object top() {
if (isEmpty()) {
JOptionPane.showMessageDialog(null, "ERROR: Stack is empty.");
return null;
}
return S[top];
}
public boolean isEmpty() {
return (top < 0);
}
public boolean isFull() {
return (top == capacity-1);
}
public int size() {
return (top + 1);
}
}

View File

@ -0,0 +1,21 @@
// class to implement Method 2
public class IVersusNMinusI implements PalindromeChecker {
// method 2 - comparing each element at index i to the element at n - i where n is the last index
@Override
public boolean checkPalindrome(String str) {
// looping through the first half of the String
NewPalindrome.operations[1]++;
for (int i = 0; i < Math.floor(str.length() / 2); i++) {
NewPalindrome.operations[1] += 1 + 1 + 1 + 1; // 1 for the getting str.length(), 1 for Math,floor, 1 for checking condition, 1 for incrementing
// returning false if the digits don't match
NewPalindrome.operations[1] += 1 + 1 + 1 + 1; // 1 for str.charAt(i), 1 for ((str.lenght() -1) - 1), 1 for the other str.charAt(), 1 for checking the condition
if (str.charAt(i) != str.charAt((str.length()-1) - i)) {
return false;
}
}
// returning true as default
return true;
}
}

View File

@ -0,0 +1,93 @@
import java.io.*;
public class NewPalindrome {
public static long[] operations = new long[4]; // array to contain the global operations count for each method
public static int[] decCount = new int[4]; // array to hold the count of decimal palindromes found using each method
public static int[] binCount = new int[4]; // array to hold the count of binary palindromes found using each method
public static int[] bothCount = new int[4]; // array to hold the count of numbers that are palindromes in both decimal & binary found using each method
public static long[] startTime = new long[4]; // array to hold the start time of each method's test loop
public static long[] totalTime = new long[4]; // array to hold the total time of each method's test loop
// array to hold all the String versions of the numbers so that they don't have to be generated for each method
// 0th column will be decimal, 1st column will be binary
public static String[][] strings = new String[1_000_001][2];
// array of StringBuilder objects used to hold the csv data (size of problem, number of operations) for each method
public static StringBuilder[] data = new StringBuilder[4];
// array of the four classes that will be tested
public static PalindromeChecker[] palindromeCheckers = {new ReverseVSOriginal(), new IVersusNMinusI(), new StackVSQueue(), new RecursiveReverse()};
public static void main(String args[]) {
// initialising the data array to StringBuilder objects
for (int i = 0; i < 4; i++) {
data[i] = new StringBuilder("operations,size\n");
}
// filling up the strings array
for (int i = 0; i <= 1_000_000; i++) {
strings[i][0] = Integer.toString(i, 10); // converting i to a String base 10
strings[i][1] = binary2string(strings[i][0]); // converting the decimal String to a binary String
}
// looping through each PalindromeChecker object in the palindromeCheckers array
for (int j = 0; j < 4; j++) {
// getting start time
startTime[j] = System.currentTimeMillis(); operations[j]++;
// looping through the numbers 0 to 1,000,000 and checking if their binary & decimal representations are palindromic
operations[j]++;
for (int i = 0; i <= 1_000_000; i++) {
// incrementing the operations count by 2, 1 for the loop condition check and 1 for incrementing i
operations[j] += 2;
// converting the number to a decimal or binary String and checking if is a palindrome
boolean isDecPalindrome = palindromeCheckers[j].checkPalindrome(strings[i][0]); operations[j]++;
boolean isBinPalindrome = palindromeCheckers[j].checkPalindrome(strings[i][1]); operations[j]++;
// incrementing the appropriate counter if the number is a palindrome in that base
decCount[j] = isDecPalindrome ? decCount[j] + 1 : decCount[j]; operations[j] += 1 + 1; // incremnting by 2, 1 for assignment, 1 for condition check
binCount[j] = isBinPalindrome ? binCount[j] + 1 : binCount[j]; operations[j] += 1 + 1;
bothCount[j] = isDecPalindrome && isBinPalindrome ? bothCount[j] + 1 : bothCount[j]; operations[j] += 1 + 1 +1; // 2 condition checks and one assignment, so incrementing by 3
// appending to the data StringBuilder at intervals of 50,000
if (i % 50_000 == 0) {
data[j].append(operations[j] + "," + i + "\n");
}
}
// calculating total time taken for method 1 and printing out the results
totalTime[j] = System.currentTimeMillis() - startTime[j]; operations[j] += 1 + 1; // incrementing by 2, 1 for getting current time and subtracting start time, 1 for assignment
System.out.println("Number of decimal palindromes found using Method " + j + ": " + decCount[j]);
System.out.println("Number of binary palindromes found using Method " + j + ": " + binCount[j]);
System.out.println("Number of palindromes in both decimal & binary found using Method " + j + ": " + bothCount[j]);
System.out.println("Number of primitive operations taken in Method " + j + ": " + operations[j]);
System.out.println("Time taken for Method " + j + ": " + totalTime[j] + " milliseconds");
System.out.println();
// outputting the data to separate csv files
try {
String filename = "method" + j + ".csv";
File csv = new File(filename);
// creating file if it doesn't already exist
csv.createNewFile();
FileWriter writer = new FileWriter(filename);
writer.write(data[j].toString());
writer.close();
} catch (IOException e) {
System.out.println("IO Error occurred");
e.printStackTrace();
System.exit(1);
}
}
}
// utility method to convert a decimal String to its equivalent binary String
public static String binary2string(String decimalStr) {
return Integer.toString(Integer.parseInt(decimalStr), 2); // parsing the String to an int and then parsing that int to a binary String
}
}

View File

@ -0,0 +1,320 @@
import java.io.*;
public class Palindrome {
// global operations count for each method
public static long operations1 = 0;
public static long operations2 = 0;
public static long operations3 = 0;
public static long operations4 = 0;
// String objects used to hold the csv data (size of problem, number of operations) for each method
public static StringBuilder data1 = new StringBuilder("operations,size\n");
public static StringBuilder data2 = new StringBuilder("operations,size\n");
public static StringBuilder data3 = new StringBuilder("operations,size\n");
public static StringBuilder data4 = new StringBuilder("operations,size\n");
public static void main(String args[]) {
// generating all the String versions of the numbers so that they don't have to be generated for each method
// 0th column will be decimal, 1st column will be binary
String[][] strings = new String[1_000_001][2];
for (int i = 0; i <= 1_000_000; i++) {
strings[i][0] = Integer.toString(i, 10); // converting i to a String base 10
strings[i][1] = binary2string(strings[i][0]); // converting the decimal String to a binary String
}
// variables for method 1 - reversed order String vs original String
int decCount1 = 0; operations1++; // count of decimal palindromes for use by method 1
int binCount1 = 0; operations1++; // count of binary palindromes for use by method 1
int bothCount1 = 0; operations1++; // count of numbers that are palindromic in both binary & decimal for use by method 1
long startTime1 = System.currentTimeMillis(); operations1 += 1 + 1;
// testing method 1 - reversed order String vs original String
// incrementing the operations counter for the initialisation of i below
operations1++;
for (int i = 0; i <= 1_000_000; i++) {
// incrementing the operations count by 2, 1 for the loop condition check and 1 for incrementing i
operations1 += 2;
// converting the number to a decimal or binary String and checking if is a palindrome
boolean isDecPalindrome = reverseVSoriginal(strings[i][0]); operations1++;
boolean isBinPalindrome = reverseVSoriginal(strings[i][1]); operations1++;
// incrementing the appropriate counter if the number is a palindrome in that base
decCount1 = isDecPalindrome ? decCount1 + 1 : decCount1; operations1 += 1 + 1; // incremnting by 2, 1 for assignment, 1 for condition check
binCount1 = isBinPalindrome ? binCount1 + 1 : binCount1; operations1 += 1 + 1;
bothCount1 = isDecPalindrome && isBinPalindrome ? bothCount1 + 1 : bothCount1; operations1 += 1 + 1 +1; // 2 condition checks and one assignment, so incrementing by 3
// appending to the data StringBuilder at intervals of 50,000
if (i % 50_000 == 0) {
data1.append(operations1 + "," + i + "\n");
}
}
// calculating total time taken for method 1 and printing out the results
long totalTime1 = System.currentTimeMillis() - startTime1; operations1 += 1 + 1; // incrementing by 2, 1 for getting current time and subtracting start time, 1 for assignment
System.out.println("Number of decimal palindromes found using Method 1: " + decCount1);
System.out.println("Number of binary palindromes found using Method 1: " + binCount1);
System.out.println("Number of palindromes in both decimal & binary found using Method 1: " + bothCount1);
System.out.println("Number of primitive operations taken in Method 1: " + operations1);
System.out.println("Time taken for Method 1: " + totalTime1 + " milliseconds");
// variables for method 2 - comparing each element at index i to the element at n - i where n is the last index
int decCount2 = 0; operations2++; // count of decimal palindromes for use by method 2
int binCount2 = 0; operations2++; // count of binary palindromes for use by method 2
int bothCount2 = 0; operations2++; // count of numbers that are palindromic in both binary & decimal for use by method 2
long startTime2 = System.currentTimeMillis(); operations2 += 1 + 1;
// testingmethod 2 - comparing each element at index i to the element at n - i where n is the last index
operations2++;
for (int i = 0; i <= 1_000_000; i++) {
operations2 += 1 + 1;
// converting the number to a decimal or binary String and checking if is a palindrome
boolean isDecPalindrome = iVSiMinusn(strings[i][0]); operations2++;
boolean isBinPalindrome = iVSiMinusn(strings[i][1]); operations2++;
// incrementing the appropriate counter if the number is a palindrome in that base
decCount2 = isDecPalindrome ? decCount2 + 1 : decCount2; operations2 += 1 + 1;
binCount2 = isBinPalindrome ? binCount2 + 1 : binCount2; operations2 += 1 + 1;
bothCount2 = isDecPalindrome && isBinPalindrome ? bothCount2 + 1 : bothCount2; operations2 += 1 + 1 +1;
// appending to the data StringBuilder at intervals of 50,000
if (i % 50_000 == 0) {
data2.append(operations2 + "," + i + "\n");
}
}
// calculating total time taken for method 2 and printing out the results
long totalTime2 = System.currentTimeMillis() - startTime2; operations2 += 1 + 1;
System.out.println();
System.out.println("Number of decimal palindromes found using Method 2: " + decCount2);
System.out.println("Number of binary palindromes found using Method 2: " + binCount2);
System.out.println("Number of palindromes in both decimal & binary found using Method 2: " + bothCount2);
System.out.println("Number of primitive operations taken in Method 2: " + operations2);
System.out.println("Time taken for Method 2: " + totalTime2 + " milliseconds");
// variables for method 3 - comparing each element at index i to the element at n - i where n is the last index
int decCount3 = 0; operations3++; // count of decimal palindromes for use by method 3
int binCount3 = 0; operations3++; // count of binary palindromes for use by method 3
int bothCount3 = 0; operations3++; // count of numbers that are palindromic in both binary & decimal for use by method 3
long startTime3 = System.currentTimeMillis(); operations3 += 1 + 1;
// testingmethod 3 - comparing each element at index i to the element at n - i where n is the last index
operations3++;
for (int i = 0; i <= 1_000_000; i++) {
operations3 += 1 + 1;
// converting the number to a decimal or binary String and checking if is a palindrome
boolean isDecPalindrome = stackVsqueue(strings[i][0]); operations3++;
boolean isBinPalindrome = stackVsqueue(strings[i][1]); operations3++;
// incrementing the appropriate counter if the number is a palindrome in that base
decCount3 = isDecPalindrome ? decCount3 + 1 : decCount3; operations3 += 1 + 1;
binCount3 = isBinPalindrome ? binCount3 + 1 : binCount3; operations3 += 1 + 1;
bothCount3 = isDecPalindrome && isBinPalindrome ? bothCount3 + 1 : bothCount3; operations3 += 1 + 1 + 1;
// appending to the data StringBuilder at intervals of 50,000
if (i % 50_000 == 0) {
data3.append(operations3 + "," + i + "\n");
}
}
// calculating total time taken for method 3 and printing out the results
long totalTime3 = System.currentTimeMillis() - startTime3; operations3 += 1 + 1;
System.out.println();
System.out.println("Number of decimal palindromes found using Method 3: " + decCount3);
System.out.println("Number of binary palindromes found using Method 3: " + binCount3);
System.out.println("Number of palindromes in both decimal & binary found using Method 3: " + bothCount3);
System.out.println("Number of primitive operations taken in Method 3: " + operations3);
System.out.println("Time taken for Method 3: " + totalTime3 + " milliseconds");
// variables for method 4 - comparing each element at index i to the element at n - i where n is the last index
int decCount4 = 0; operations4++; // count of decimal palindromes for use by method 4
int binCount4 = 0; operations4++; // count of binary palindromes for use by method 4
int bothCount4 = 0; operations4++; // count of numbers that are palindromic in both binary & decimal for use by method 4
long startTime4 = System.currentTimeMillis(); operations4 += 1 + 1;
// testingmethod 4 - comparing each element at index i to the element at n - i where n is the last index
operations4++;
for (int i = 0; i <= 1_000_000; i++) {
operations4 += 2;
// converting the number to a decimal or binary String and checking if is a palindrome
boolean isDecPalindrome = recursiveReverseVSoriginal(strings[i][0]); operations4++;
boolean isBinPalindrome = recursiveReverseVSoriginal(strings[i][1]); operations4++;
// incrementing the appropriate counter if the number is a palindrome in that base
decCount4 = isDecPalindrome ? decCount4 + 1 : decCount4; operations4 += 1 + 1;
binCount4 = isBinPalindrome ? binCount4 + 1 : binCount4; operations4 += 1 + 1;
bothCount4 = isDecPalindrome && isBinPalindrome ? bothCount4 + 1 : bothCount4; operations4 += 1 + 1 + 1;
// appending to the data StringBuilder at intervals of 50,000
if (i % 50_000 == 0) {
data4.append(operations4 + "," + i + "\n");
}
}
// calculating total time taken for method 4 and printing out the results
long totalTime4 = System.currentTimeMillis() - startTime4; operations4 += 1 + 1;
System.out.println();
System.out.println("Number of decimal palindromes found using Method 4: " + decCount4);
System.out.println("Number of binary palindromes found using Method 4: " + binCount4);
System.out.println("Number of palindromes in both decimal & binary found using Method 4: " + bothCount4);
System.out.println("Number of primitive operations taken in Method 4: " + operations4);
System.out.println("Time taken for Method 4: " + totalTime4 + " milliseconds");
// outputting the data to separate csv files
try {
File csv1 = new File("method1.csv");
File csv2 = new File("method2.csv");
File csv3 = new File("method3.csv");
File csv4 = new File("method4.csv");
// creating files if they don't already exist
csv1.createNewFile();
csv2.createNewFile();
csv3.createNewFile();
csv4.createNewFile();
FileWriter writer1 = new FileWriter("method1.csv");
writer1.write(data1.toString());
writer1.close();
FileWriter writer2 = new FileWriter("method2.csv");
writer2.write(data2.toString());
writer2.close();
FileWriter writer3 = new FileWriter("method3.csv");
writer3.write(data3.toString());
writer3.close();
FileWriter writer4 = new FileWriter("method4.csv");
writer4.write(data4.toString());
writer4.close();
} catch (IOException e) {
System.out.println("IO Error occurred");
e.printStackTrace();
System.exit(1);
}
}
// method 1 - reversed order String vs original String
public static boolean reverseVSoriginal(String str) {
String reversedStr = ""; operations1++;
// looping through each character in the String, backwards
// incrementing operations counter by 2, 1 for initialisating i, 1 for getting str.length()
operations1 += 1 + 1;
for (int i = str.length(); i > 0; i--) {
operations1 += 1 + 1; // for loop condition check & incrementing i
reversedStr += str.charAt(i-1); operations1 += 1 + 1;
}
// returning true if the Strings are equal, false if not
operations1 += str.length(); // the equals method must loop through each character of the String to check that they are equal so it is O(n)
return str.equals(reversedStr);
}
// method 2 - comparing each element at index i to the element at n - i where n is the last index
public static boolean iVSiMinusn(String str) {
// looping through the first half of the String
operations2++;
for (int i = 0; i < Math.floor(str.length() / 2); i++) {
operations2 += 1 + 1 + 1 + 1; // 1 for the getting str.length(), 1 for Math,floor, 1 for checking condition, 1 for incrementing
// returning false if the digits don't match
operations2 += 1 + 1 + 1 + 1; // 1 for str.charAt(i), 1 for ((str.lenght() -1) - 1), 1 for the other str.charAt(), 1 for checking the condition
if (str.charAt(i) != str.charAt((str.length()-1) - i)) {
return false;
}
}
// returning true as default
return true;
}
// method 3 - using a stack and a queue to do, essentially, what method 2 does
public static boolean stackVsqueue(String str) {
ArrayStack stack = new ArrayStack(); operations3 += 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1;
ArrayQueue queue = new ArrayQueue(); operations3 += 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1;
// looping through each character in the String and adding the character to the stack & queue
operations3++;
for (int i = 0; i < str.length(); i++) {
operations3 += 1 + 1 + 1;
stack.push(str.charAt(i)); operations3 += 1 + 1 + 1 + 1;
queue.enqueue(str.charAt(i)); operations3 += 1 + 1 + 1 + 1;
}
// looping through each character on the stack & queue and comparing them, returning false if they're different
operations3++;
for (int i = 0; i < str.length(); i++) {
operations3 += 1 + 1 + 1;
operations3 += 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1;
if (!stack.pop().equals(queue.front())) {
return false;
}
// the complexity of ArrayQueue.dequeue() is 3n+2, where n is the number of items in the queue when dequeue() is called.
// we need to determine the number of items in the queue so that we can determine the number of primitive operations performed when queue.dequeue() is called.
// to do this, we'll loop through the queue, dequeuing each object and enqueueing it in another ArrayQueue. once complete, we'll reassign the variable queue to point to the new ArrayQueue containing all the objects
ArrayQueue newQueue = new ArrayQueue(); // not counting the operations for this as it's not part of the algorithm, it's part of the operations counting
int n = 0; // n is the number of items in the ArrayQueue when dequeue() is called
while (!queue.isEmpty()) {
newQueue.enqueue(queue.dequeue());
n++;
}
queue = newQueue; // setting queue to point to the newQueue, which is just the state that queue would have been in if we didn't do this to calculate the primitive operations
newQueue = null; // don't need the newQueue object reference anymore
operations3 += 3*n + 2; // complexity of dequeue is 3n+2
queue.dequeue();
}
return true;
}
// method 4 - comparing the String reversed using recursion to the original String (essentially method 1 but with recursion)
public static boolean recursiveReverseVSoriginal(String str) {
// returning true if the original String is equal to the reversed String, false if not
operations4++;
return str.equals(reverse(str));
}
// method to reverse the characters in a String using recursion
public static String reverse(String str) {
// base case - returning an empty String if there is no character left in the String
operations4++;
if (str.length() == 0) {
return "";
}
else {
char firstChar = str.charAt(0); operations4 += 1 + 1;
String remainder = str.substring(1); operations4 += 1 + 1; // selecting the rest of the String, excluding the 0th character
// recursing with what's left of the String
String reversedRemainder = reverse(remainder); operations4++;
// returning the reversed rest of String with the first character of the String appended
return reversedRemainder + firstChar;
}
}
// utility method to convert a decimal String to its equivalent binary String
public static String binary2string(String decimalStr) {
return Integer.toString(Integer.parseInt(decimalStr), 2); // parsing the String to an int and then parsing that int to a binary String
}
}

View File

@ -0,0 +1,3 @@
public interface PalindromeChecker {
public boolean checkPalindrome(String str);
}

View File

@ -0,0 +1,14 @@
/*
* Abstract Queue interface
*/
public interface Queue {
// most important methods
public void enqueue(Object n); // add an object at the rear of the queue
public Object dequeue(); // remove an object from the front of the queue
// others
public boolean isEmpty(); // true if queue is empty
public boolean isFull(); // true if queue is full (if it has limited storage)
public Object front(); // examine front object on queue without removing it
}

View File

@ -0,0 +1,29 @@
// class to implement method 4
public class RecursiveReverse implements PalindromeChecker {
// comparing the String reversed using recursion to the original String (essentially method 1 but with recursion)
@Override
public boolean checkPalindrome(String str) {
// returning true if the original String is equal to the reversed String, false if not
NewPalindrome.operations[3]++;
return str.equals(reverse(str));
}
// method to reverse the characters in a String using recursion
public static String reverse(String str) {
// base case - returning an empty String if there is no character left in the String
NewPalindrome.operations[3]++;
if (str.length() == 0) {
return "";
}
else {
char firstChar = str.charAt(0); NewPalindrome.operations[3] += 1 + 1;
String remainder = str.substring(1); NewPalindrome.operations[3] += 1 + 1; // selecting the rest of the String, excluding the 0th character
// recursing with what's left of the String
String reversedRemainder = reverse(remainder); NewPalindrome.operations[3]++;
// returning the reversed rest of String with the first character of the String appended
return reversedRemainder + firstChar;
}
}
}

View File

@ -0,0 +1,21 @@
// class to implement Method 3
public class ReverseVSOriginal implements PalindromeChecker {
// method 1 - reversed order String vs original String
@Override
public boolean checkPalindrome(String str) {
String reversedStr = ""; NewPalindrome.operations[0]++;
// looping through each character in the String, backwards
// incrementing operations counter by 2, 1 for initialisating i, 1 for getting str.length()
NewPalindrome.operations[0] += 1 + 1;
for (int i = str.length(); i > 0; i--) {
NewPalindrome.operations[0] += 1 + 1; // for loop condition check & incrementing i
reversedStr += str.charAt(i-1); NewPalindrome.operations[0] += 1 + 1;
}
// returning true if the Strings are equal, false if not
NewPalindrome.operations[0] += str.length(); // the equals method must loop through each character of the String to check that they are equal so it is O(n)
return str.equals(reversedStr);
}
}

View File

@ -0,0 +1,13 @@
/** Abstract Stack interface */
public interface Stack
{
// most important methods
public void push(Object n); // push an object onto top of the stack
public Object pop(); // pop an object from top of the stack
// others
public Object top(); // examine top object on stack without removing it
public boolean isEmpty(); // true if stack is empty
public boolean isFull(); // true if stack is full (if it has limited storage)
}

View File

@ -0,0 +1,48 @@
// class to implement method 3
public class StackVSQueue implements PalindromeChecker {
// method 3 - using a stack and a queue to do, essentially, what method 2 does (compare the first index to the last index, etc.)
@Override
public boolean checkPalindrome(String str) {
ArrayStack stack = new ArrayStack(); NewPalindrome.operations[2] += 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1;
ArrayQueue queue = new ArrayQueue(); NewPalindrome.operations[2] += 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1;
// looping through each character in the String and adding the character to the stack & queue
NewPalindrome.operations[2]++;
for (int i = 0; i < str.length(); i++) {
NewPalindrome.operations[2] += 1 + 1 + 1;
stack.push(str.charAt(i)); NewPalindrome.operations[2] += 1 + 1 + 1 + 1;
queue.enqueue(str.charAt(i)); NewPalindrome.operations[2] += 1 + 1 + 1 + 1;
}
// looping through each character on the stack & queue and comparing them, returning false if they're different
NewPalindrome.operations[2]++;
for (int i = 0; i < str.length(); i++) {
NewPalindrome.operations[2] += 1 + 1 + 1;
NewPalindrome.operations[2] += 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1;
if (!stack.pop().equals(queue.front())) {
return false;
}
// the complexity of ArrayQueue.dequeue() is 3n+2, where n is the number of items in the queue when dequeue() is called.
// we need to determine the number of items in the queue so that we can determine the number of primitive operations performed when queue.dequeue() is called.
// to do this, we'll loop through the queue, dequeuing each object and enqueueing it in another ArrayQueue. once complete, we'll reassign the variable queue to point to the new ArrayQueue containing all the objects
ArrayQueue newQueue = new ArrayQueue(); // not counting the operations for this as it's not part of the algorithm, it's part of the operations counting
int n = 0; // n is the number of items in the ArrayQueue when dequeue() is called
while (!queue.isEmpty()) {
newQueue.enqueue(queue.dequeue());
n++;
}
queue = newQueue; // setting queue to point to the newQueue, which is just the state that queue would have been in if we didn't do this to calculate the primitive operations
newQueue = null; // don't need the newQueue object reference anymore
NewPalindrome.operations[2] += 3*n + 2; // complexity of dequeue is 3n+2
queue.dequeue();
}
return true;
}
}

View File

@ -0,0 +1,14 @@
public class Test {
public static void main(String[] args) {
String str = "1234567890";
ArrayQueue queue = new ArrayQueue();
for (int i = 0; i < str.length(); i++) {
queue.enqueue(str.charAt(i));
}
for (int i = 0; i < str.length(); i++) {
queue.dequeue();
}
}
}

View File

@ -0,0 +1,22 @@
operations,size
29,0
5716904,50000
11989234,100000
18683879,150000
25533879,200000
32383879,250000
39423164,300000
46523164,350000
53623164,400000
60723164,450000
67823164,500000
75051729,550000
82401729,600000
89751729,650000
97101729,700000
104451729,750000
111801729,800000
119151729,850000
126501729,900000
133851729,950000
141201734,1000000
1 operations size
2 29 0
3 5716904 50000
4 11989234 100000
5 18683879 150000
6 25533879 200000
7 32383879 250000
8 39423164 300000
9 46523164 350000
10 53623164 400000
11 60723164 450000
12 67823164 500000
13 75051729 550000
14 82401729 600000
15 89751729 650000
16 97101729 700000
17 104451729 750000
18 111801729 800000
19 119151729 850000
20 126501729 900000
21 133851729 950000
22 141201734 1000000

View File

@ -0,0 +1,22 @@
operations,size
15,0
1881959,50000
3768823,100000
5660295,150000
7552719,200000
9445167,250000
11337607,300000
13230031,350000
15122471,400000
17014895,450000
18907343,500000
20800207,550000
22693407,600000
24586615,650000
26479855,700000
28373063,750000
30266287,800000
32159487,850000
34052711,900000
35945943,950000
37839175,1000000
1 operations size
2 15 0
3 1881959 50000
4 3768823 100000
5 5660295 150000
6 7552719 200000
7 9445167 250000
8 11337607 300000
9 13230031 350000
10 15122471 400000
11 17014895 450000
12 18907343 500000
13 20800207 550000
14 22693407 600000
15 24586615 650000
16 26479855 700000
17 28373063 750000
18 30266287 800000
19 32159487 850000
20 34052711 900000
21 35945943 950000
22 37839175 1000000

View File

@ -0,0 +1,22 @@
operations,size
105,0
17250278,50000
36003532,100000
55780375,150000
75979194,200000
96178166,250000
116909827,300000
137812321,350000
158715267,400000
179617761,450000
200521097,500000
221777541,550000
243367974,600000
264958463,650000
286548836,700000
308139668,750000
329729920,800000
351320353,850000
372910963,900000
394501277,950000
416092270,1000000
1 operations size
2 105 0
3 17250278 50000
4 36003532 100000
5 55780375 150000
6 75979194 200000
7 96178166 250000
8 116909827 300000
9 137812321 350000
10 158715267 400000
11 179617761 450000
12 200521097 500000
13 221777541 550000
14 243367974 600000
15 264958463 650000
16 286548836 700000
17 308139668 750000
18 329729920 800000
19 351320353 850000
20 372910963 900000
21 394501277 950000
22 416092270 1000000

View File

@ -0,0 +1,22 @@
operations,size
29,0
6590279,50000
13847075,100000
21610649,150000
29560649,200000
37510649,250000
45687791,300000
53937791,350000
62187791,400000
70437791,450000
78687791,500000
87092069,550000
95642069,600000
104192069,650000
112742069,700000
121292069,750000
129842069,800000
138392069,850000
146942069,900000
155492069,950000
164042075,1000000
1 operations size
2 29 0
3 6590279 50000
4 13847075 100000
5 21610649 150000
6 29560649 200000
7 37510649 250000
8 45687791 300000
9 53937791 350000
10 62187791 400000
11 70437791 450000
12 78687791 500000
13 87092069 550000
14 95642069 600000
15 104192069 650000
16 112742069 700000
17 121292069 750000
18 129842069 800000
19 138392069 850000
20 146942069 900000
21 155492069 950000
22 164042075 1000000

View File

@ -0,0 +1,85 @@
<?xml version="1.0" standalone="yes"?>
<!-- logreq request file -->
<!-- logreq version 1.0 / dtd version 1.0 -->
<!-- Do not edit this file! -->
<!DOCTYPE requests [
<!ELEMENT requests (internal | external)*>
<!ELEMENT internal (generic, (provides | requires)*)>
<!ELEMENT external (generic, cmdline?, input?, output?, (provides | requires)*)>
<!ELEMENT cmdline (binary, (option | infile | outfile)*)>
<!ELEMENT input (file)+>
<!ELEMENT output (file)+>
<!ELEMENT provides (file)+>
<!ELEMENT requires (file)+>
<!ELEMENT generic (#PCDATA)>
<!ELEMENT binary (#PCDATA)>
<!ELEMENT option (#PCDATA)>
<!ELEMENT infile (#PCDATA)>
<!ELEMENT outfile (#PCDATA)>
<!ELEMENT file (#PCDATA)>
<!ATTLIST requests
version CDATA #REQUIRED
>
<!ATTLIST internal
package CDATA #REQUIRED
priority (9) #REQUIRED
active (0 | 1) #REQUIRED
>
<!ATTLIST external
package CDATA #REQUIRED
priority (1 | 2 | 3 | 4 | 5 | 6 | 7 | 8) #REQUIRED
active (0 | 1) #REQUIRED
>
<!ATTLIST provides
type (static | dynamic | editable) #REQUIRED
>
<!ATTLIST requires
type (static | dynamic | editable) #REQUIRED
>
<!ATTLIST file
type CDATA #IMPLIED
>
]>
<requests version="1.0">
<internal package="biblatex" priority="9" active="0">
<generic>latex</generic>
<provides type="dynamic">
<file>CT2109-Assignment-03.bcf</file>
</provides>
<requires type="dynamic">
<file>CT2109-Assignment-03.bbl</file>
</requires>
<requires type="static">
<file>blx-dm.def</file>
<file>blx-compat.def</file>
<file>biblatex.def</file>
<file>standard.bbx</file>
<file>numeric.bbx</file>
<file>numeric.cbx</file>
<file>biblatex.cfg</file>
<file>english.lbx</file>
</requires>
</internal>
<external package="biblatex" priority="5" active="0">
<generic>biber</generic>
<cmdline>
<binary>biber</binary>
<infile>CT2109-Assignment-03</infile>
</cmdline>
<input>
<file>CT2109-Assignment-03.bcf</file>
</input>
<output>
<file>CT2109-Assignment-03.bbl</file>
</output>
<provides type="dynamic">
<file>CT2109-Assignment-03.bbl</file>
</provides>
<requires type="dynamic">
<file>CT2109-Assignment-03.bcf</file>
</requires>
<requires type="editable">
<file>ecl.bib</file>
</requires>
</external>
</requests>

View File

@ -0,0 +1,214 @@
\documentclass[a4paper]{article}
\usepackage{listings}
\usepackage{xcolor}
\definecolor{codegreen}{rgb}{0,0.6,0}
\definecolor{codegray}{rgb}{0.5,0.5,0.5}
\definecolor{codeorange}{rgb}{1,0.49,0}
\definecolor{backcolour}{rgb}{0.95,0.95,0.96}
\usepackage{pgfplots}
\pgfplotsset{width=\textwidth,compat=1.9}
\lstdefinestyle{mystyle}{
backgroundcolor=\color{backcolour},
commentstyle=\color{codegray},
keywordstyle=\color{codeorange},
numberstyle=\tiny\color{codegray},
stringstyle=\color{codegreen},
basicstyle=\ttfamily\footnotesize,
breakatwhitespace=false,
breaklines=true,
captionpos=b,
keepspaces=true,
numbers=left,
numbersep=5pt,
showspaces=false,
showstringspaces=false,
showtabs=false,
tabsize=2,
xleftmargin=10pt,
}
\lstset{style=mystyle}
\input{head}
\begin{document}
%-------------------------------
% TITLE SECTION
%-------------------------------
\fancyhead[C]{}
\hrule \medskip % Upper rule
\begin{minipage}{0.295\textwidth}
\begin{raggedright}
\footnotesize
Andrew Hayes \hfill\\
21321503 \hfill\\
a.hayes18@nuigalway.ie
\end{raggedright}
\end{minipage}
\begin{minipage}{0.4\textwidth}
\begin{centering}
\large
CT2109 Assignment 3\\
\normalsize
\end{centering}
\end{minipage}
\begin{minipage}{0.295\textwidth}
\begin{raggedleft}
\footnotesize
\today \hfill\\
\end{raggedleft}
\end{minipage}
\medskip\hrule
\medskip
\begin{centering}
Double-Base Palindromes \& Complexity Analysis\\
\end{centering}
\medskip\hrule
\bigskip
\section{Problem Statement}
The overall purpose of this assignment is to perform some basic complexity analysis on four distinct algorithms, each of which aim to achieve the same result: determining whether a String is palindromic.
More specifically, each algorithm will be fed the binary \& decimal representations of each integer between $0_{10}$ and $1,000,000_{10}$, in String form.
Each algorithm will then determine whether the String is palindromic, returning either \verb|true| or \verb|false|.
Each method will have three counter variables to record the number of palindromes found: one for the numbers whose decimal form is palindromic, one for the numbers whose binary form is palindromic, and one
for the numbers which are palindromic in both decimal \& binary form.
\\\\
The number of primitive operations will be recorded using a separate global variable for each method.
Additionally, the real time taken by each method (in milliseconds) will be recorded.
These measurements will form the basis of the complexity analysis performed.
The number of primitive operations will be recorded for each method and plotted against the size of the problem (the number of values being checked for palindromicity, $n$).
This graph should reflect the ``order'' of the problem, i.e. it should match the big-O representation derived from a time-complexity analysis of the algorithm.
For example, an exponential curve on the graph would indicate that the algorithm is of $O(n^2)$ complexity, while a straight line through the origin would indicate that the algorithm is of $O(n)$ complexity.
\section{Analysis \& Design Notes}
The first thing that we'll want to do in this program is declare the variables that we'll use to record the data for each method being tested.
We will have seven arrays of size four, with one index for each method being tested.
These arrays will be:
\begin{itemize}
\item \verb|long[] operations| - To count the number of primitive operations for each method.
\item \verb|int[] decCount| - To count how many numbers that are palindromic in decimal form are found using each method.
\item \verb|int[] binCount| - To count how many numbers that are palindromic in binary form are found using each method.
\item \verb|int[] bothCount| - To count how many numbers that are palindromic in both decimal \& binary form are found using each method.
\item \verb|long[] startTime| - To record the start time (in Unix epoch form) of the testing of each of the four methods.
\item \verb|long[] totalTime| - To record the total time (in milliseconds) by the testing of each of the four methods.
\item \verb|StringBuilder[] data| - This will be be used to create a String of CSV data for each method, which will be output to a \verb|.csv| file at the end of testing.
Doing this saves us from having to open, write to, \& close a \verb|.csv| file every time we want to record some data, which would be very inefficient.
\end{itemize}
The first thing that we'll do in the main method is initialise all the indices in the \verb|StringBuilder[] data| array to have the appropriate headings from each column, one column for the number of primitive operations
and one for the size of the problem that used that number of primitive operations, i.e. \verb|"operations,size\n"|.
\\\\
We'll also want to generate a two-dimensional array of all the Strings that we'll be testing for palindromicity, with one dimension for decimal Strings and one dimension for binary Strings, both going up to
$1,000,000_{10}$.
Generating this once in the beginning will save us from having to re-generate the same Strings four times, which would be very inefficient.
\\\\
Each method that we will be testing will have its own class that implements the interface \verb|PalindromeChecker|.
This interface will contain a single method with the signature \verb|public boolean checkPalindrome(String str)|.
The reason for doing this will be to follow OOP principles \& the DRY principle so that we don't have unnecessary repetition of code.
This will allow us to have one generic loop through each of the numbers from $0_{10}$ to $1,000,000_{10}$ instead of four separate ones.
Each of the methods that we will be testing will be overridden implementations of \verb|checkPalindrome|.
We will have four classes that implement \verb|PalindromeChecker|:
\begin{itemize}
\item \verb|ReverseVSOriginal| - This class will contain ``Method One'' outlined in the assignment specification, which checks if a String is palindromic by comparing the String to a reversed copy of itself, hence the name.
\item \verb|IVersusIMinusN| - This will contain ``Method Two'' outlined in the assignment specification, which checks if a String is palindromic by looping through each character in the String using an iterator
\verb|i| and comparing the character at index \verb|i| to the character at index \verb|n-i|, where \verb|n| is the last index in the String, i.e., comparing the first character to the last, the second character to the second-last, etc.
\item \verb|StackVSQueue| - This will contain ``Method Three'' outlined in the assignment specification, which checks if a String is palindromic using essentially the same technique as ``Method Two''
but instead of simply iterating through the String, each character of the String will be put onto both a Stack \& a Queue, and then items will be removed from the Stack \& Queue and compared to each other.
The LIFO nature of the Stack and the FIFO nature of the Queue result in this comparison being first character versus last, second character versus second-last, and so on.
\item \verb|RecursiveReverse| - This will contain ``Method Four'' outlined in the assignment specification, which checks if a String is palindromic using essentially the same technique as ``Method One''
but using recursion to reverse the String instead of iteration.
\end{itemize}
An array called \verb|PalindromeCheckers[]| will be initialised to contain an instance of each of these four classes.
This array will be iterated over (using iterator \verb|j|) to test each method, which prevents code repetition.
In said loop, firstly, the \verb|startTime[j]| will be recorded using \verb|System.getCurrentTimeMillis();|.
Then, a loop will be entered that iterators over each number between $0_{10}$ to $1,000,000_{10}$.
Both the decimal \& binary Strings at index \verb|i| of the \verb|strings[]| array will be passed to \verb|palindromeCheckers[j].checkPalindrome()| to be checked for palindromicity.
Then, \verb|decCount[j]|, \verb|binCount[j]|, \& \verb|bothCount[j]| will be iterated or will remain unchanged, as appropriate.
\\\\
The count of primitive operations for each method will be iterated as they are executed.
I won't count the \verb|return| statements at the end of methods or accessing a variable or array index as primitive operations, as these (especially the \verb|return| statements) are computationally
insignificant, and certainly aren't on the same level as something like creating a new variable in memory.
Unfortunately, it's not really possible to say with accuracy what is \& isn't a ``primitive operation'' in a language so high-level \& abstract as Java, but I feel that this is a reasonable approximation.
We want to record the count of primitive operations at regular intervals of 50,000 during the process, so we will append the operations count and the current \verb|i| to \verb|data[j]| if \verb|i| is
divisible by 50,000.
\\\\
Once the loop using iterator \verb|i| has ended, the total time taken will be recorded by subtracting the current time from the start time.
The number of palindromes found in decimal, binary, and both decimal \& binary will be printed out to the screen, along with the total time taken \& the total number of primitive operations for that method.
Finally, the data for that method will be written to a \verb|.csv| file.
This will be repeated for all four methods in the \verb|palindromeCheckers| array.
\section{Code}
\lstinputlisting[language=Java, breaklines=true, title={NewPalindrome.java}]{../code/NewPalindrome.java}
\lstinputlisting[language=Java, breaklines=true, title={PalindromeChecker.java}]{../code/PalindromeChecker.java}
\lstinputlisting[language=Java, breaklines=true, title={ReverseVSOriginal.java}]{../code/ReverseVSOriginal.java}
\lstinputlisting[language=Java, breaklines=true, title={IVersusIMinusN.java}]{../code/IVersusNMinusI.java}
\lstinputlisting[language=Java, breaklines=true, title={StackVSQueue.java}]{../code/StackVSQueue.java}
\lstinputlisting[language=Java, breaklines=true, title={RecursiveReverse.java}]{../code/RecursiveReverse.java}
\newpage
\section{Testing}
\begin{center}
\begin{tikzpicture}
\begin{axis}[
title={Number of Primitive Operations per Method},
xlabel={Size of Problem},
ylabel={Number of Operations}
]
\addplot table [x=size, y=operations, col sep=comma] {../code/method0.csv};
\addplot table [x=size, y=operations, col sep=comma] {../code/method1.csv};
\addplot table [x=size, y=operations, col sep=comma] {../code/method2.csv};
\addplot table [x=size, y=operations, col sep=comma] {../code/method3.csv};
\legend{Iterative Reverse vs Original,$i$ vs $n-i$,Stack vs Queue,Recursive Reverse vs Original}
\end{axis}
\end{tikzpicture}
\end{center}
\begin{figure}[h]
\centering
\includegraphics[width=0.7\textwidth]{images/output.png}
\caption{Output of the Main Method}
\end{figure}
The output from the program shows that all the methods agreed on the number of palindromes found in each category, which shows us
that they did indeed work as intended.
\\\\
We can see from the graph that $i$ versus $n-i$ or \verb|IVersusNMinusI| method was the most efficient, as it used the fewest
primitive operations out of the four methods (37,839,177) and the complexity grew relatively slowly as the size of the problem increased,
demonstrated by the fact that its curve has quite a gentle slope.
This is reflected in the testing times as it was by far the fastest method (referred to in the screenshot as ``Method 1'', as
indexing was done from 0), taking only 39 milliseconds to complete.
This makes sense, as the method consisted of just one loop and some basic operations, without using any fancy data structures.
Furthermore, this method quickly detects non-palindromic Strings, and returns \verb|false|, saving computation.
\\\\
The next most efficient method was the iterative reverse versus original or \verb|ReverseVSOriginal| method.
Despite being the next most efficient method, it took almost ten times the time that \verb|IVersusNMinusI| took to complete, taking 366
milliseconds, which, all things considered, is still quite fast.
The number of primitive operations and the rate of growth of this method were also accordingly higher than the previous method.
\\\\
The third most efficient method was the recursive reverse versus original or \verb|RecursiveReverse| method.
This makes sense, as it uses a very similar approach to the second most efficient method, but instead did it recursively.
Despite this solution appearing somewhat more elegant from a lines of code perspective, it was in practice less efficient than
its iterative counterpart, both in terms of memory (as the recursive function calls had to remain in memory until all the sub-calls
were complete) and in terms of operations, taking approximately 20 million more primitive operations to complete the same task
as the iterative approach.
It was also significantly slower than its iterative counterpart, taking around 200 milliseconds more to complete the task.
We can also tell from looking at the graph that at low problem sizes that this approach is comparable \& rather similar in terms
of efficiency to the iterative approach, but they quickly diverge, with the recursive approach having a significantly steeper
slope.
We can extrapolate from this that this method would be even less efficient at very large problem sizes, as its rate of growth
is quite large.
\\\\
By far the least efficient method was the Stack versus Queue or \verb|StackVSQueue| method.
It took by far the greatest number of primitive operations, and the rate of growth was ridiculously large, rapidly diverging from
the other four techniques.
Its rate of growth is so large that it would likely quickly become unusable for any significantly large problem.
This is reinforced by the fact that it took 3,519 milliseconds to complete the task, being the only method that took more than one
second to do so, and taking almost 100 times what the best-performing method took.
\end{document}

View File

@ -0,0 +1,49 @@
\addtolength{\hoffset}{-2.25cm}
\addtolength{\textwidth}{4.5cm}
\addtolength{\voffset}{-3.25cm}
\addtolength{\textheight}{5cm}
\setlength{\parskip}{0pt}
\setlength{\parindent}{0in}
%----------------------------------------------------------------------------------------
% PACKAGES AND OTHER DOCUMENT CONFIGURATIONS
%----------------------------------------------------------------------------------------
\usepackage{blindtext} % Package to generate dummy text
\usepackage{charter} % Use the Charter font
\usepackage[utf8]{inputenc} % Use UTF-8 encoding
\usepackage{microtype} % Slightly tweak font spacing for aesthetics
\usepackage[english]{babel} % Language hyphenation and typographical rules
\usepackage{amsthm, amsmath, amssymb} % Mathematical typesetting
\usepackage{float} % Improved interface for floating objects
\usepackage[final, colorlinks = true,
linkcolor = black,
citecolor = black]{hyperref} % For hyperlinks in the PDF
\usepackage{graphicx, multicol} % Enhanced support for graphics
\usepackage{xcolor} % Driver-independent color extensions
\usepackage{marvosym, wasysym} % More symbols
\usepackage{rotating} % Rotation tools
\usepackage{censor} % Facilities for controlling restricted text
\usepackage{listings, style/lstlisting} % Environment for non-formatted code, !uses style file!
\usepackage{pseudocode} % Environment for specifying algorithms in a natural way
\usepackage{style/avm} % Environment for f-structures, !uses style file!
\usepackage{booktabs} % Enhances quality of tables
\usepackage{tikz-qtree} % Easy tree drawing tool
\tikzset{every tree node/.style={align=center,anchor=north},
level distance=2cm} % Configuration for q-trees
\usepackage{style/btree} % Configuration for b-trees and b+-trees, !uses style file!
\usepackage[backend=biber,style=numeric,
sorting=nyt]{biblatex} % Complete reimplementation of bibliographic facilities
\addbibresource{ecl.bib}
\usepackage{csquotes} % Context sensitive quotation facilities
\usepackage[yyyymmdd]{datetime} % Uses YEAR-MONTH-DAY format for dates
\renewcommand{\dateseparator}{-} % Sets dateseparator to '-'
\usepackage{fancyhdr} % Headers and footers
\pagestyle{fancy} % All pages have headers and footers
\fancyhead{}\renewcommand{\headrulewidth}{0pt} % Blank out the default header
\fancyfoot[L]{} % Custom footer text
\fancyfoot[C]{} % Custom footer text
\fancyfoot[R]{\thepage} % Custom footer text
\newcommand{\note}[1]{\marginpar{\scriptsize \textcolor{red}{#1}}} % Enables comments in red on margin
%----------------------------------------------------------------------------------------

Binary file not shown.

After

Width:  |  Height:  |  Size: 50 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 86 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 43 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 74 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 79 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 78 KiB

View File

@ -0,0 +1,165 @@
% avm.sty -- for attribute-value matrices -- mar 29, 1992; rev. dec 6, 1993
% (c) 1992 christopher manning (manning@csli.stanford.edu) -- see avm.doc.tex
\newif\ifavmactive\newif\ifavmsorted\newif\ifavmlabeled
\newif\ifavmcenter\newif\ifavmbottom
\newif\ifavmbottomright\newif\ifavmtopleft\newif\ifavmtopright
\newdimen\avmdimen
\newbox\avmboxone\newbox\avmboxthree
\def\avmoptions#1{\avmactivefalse\avmsortedfalse\avmlabeledfalse
\avmcenterfalse\avmbottomfalse
\avmbottomrightfalse\avmtopleftfalse\avmtoprightfalse
\def\more{#1}\ifx\more\empty\else\avmjoptions#1,\@nil\fi}
\def\avmjoptions#1,#2\@nil{\def\more{#2}\csname avm#1true\endcsname
\ifx\more\empty\else\avmjoptions#2\@nil\fi}
\def\avmfont#1{\def\avmjfont{#1}}
\def\avmjfont{}
\def\avmvalfont#1{\def\avmjvalfont{#1}}
\def\avmjvalfont{}
\def\avmsortfont#1{\def\avmjsortfont{#1}}
\def\avmjsortfont{}
\def\avmhskip#1{\def\avmjhskip{#1}}
\def\avmjhskip{1em}
\def\avmbskip#1{\def\avmjbskip{#1}}
\def\avmjbskip{0em}
\def\avmvskip#1{\def\avmjvskip{#1}}
\def\avmjvskip{0.385ex}%was .3875
\def\avmjprolog#1{$\mskip-\thinmuskip
\left#1\hskip\avmjbskip\vcenter\bgroup\vskip\avmjvskip
\ialign\bgroup\avmjfont
\strut ##\unskip\hfil
&&\hskip\avmjhskip\avmjvalfont ##\unskip\hfil\cr}
\def\avmjpostlog#1{\crcr\egroup\vskip\avmjvskip\egroup
\hskip\avmjbskip\right#1\mskip-\thinmuskip$\ignorespaces}
\def\avmjcatcode{\let\lparen=(\let\rparen=)\catcode`\[=13\catcode`\]=13
\catcode`\<=13\catcode`\@=13\catcode`\(=13\catcode`\)=13
\catcode`\>=13\catcode`\|=13}
{\avmjcatcode % new group: redefine above catcodes as active
\gdef\specialavm{\avmjcatcode
\def({\avmjprolog\lparen}%
\def){\avmjpostlog\rparen}%
\def<{\avmjprolog\langle}%
\def>{\avmjpostlog\rangle}%
\ifavmsorted
\def[##1{\setbox\avmboxthree=\hbox{\avmjsortfont##1\/}\setbox2=\hbox
\bgroup\avmjprolog\lbrack}%
\def]{\avmjpostlog\rbrack\egroup\avmjsort}%
\else\ifavmlabeled
\def[##1{\def\more{##1}\setbox2=\hbox\bgroup\avmjprolog[}%
\def]{\avmjpostlog]\egroup\node{\more}{\box2}}%
\else
\def[{\avmjprolog\lbrack}%
\def]{\avmjpostlog\rbrack}%
\fi\fi
%
\def\<{$\langle$}\def\>{$\rangle$}%
\def\({\lparen}\def\){\rparen}%
\def\[{\lbrack}\def\]{\rbrack}%
\def|{$\,\vert\,$}%
\def@##1{\avmbox{##1}}%
} % end defn of \specialavm
} % restore active catcodes
\long\def\avm{\begingroup
\ifavmactive\specialavm
\else
\def\({\avmjprolog(}%
\def\){\avmjpostlog)}%
\def\<{\avmjprolog\langle}%
\def\>{\avmjpostlog\rangle}%
%
\ifavmsorted
\def\[##1{\setbox\avmboxthree=\hbox{\avmjsortfont##1\/}\setbox
2=\hbox\bgroup\avmjprolog[}%
\def\]{\avmjpostlog]\egroup\avmjsort}%
\else\ifavmlabeled
\def\[##1{\def\more{##1}\setbox2=\hbox\bgroup\avmjprolog[}%
\def\]{\avmjpostlog]\egroup\node{\more}{\box2}}%
\else
\def\[{\avmjprolog[}%
\def\]{\avmjpostlog]}%
\fi\fi
%
\def\|{$\,\vert\,$}%
\def\@##1{\avmbox{##1}}%
\fi % end not active
%
\ifx\LaTeX\undefined\def\\{\cr}% running under TeX
\else \def\\{\@tabularcr}% Leverage off LaTeX's \\*[dimen] options
\fi
\def\!{\node}%
\long\def\avmjsort{\dimen2=\ht2\advance\dimen2 by -.25\baselineskip
\global\dimen\avmdimen=\wd\avmboxthree
\ifavmtopleft \raise\dimen2\llap{\box\avmboxthree}\box2%
\else\ifavmtopright \box2\raise\dimen2\box\avmboxthree%
\else\ifavmbottomright \box2\lower\dimen2\box\avmboxthree%
\else \lower\dimen2\llap{\box\avmboxthree}\box2%
\fi\fi\fi}%
\long\def\sort##1##2{\setbox2=\hbox{##2}\setbox
\avmboxthree=\hbox{\avmjsortfont##1\/}\dimen2=\ht2
\advance\dimen2 by -.25\baselineskip
\ifavmtopleft \raise\dimen2\box\avmboxthree\box2%
\else\ifavmtopright \box2\raise\dimen2\box\avmboxthree%
\else\ifavmbottomright \box2\lower\dimen2\box\avmboxthree%
\else \lower\dimen2\box\avmboxthree\box2%
\fi\fi\fi}%
\long\def\osort##1##2{\setbox2=\hbox{##2}\setbox
\avmboxthree=\hbox{\avmjsortfont ##1\/}\avmjsort}%
\def\avml{\avmjprolog.}%
\def\avmr{\avmjpostlog.}%
\def\avmb##1{\node{##1}{\lbrack\;\rbrack}}%
\def\avmd##1{\node{##1}{---}}%
\def\q##1{\ifx ##1\{$\lbrace$\else
\ifx ##1\}$\rbrace$\else
\ifx ##1<$\langle$\else
\ifx ##1>$\rangle$\fi \fi \fi \fi}%
\def\{{\avmjprolog\lbrace}%
\def\}{\avmjpostlog\rbrace}%
\def\;{\hskip\avmjhskip}%
\def\avmspan##1{\multispan2\strut ##1\expandafter\hfil}%
\avmjfont
\openup\avmjvskip
\setbox\avmboxone=\hbox\bgroup\ignorespaces
} % end defn of \avm
\def\endavm{\egroup\ifvmode\leavevmode\fi % this if is useful!
\ifavmsorted\null\hskip\dimen\avmdimen\fi
\ifavmcenter
\box\avmboxone
\else \ifavmbottom
\lower.575\baselineskip\hbox{\vbox{\box\avmboxone\null}}%
\else
% the next bit is ripped off from Emma's \evnup in lingmacros.sty
\dimen2=\ht\avmboxone\advance\dimen2 by -.725\baselineskip
\lower\dimen2\box\avmboxone
\fi \fi \endgroup}
% based on TeXbook exercise 21.3
\def\avmbox#1{\setbox2=\hbox{$\scriptstyle #1$}\lower.2ex\vbox{\hrule
\hbox{\vrule\kern1.25pt
\vbox{\kern1.25pt\box2\kern1.25pt}\kern1.25pt\vrule}\hrule}}
% ============ COSTOM CONFIGURATION =============
\avmfont{\sc}
\avmoptions{sorted,active}
\avmvalfont{\rm}
\avmsortfont{\scriptsize\it}
% ===============================================

View File

@ -0,0 +1,131 @@
%% Last Modified: Thu Oct 18 18:26:25 2007.
\NeedsTeXFormat{LaTeX2e}
\ProvidesPackage{style/btree}
\typeout{Document Style `weiw_BTree - Support drawing B+-Tree (ver 0.999)}
\RequirePackage{tikz}
\RequirePackage{ifthen}
% use libraries
\usetikzlibrary{arrows,shapes,decorations,matrix}
%% global declaration
\tikzstyle{btreeptr} = [draw, semithick, minimum height=2em]
\tikzstyle{btreeval} = [draw, semithick, minimum size=2em]
\tikzstyle{btreevale} = [draw,semithick, minimum size=2em]
\tikzstyle{btlink} = [draw, semithick, ->, >=triangle 45]
%% macro
%% helper macros
\newcommand{\suppressemptystr}[1]{% leave blank for entries in leaf nodes
\ifthenelse{\equal{#1}{}}%
{%
\relax%
}%
% Else
{%
#1\textsuperscript{*}%
}%
}%
\newcommand{\xyshift}[3]{% help to place the nodes
\begin{scope}[xshift=#1, yshift=#2]
#3
\end{scope}%
}
%% Common btree macros
\newcommand{\btreelink}[2]{% #1: src node; #2: dest node;
\draw[btlink] ([yshift=3pt] #1.south) -- (#2-b.north);
}
\newcommand{\btreelinknorth}[2]{% #1: src node; #2: dest node;
\draw[btlink] ([yshift=3pt] #1.south) -- (#2.north);
}
\newcommand{\btreetriangle}[2]{% #1: node name; #2 text inside
\node[anchor=north, regular polygon, regular polygon sides=3, draw] (#1) {#2};
}
%%======================================================================
%% btree with capacity = 4
\newcommand{\btreeinodefour}[5]{%
\matrix [ampersand replacement=\&] (#1)
{
\node[btreeptr] (#1-1) {\vphantom{1}}; \& \node[btreeval] (#1-a) {#2}; \&
\node[btreeptr] (#1-2) {\vphantom{1}}; \& \node[btreeval] (#1-b) {#3}; \&
\node[btreeptr] (#1-3) {\vphantom{1}}; \& \node[btreeval] (#1-c) {#4}; \&
\node[btreeptr] (#1-4) {\vphantom{1}}; \& \node[btreeval] (#1-d) {#5}; \&
\node[btreeptr] (#1-5) {\vphantom{1}}; \\
};
}
\newcommand{\btreelnodefour}[5]{%
\matrix [ampersand replacement=\&, outer sep=0pt, matrix anchor=north] (#1)
{
\node[btreevale] (#1-a) {\suppressemptystr{#2}}; \&
\node[btreevale] (#1-b) {\suppressemptystr{#3}}; \&
\node[btreevale] (#1-c) {\suppressemptystr{#4}}; \&
\node[btreevale] (#1-d) {\suppressemptystr{#5}}; \\
};
}
%%======================================================================
%% btree with capacity = 3
\newcommand{\btreeinodethree}[4]{%
\matrix [ampersand replacement=\&] (#1)
{
\node[btreeptr] (#1-1) {\vphantom{1}}; \& \node[btreeval] (#1-a) {#2}; \&
\node[btreeptr] (#1-2) {\vphantom{1}}; \& \node[btreeval] (#1-b) {#3}; \&
\node[btreeptr] (#1-3) {\vphantom{1}}; \& \node[btreeval] (#1-c) {#4}; \&
\node[btreeptr] (#1-4) {\vphantom{1}}; \\
};
}
\newcommand{\btreelnodethree}[4]{%
\matrix [ampersand replacement=\&, outer sep=0pt, matrix anchor=north] (#1)
{
\node[btreevale] (#1-a) {\suppressemptystr{#2}}; \&
\node[btreevale] (#1-b) {\suppressemptystr{#3}}; \&
\node[btreevale] (#1-c) {\suppressemptystr{#4}}; \\
};
}
%%======================================================================
%% btree with capacity = 2
\newcommand{\btreeinodetwo}[4]{%
\matrix [ampersand replacement=\&] (#1)
{
\node[btreeptr] (#1-1) {\vphantom{1}}; \& \node[btreeval] (#1-a) {#2}; \&
\node[btreeptr] (#1-2) {\vphantom{1}}; \& \node[btreeval] (#1-b) {#3}; \&
\node[btreeptr] (#1-3) {\vphantom{1}}; \\
};
}
\newcommand{\btreelnodetwo}[3]{%
\matrix [ampersand replacement=\&, outer sep=0pt, matrix anchor=north] (#1)
{
\node[btreevale] (#1-a) {\suppressemptystr{#2}}; \&
\node[btreevale] (#1-b) {\suppressemptystr{#3}}; \\
};
}
%%======================================================================
%% simple example
% \begin{center}
% \scalebox{0.7}{
% \begin{tikzpicture}
% %
% \btreeinodefour{root}{13}{17}{24}{30};
% \xyshift{-40mm}{-20mm}{\btreelnodefour{n1}{2}{3}{5}{7}}
% \xyshift{-0mm}{-20mm}{\btreelnodefour{n2}{14}{16}{}{}}
% \xyshift{40mm}{-20mm}{\btreelnodefour{n3}{19}{20}{22}{}}
% \xyshift{80mm}{-20mm}{\btreelnodefour{n4}{24}{27}{29}{}}
% \xyshift{120mm}{-20mm}{\btreelnodefour{n5}{33}{34}{38}{39}}
% %
% \foreach \x in {1,2,...,5} { \btreelink{root-\x}{n\x} }
% \end{tikzpicture}
% }
% \end{center}

View File

@ -0,0 +1,38 @@
% Source: ss17_wissschreib (Eva)
\lstset{
basicstyle=\ttfamily\scriptsize\mdseries,
keywordstyle=\bfseries\color[rgb]{0.171875, 0.242188, 0.3125},
identifierstyle=,
commentstyle=\color[rgb]{0.257813, 0.15625, 0},
stringstyle=\itshape\color[rgb]{0.0195313, 0.195313, 0.0117188},
numbers=left,
numberstyle=\tiny,
stepnumber=1,
breaklines=true,
frame=none,
showstringspaces=false,
tabsize=4,
backgroundcolor=\color[rgb]{0.98,0.98,0.98},
captionpos=b,
float=htbp,
language=Python,
xleftmargin=15pt,
xrightmargin=15pt
}
%(deutsche) Sonderzeichen
\lstset{literate=%
{Ä}{{\"A}}1
{Ö}{{\"O}}1
{Ü}{{\"U}}1
{ä}{{\"a}}1
{ö}{{\"o}}1
{ü}{{\"u}}1
{ß}{{\ss}}1
}
%Verwendung im Text:
%-> \begin{lstlisting}[language=Python,firstnumber=27] ... \end{lstlisting}
%-> \begin{lstlisting}[language=Python,numbers=none] ... \end{lstlisting}
%-> \lstinline[language=JAVA]{...}

View File

@ -0,0 +1,499 @@
% $ biblatex auxiliary file $
% $ biblatex bbl format version 3.2 $
% Do not modify the above lines!
%
% This is an auxiliary file used by the 'biblatex' package.
% This file may safely be deleted. It will be recreated by
% biber as required.
%
\begingroup
\makeatletter
\@ifundefined{ver@biblatex.sty}
{\@latex@error
{Missing 'biblatex' package}
{The bibliography requires the 'biblatex' package.}
\aftergroup\endinput}
{}
\endgroup
\refsection{0}
\datalist[entry]{none/global//global/global}
\entry{slides}{online}{}
\name{author}{1}{}{%
{{hash=4db5fdda44d980dfd1fa3c357d9f1fe3}{%
family={Glavin},
familyi={G\bibinitperiod},
given={Frank},
giveni={F\bibinitperiod}}}%
}
\strng{namehash}{4db5fdda44d980dfd1fa3c357d9f1fe3}
\strng{fullhash}{4db5fdda44d980dfd1fa3c357d9f1fe3}
\strng{bibnamehash}{4db5fdda44d980dfd1fa3c357d9f1fe3}
\strng{authorbibnamehash}{4db5fdda44d980dfd1fa3c357d9f1fe3}
\strng{authornamehash}{4db5fdda44d980dfd1fa3c357d9f1fe3}
\strng{authorfullhash}{4db5fdda44d980dfd1fa3c357d9f1fe3}
\field{sortinit}{1}
\field{sortinithash}{4f6aaa89bab872aa0999fec09ff8e98a}
\field{labelnamesource}{author}
\field{labeltitlesource}{title}
\field{addendum}{Uploaded to Blackboard: 2023-02-17}
\field{title}{Topic Three: Algorithm Analysis \& Dynamic Programming Part II}
\keyw{p,np}
\endentry
\entry{wolfram}{online}{}
\name{author}{1}{}{%
{{hash=d041a125476c57c12ca53005c1fe93b1}{%
family={Terr},
familyi={T\bibinitperiod},
given={David},
giveni={D\bibinitperiod}}}%
}
\strng{namehash}{d041a125476c57c12ca53005c1fe93b1}
\strng{fullhash}{d041a125476c57c12ca53005c1fe93b1}
\strng{bibnamehash}{d041a125476c57c12ca53005c1fe93b1}
\strng{authorbibnamehash}{d041a125476c57c12ca53005c1fe93b1}
\strng{authornamehash}{d041a125476c57c12ca53005c1fe93b1}
\strng{authorfullhash}{d041a125476c57c12ca53005c1fe93b1}
\field{sortinit}{2}
\field{sortinithash}{8b555b3791beccb63322c22f3320aa9a}
\field{labelnamesource}{author}
\field{labeltitlesource}{title}
\field{addendum}{(Accessed: 2023-03-03)}
\field{title}{Polynomial Time}
\verb{urlraw}
\verb https://mathworld.wolfram.com/PolynomialTime.html
\endverb
\verb{url}
\verb https://mathworld.wolfram.com/PolynomialTime.html
\endverb
\keyw{p}
\endentry
\entry{floydnondeterm}{online}{}
\name{author}{1}{}{%
{{hash=6a7319445e476f9e3f352261abd48a4a}{%
family={Floyd},
familyi={F\bibinitperiod},
given={Robert\bibnamedelima W.},
giveni={R\bibinitperiod\bibinitdelim W\bibinitperiod}}}%
}
\list{publisher}{1}{%
{Journal of the ACM}%
}
\strng{namehash}{6a7319445e476f9e3f352261abd48a4a}
\strng{fullhash}{6a7319445e476f9e3f352261abd48a4a}
\strng{bibnamehash}{6a7319445e476f9e3f352261abd48a4a}
\strng{authorbibnamehash}{6a7319445e476f9e3f352261abd48a4a}
\strng{authornamehash}{6a7319445e476f9e3f352261abd48a4a}
\strng{authorfullhash}{6a7319445e476f9e3f352261abd48a4a}
\field{sortinit}{3}
\field{sortinithash}{ad6fe7482ffbd7b9f99c9e8b5dccd3d7}
\field{labelnamesource}{author}
\field{labeltitlesource}{title}
\field{month}{10}
\field{title}{Nondeterministic Algorithms}
\field{year}{1967}
\field{dateera}{ce}
\verb{doi}
\verb 10.1145/321420.321422
\endverb
\endentry
\entry{britnpcomp}{online}{}
\name{author}{1}{}{%
{{hash=b5b5d41e9deb4fed9ffa108254d8b7ad}{%
family={Hosch},
familyi={H\bibinitperiod},
given={William\bibnamedelima L.},
giveni={W\bibinitperiod\bibinitdelim L\bibinitperiod}}}%
}
\list{publisher}{1}{%
{Encyclopedia Britannica}%
}
\strng{namehash}{b5b5d41e9deb4fed9ffa108254d8b7ad}
\strng{fullhash}{b5b5d41e9deb4fed9ffa108254d8b7ad}
\strng{bibnamehash}{b5b5d41e9deb4fed9ffa108254d8b7ad}
\strng{authorbibnamehash}{b5b5d41e9deb4fed9ffa108254d8b7ad}
\strng{authornamehash}{b5b5d41e9deb4fed9ffa108254d8b7ad}
\strng{authorfullhash}{b5b5d41e9deb4fed9ffa108254d8b7ad}
\field{extraname}{1}
\field{sortinit}{4}
\field{sortinithash}{9381316451d1b9788675a07e972a12a7}
\field{labelnamesource}{author}
\field{labeltitlesource}{title}
\field{addendum}{(Accessed: 2023-03-03)}
\field{day}{10}
\field{month}{3}
\field{title}{NP-complete problem}
\field{year}{2023}
\field{dateera}{ce}
\verb{urlraw}
\verb https://www.britannica.com/science/NP-complete-problem#ref97458
\endverb
\verb{url}
\verb https://www.britannica.com/science/NP-complete-problem#ref97458
\endverb
\endentry
\entry{fortnow}{online}{}
\name{author}{1}{}{%
{{hash=e43a5724fcae7ec1838dfc44579da075}{%
family={Fortnow},
familyi={F\bibinitperiod},
given={Lance},
giveni={L\bibinitperiod}}}%
}
\list{publisher}{1}{%
{Communications of the ACM}%
}
\strng{namehash}{e43a5724fcae7ec1838dfc44579da075}
\strng{fullhash}{e43a5724fcae7ec1838dfc44579da075}
\strng{bibnamehash}{e43a5724fcae7ec1838dfc44579da075}
\strng{authorbibnamehash}{e43a5724fcae7ec1838dfc44579da075}
\strng{authornamehash}{e43a5724fcae7ec1838dfc44579da075}
\strng{authorfullhash}{e43a5724fcae7ec1838dfc44579da075}
\field{sortinit}{5}
\field{sortinithash}{20e9b4b0b173788c5dace24730f47d8c}
\field{labelnamesource}{author}
\field{labeltitlesource}{title}
\field{title}{The status of the P versus NP problem}
\field{year}{2009}
\field{dateera}{ce}
\verb{doi}
\verb 10.1145/1562164.1562186
\endverb
\endentry
\entry{techopedia}{online}{}
\list{publisher}{1}{%
{techopedia}%
}
\field{sortinit}{6}
\field{sortinithash}{b33bc299efb3c36abec520a4c896a66d}
\field{labeltitlesource}{title}
\field{addendum}{(Accessed: 2023-03-03)}
\field{day}{29}
\field{month}{8}
\field{title}{Non-Deterministic Polynomial Time (NP)}
\field{year}{2019}
\field{dateera}{ce}
\verb{urlraw}
\verb https://www.techopedia.com/definition/21028/non-deterministic-polynomial-time-np
\endverb
\verb{url}
\verb https://www.techopedia.com/definition/21028/non-deterministic-polynomial-time-np
\endverb
\endentry
\entry{britpvsnpproblem}{online}{}
\name{author}{1}{}{%
{{hash=b5b5d41e9deb4fed9ffa108254d8b7ad}{%
family={Hosch},
familyi={H\bibinitperiod},
given={William\bibnamedelima L.},
giveni={W\bibinitperiod\bibinitdelim L\bibinitperiod}}}%
}
\list{publisher}{1}{%
{Encyclopedia Britannica}%
}
\strng{namehash}{b5b5d41e9deb4fed9ffa108254d8b7ad}
\strng{fullhash}{b5b5d41e9deb4fed9ffa108254d8b7ad}
\strng{bibnamehash}{b5b5d41e9deb4fed9ffa108254d8b7ad}
\strng{authorbibnamehash}{b5b5d41e9deb4fed9ffa108254d8b7ad}
\strng{authornamehash}{b5b5d41e9deb4fed9ffa108254d8b7ad}
\strng{authorfullhash}{b5b5d41e9deb4fed9ffa108254d8b7ad}
\field{extraname}{2}
\field{sortinit}{9}
\field{sortinithash}{0a5ebc79d83c96b6579069544c73c7d4}
\field{labelnamesource}{author}
\field{labeltitlesource}{title}
\field{addendum}{(Accessed: 2023-03-03)}
\field{day}{22}
\field{month}{2}
\field{title}{P versus NP problem}
\field{year}{2023}
\field{dateera}{ce}
\verb{urlraw}
\verb https://www.britannica.com/science/P-versus-NP-problem
\endverb
\verb{url}
\verb https://www.britannica.com/science/P-versus-NP-problem
\endverb
\endentry
\entry{salesman}{online}{}
\name{author}{1}{}{%
{{hash=d29e15a1eaae3938b743eb055c894692}{%
family={Carlson},
familyi={C\bibinitperiod},
given={Stephan\bibnamedelima C.},
giveni={S\bibinitperiod\bibinitdelim C\bibinitperiod}}}%
}
\list{publisher}{1}{%
{Encyclopedia Britannica}%
}
\strng{namehash}{d29e15a1eaae3938b743eb055c894692}
\strng{fullhash}{d29e15a1eaae3938b743eb055c894692}
\strng{bibnamehash}{d29e15a1eaae3938b743eb055c894692}
\strng{authorbibnamehash}{d29e15a1eaae3938b743eb055c894692}
\strng{authornamehash}{d29e15a1eaae3938b743eb055c894692}
\strng{authorfullhash}{d29e15a1eaae3938b743eb055c894692}
\field{sortinit}{1}
\field{sortinithash}{4f6aaa89bab872aa0999fec09ff8e98a}
\field{labelnamesource}{author}
\field{labeltitlesource}{title}
\field{addendum}{(Accessed: 2023-03-03)}
\field{day}{5}
\field{month}{2}
\field{title}{Travelling salesman Problem}
\field{year}{2023}
\field{dateera}{ce}
\verb{urlraw}
\verb https://www.britannica.com/science/traveling-salesman-problem
\endverb
\verb{url}
\verb https://www.britannica.com/science/traveling-salesman-problem
\endverb
\endentry
\entry{wolframnphard}{online}{}
\name{author}{1}{}{%
{{hash=819197bfeff32a3f58d49b2a3eb0a580}{%
family={Weisstein},
familyi={W\bibinitperiod},
given={Eric\bibnamedelima W.},
giveni={E\bibinitperiod\bibinitdelim W\bibinitperiod}}}%
}
\list{publisher}{1}{%
{MathWorld = A Wolfram Web Resource}%
}
\strng{namehash}{819197bfeff32a3f58d49b2a3eb0a580}
\strng{fullhash}{819197bfeff32a3f58d49b2a3eb0a580}
\strng{bibnamehash}{819197bfeff32a3f58d49b2a3eb0a580}
\strng{authorbibnamehash}{819197bfeff32a3f58d49b2a3eb0a580}
\strng{authornamehash}{819197bfeff32a3f58d49b2a3eb0a580}
\strng{authorfullhash}{819197bfeff32a3f58d49b2a3eb0a580}
\field{sortinit}{1}
\field{sortinithash}{4f6aaa89bab872aa0999fec09ff8e98a}
\field{labelnamesource}{author}
\field{labeltitlesource}{title}
\field{addendum}{(Accessed: 2023-03-03)}
\field{title}{NP-Hard Problem}
\verb{urlraw}
\verb https://mathworld.wolfram.com/NP-HardProblem.html
\endverb
\verb{url}
\verb https://mathworld.wolfram.com/NP-HardProblem.html
\endverb
\endentry
\entry{interact}{book}{}
\name{author}{1}{}{%
{{hash=d7582c31fe3061838883debf5d237536}{%
family={Johnson},
familyi={J\bibinitperiod},
given={Michael\bibnamedelimb R.\bibnamedelimi Garey\bibnamedelimb \& David\bibnamedelima S.},
giveni={M\bibinitperiod\bibinitdelim R\bibinitperiod\bibinitdelim G\bibinitperiod\bibinitdelim \\bibinitperiod\bibinitdelim D\bibinitperiod\bibinitdelim S\bibinitperiod}}}%
}
\list{publisher}{1}{%
{W.H. Freeman}%
}
\strng{namehash}{d7582c31fe3061838883debf5d237536}
\strng{fullhash}{d7582c31fe3061838883debf5d237536}
\strng{bibnamehash}{d7582c31fe3061838883debf5d237536}
\strng{authorbibnamehash}{d7582c31fe3061838883debf5d237536}
\strng{authornamehash}{d7582c31fe3061838883debf5d237536}
\strng{authorfullhash}{d7582c31fe3061838883debf5d237536}
\field{sortinit}{1}
\field{sortinithash}{4f6aaa89bab872aa0999fec09ff8e98a}
\field{labelnamesource}{author}
\field{labeltitlesource}{title}
\field{isbn}{0-7167-1045-5}
\field{title}{Computers \& Intractability: A Guide to the Theory of NP-Completeness}
\field{year}{1979}
\field{dateera}{ce}
\endentry
\entry{halting}{online}{}
\name{author}{1}{}{%
{{hash=38ba3b8c5a650c291517635c39277196}{%
family={al.},
familyi={a\bibinitperiod},
given={Karleigh\bibnamedelima Moore},
giveni={K\bibinitperiod\bibinitdelim M\bibinitperiod},
prefix={et},
prefixi={e\bibinitperiod}}}%
}
\list{publisher}{1}{%
{Brilliant}%
}
\strng{namehash}{38ba3b8c5a650c291517635c39277196}
\strng{fullhash}{38ba3b8c5a650c291517635c39277196}
\strng{bibnamehash}{38ba3b8c5a650c291517635c39277196}
\strng{authorbibnamehash}{38ba3b8c5a650c291517635c39277196}
\strng{authornamehash}{38ba3b8c5a650c291517635c39277196}
\strng{authorfullhash}{38ba3b8c5a650c291517635c39277196}
\field{sortinit}{1}
\field{sortinithash}{4f6aaa89bab872aa0999fec09ff8e98a}
\field{labelnamesource}{author}
\field{labeltitlesource}{title}
\field{addendum}{(Accessed: 2023-03-03)}
\field{title}{Halting Problem}
\verb{urlraw}
\verb https://brilliant.org/wiki/halting-problem/
\endverb
\verb{url}
\verb https://brilliant.org/wiki/halting-problem/
\endverb
\endentry
\entry{npcompbrit}{online}{}
\name{author}{1}{}{%
{{hash=db058bcb62506fba9fe25e53a62e1e0f}{%
family={Gregersen},
familyi={G\bibinitperiod},
given={Erik},
giveni={E\bibinitperiod}}}%
}
\list{publisher}{1}{%
{Encyclopedia Britannica}%
}
\strng{namehash}{db058bcb62506fba9fe25e53a62e1e0f}
\strng{fullhash}{db058bcb62506fba9fe25e53a62e1e0f}
\strng{bibnamehash}{db058bcb62506fba9fe25e53a62e1e0f}
\strng{authorbibnamehash}{db058bcb62506fba9fe25e53a62e1e0f}
\strng{authornamehash}{db058bcb62506fba9fe25e53a62e1e0f}
\strng{authorfullhash}{db058bcb62506fba9fe25e53a62e1e0f}
\field{sortinit}{1}
\field{sortinithash}{4f6aaa89bab872aa0999fec09ff8e98a}
\field{labelnamesource}{author}
\field{labeltitlesource}{title}
\field{addendum}{(Accessed: 2023-03-12)}
\field{day}{10}
\field{month}{3}
\field{title}{NP-Complete Problem}
\field{year}{2023}
\field{dateera}{ce}
\verb{urlraw}
\verb https://www.britannica.com/science/traveling-salesman-problem
\endverb
\verb{url}
\verb https://www.britannica.com/science/traveling-salesman-problem
\endverb
\endentry
\entry{cook}{online}{}
\name{author}{1}{}{%
{{hash=6d0042ba6060405425561c0184e8ece1}{%
family={Cook},
familyi={C\bibinitperiod},
given={Stephen},
giveni={S\bibinitperiod}}}%
}
\list{publisher}{1}{%
{Proceedings of the Third Annual ACM Symposium on Theory of Computing}%
}
\strng{namehash}{6d0042ba6060405425561c0184e8ece1}
\strng{fullhash}{6d0042ba6060405425561c0184e8ece1}
\strng{bibnamehash}{6d0042ba6060405425561c0184e8ece1}
\strng{authorbibnamehash}{6d0042ba6060405425561c0184e8ece1}
\strng{authornamehash}{6d0042ba6060405425561c0184e8ece1}
\strng{authorfullhash}{6d0042ba6060405425561c0184e8ece1}
\field{sortinit}{1}
\field{sortinithash}{4f6aaa89bab872aa0999fec09ff8e98a}
\field{labelnamesource}{author}
\field{labeltitlesource}{title}
\field{title}{The complexity of theorem-proving procedures}
\field{year}{1971}
\field{dateera}{ce}
\verb{doi}
\verb 10.1145/800157.805047
\endverb
\endentry
\entry{pvsnpbrit}{online}{}
\name{author}{1}{}{%
{{hash=b5b5d41e9deb4fed9ffa108254d8b7ad}{%
family={Hosch},
familyi={H\bibinitperiod},
given={William\bibnamedelima L.},
giveni={W\bibinitperiod\bibinitdelim L\bibinitperiod}}}%
}
\list{publisher}{1}{%
{Encyclopedia Britannica}%
}
\strng{namehash}{b5b5d41e9deb4fed9ffa108254d8b7ad}
\strng{fullhash}{b5b5d41e9deb4fed9ffa108254d8b7ad}
\strng{bibnamehash}{b5b5d41e9deb4fed9ffa108254d8b7ad}
\strng{authorbibnamehash}{b5b5d41e9deb4fed9ffa108254d8b7ad}
\strng{authornamehash}{b5b5d41e9deb4fed9ffa108254d8b7ad}
\strng{authorfullhash}{b5b5d41e9deb4fed9ffa108254d8b7ad}
\field{extraname}{3}
\field{sortinit}{1}
\field{sortinithash}{4f6aaa89bab872aa0999fec09ff8e98a}
\field{labelnamesource}{author}
\field{labeltitlesource}{title}
\field{addendum}{(Accessed: 2023-03-03)}
\field{day}{22}
\field{month}{2}
\field{title}{P versus NP problem}
\field{year}{2023}
\field{dateera}{ce}
\verb{urlraw}
\verb https://www.britannica.com/science/P-versus-NP-problem
\endverb
\verb{url}
\verb https://www.britannica.com/science/P-versus-NP-problem
\endverb
\endentry
\entry{poll}{online}{}
\name{author}{1}{}{%
{{hash=888d7977ce776bc206a593c5821bea9f}{%
family={Gasarch},
familyi={G\bibinitperiod},
given={William\bibnamedelima I.},
giveni={W\bibinitperiod\bibinitdelim I\bibinitperiod}}}%
}
\list{publisher}{1}{%
{SIGACT News}%
}
\strng{namehash}{888d7977ce776bc206a593c5821bea9f}
\strng{fullhash}{888d7977ce776bc206a593c5821bea9f}
\strng{bibnamehash}{888d7977ce776bc206a593c5821bea9f}
\strng{authorbibnamehash}{888d7977ce776bc206a593c5821bea9f}
\strng{authornamehash}{888d7977ce776bc206a593c5821bea9f}
\strng{authorfullhash}{888d7977ce776bc206a593c5821bea9f}
\field{sortinit}{2}
\field{sortinithash}{8b555b3791beccb63322c22f3320aa9a}
\field{labelnamesource}{author}
\field{labeltitlesource}{title}
\field{month}{6}
\field{title}{The P=?NP poll}
\field{year}{2002}
\field{dateera}{ce}
\verb{doi}
\verb 10.1145/564585.564599
\endverb
\endentry
\entry{sipser}{online}{}
\name{author}{1}{}{%
{{hash=13b9c16a9de2bb891eb8aa2a768eb2a8}{%
family={Sipser},
familyi={S\bibinitperiod},
given={Michael},
giveni={M\bibinitperiod}}}%
}
\list{publisher}{1}{%
{Proceedings of the twenty-fourth annual ACM Symposium on Theory of Computing}%
}
\strng{namehash}{13b9c16a9de2bb891eb8aa2a768eb2a8}
\strng{fullhash}{13b9c16a9de2bb891eb8aa2a768eb2a8}
\strng{bibnamehash}{13b9c16a9de2bb891eb8aa2a768eb2a8}
\strng{authorbibnamehash}{13b9c16a9de2bb891eb8aa2a768eb2a8}
\strng{authornamehash}{13b9c16a9de2bb891eb8aa2a768eb2a8}
\strng{authorfullhash}{13b9c16a9de2bb891eb8aa2a768eb2a8}
\field{sortinit}{2}
\field{sortinithash}{8b555b3791beccb63322c22f3320aa9a}
\field{labelnamesource}{author}
\field{labeltitlesource}{title}
\field{month}{7}
\field{title}{The history \& status of the P versus NP question}
\field{year}{1992}
\field{dateera}{ce}
\verb{doi}
\verb 10.1145/129712.129771
\endverb
\endentry
\enddatalist
\endrefsection
\endinput

View File

@ -0,0 +1,86 @@
<?xml version="1.0" standalone="yes"?>
<!-- logreq request file -->
<!-- logreq version 1.0 / dtd version 1.0 -->
<!-- Do not edit this file! -->
<!DOCTYPE requests [
<!ELEMENT requests (internal | external)*>
<!ELEMENT internal (generic, (provides | requires)*)>
<!ELEMENT external (generic, cmdline?, input?, output?, (provides | requires)*)>
<!ELEMENT cmdline (binary, (option | infile | outfile)*)>
<!ELEMENT input (file)+>
<!ELEMENT output (file)+>
<!ELEMENT provides (file)+>
<!ELEMENT requires (file)+>
<!ELEMENT generic (#PCDATA)>
<!ELEMENT binary (#PCDATA)>
<!ELEMENT option (#PCDATA)>
<!ELEMENT infile (#PCDATA)>
<!ELEMENT outfile (#PCDATA)>
<!ELEMENT file (#PCDATA)>
<!ATTLIST requests
version CDATA #REQUIRED
>
<!ATTLIST internal
package CDATA #REQUIRED
priority (9) #REQUIRED
active (0 | 1) #REQUIRED
>
<!ATTLIST external
package CDATA #REQUIRED
priority (1 | 2 | 3 | 4 | 5 | 6 | 7 | 8) #REQUIRED
active (0 | 1) #REQUIRED
>
<!ATTLIST provides
type (static | dynamic | editable) #REQUIRED
>
<!ATTLIST requires
type (static | dynamic | editable) #REQUIRED
>
<!ATTLIST file
type CDATA #IMPLIED
>
]>
<requests version="1.0">
<internal package="biblatex" priority="9" active="0">
<generic>latex</generic>
<provides type="dynamic">
<file>CT2109-Assignment-04.bcf</file>
</provides>
<requires type="dynamic">
<file>CT2109-Assignment-04.bbl</file>
</requires>
<requires type="static">
<file>blx-dm.def</file>
<file>blx-compat.def</file>
<file>biblatex.def</file>
<file>standard.bbx</file>
<file>numeric.bbx</file>
<file>numeric-comp.bbx</file>
<file>numeric-comp.cbx</file>
<file>biblatex.cfg</file>
<file>english.lbx</file>
</requires>
</internal>
<external package="biblatex" priority="5" active="0">
<generic>biber</generic>
<cmdline>
<binary>biber</binary>
<infile>CT2109-Assignment-04</infile>
</cmdline>
<input>
<file>CT2109-Assignment-04.bcf</file>
</input>
<output>
<file>CT2109-Assignment-04.bbl</file>
</output>
<provides type="dynamic">
<file>CT2109-Assignment-04.bbl</file>
</provides>
<requires type="dynamic">
<file>CT2109-Assignment-04.bcf</file>
</requires>
<requires type="editable">
<file>references.bib</file>
</requires>
</external>
</requests>

View File

@ -0,0 +1,5 @@
[0] Config.pm:306> INFO - This is Biber 2.18
[0] Config.pm:309> INFO - Logfile is 'CT2109-Assignment-04.tex.blg'
[47] biber:340> INFO - === Tue Mar 14, 2023, 17:38:31
[138] Utils.pm:410> ERROR - Cannot find 'CT2109-Assignment-04.tex.bcf'!
[138] Biber.pm:135> INFO - ERRORS: 1

View File

@ -0,0 +1,46 @@
\addtolength{\hoffset}{-2.25cm}
\addtolength{\textwidth}{4.5cm}
\addtolength{\voffset}{-3.25cm}
\addtolength{\textheight}{5cm}
\setlength{\parskip}{0pt}
\setlength{\parindent}{0in}
%----------------------------------------------------------------------------------------
% PACKAGES AND OTHER DOCUMENT CONFIGURATIONS
%----------------------------------------------------------------------------------------
\usepackage{blindtext} % Package to generate dummy text
\usepackage{charter} % Use the Charter font
\usepackage[utf8]{inputenc} % Use UTF-8 encoding
\usepackage{microtype} % Slightly tweak font spacing for aesthetics
\usepackage[english]{babel} % Language hyphenation and typographical rules
\usepackage{amsthm, amsmath, amssymb} % Mathematical typesetting
\usepackage{float} % Improved interface for floating objects
\usepackage[final, colorlinks = true,
linkcolor = black,
citecolor = black]{hyperref} % For hyperlinks in the PDF
\usepackage{graphicx, multicol} % Enhanced support for graphics
\usepackage{xcolor} % Driver-independent color extensions
\usepackage{marvosym, wasysym} % More symbols
\usepackage{rotating} % Rotation tools
\usepackage{censor} % Facilities for controlling restricted text
\usepackage{listings, style/lstlisting} % Environment for non-formatted code, !uses style file!
\usepackage{pseudocode} % Environment for specifying algorithms in a natural way
\usepackage{style/avm} % Environment for f-structures, !uses style file!
\usepackage{booktabs} % Enhances quality of tables
\usepackage{tikz-qtree} % Easy tree drawing tool
\tikzset{every tree node/.style={align=center,anchor=north},
level distance=2cm} % Configuration for q-trees
\usepackage{style/btree} % Configuration for b-trees and b+-trees, !uses style file!
\usepackage{csquotes} % Context sensitive quotation facilities
\usepackage[yyyymmdd]{datetime} % Uses YEAR-MONTH-DAY format for dates
\renewcommand{\dateseparator}{-} % Sets dateseparator to '-'
\usepackage{fancyhdr} % Headers and footers
\pagestyle{fancy} % All pages have headers and footers
\fancyhead{}\renewcommand{\headrulewidth}{0pt} % Blank out the default header
\fancyfoot[L]{} % Custom footer text
\fancyfoot[C]{} % Custom footer text
\fancyfoot[R]{\thepage} % Custom footer text
\newcommand{\note}[1]{\marginpar{\scriptsize \textcolor{red}{#1}}} % Enables comments in red on margin
%----------------------------------------------------------------------------------------

View File

@ -0,0 +1,116 @@
@online{wolframnphard,
author = "Eric W. Weisstein",
title = "NP-Hard Problem",
publisher = "MathWorld = A Wolfram Web Resource",
url = "https://mathworld.wolfram.com/NP-HardProblem.html",
addendum = "(Accessed: 2023-03-03)"
}
@online{wolfram,
author = "David Terr",
title = "Polynomial Time",
url = "https://mathworld.wolfram.com/PolynomialTime.html",
addendum = "(Accessed: 2023-03-03)",
keywords = "p"
}
@online{slides,
author = "Frank Glavin",
title = "Topic Three: Algorithm Analysis \& Dynamic Programming Part II",
addendum = "Uploaded to Blackboard: 2023-02-17",
keywords = "p,np,"
}
@online{floydnondeterm,
author = "Robert W. Floyd",
title = "Nondeterministic Algorithms",
publisher = "Journal of the ACM",
date = "1967-10",
doi = "10.1145/321420.321422"
}
@online{britnpcomp,
author = "William L. Hosch",
title = "NP-complete problem",
publisher = "Encyclopedia Britannica",
date = "2023-03-10",
url = "https://www.britannica.com/science/NP-complete-problem#ref97458",
addendum="(Accessed: 2023-03-03)"
}
@online{techopedia,
title = "Non-Deterministic Polynomial Time (NP)",
publisher = "techopedia",
date = "2019-08-29",
url = "https://www.techopedia.com/definition/21028/non-deterministic-polynomial-time-np",
addendum="(Accessed: 2023-03-03)"
}
@online{fortnow,
author = "Lance Fortnow",
title = "The status of the P versus NP problem",
publisher = "Communications of the ACM",
date = "2009",
doi = " 10.1145/1562164.1562186"
}
@online{britpvsnpproblem,
author = "William L. Hosch",
title = "P versus NP problem",
publisher = "Encyclopedia Britannica",
date = "2023-02-22",
url = "https://www.britannica.com/science/P-versus-NP-problem",
addendum="(Accessed: 2023-03-03)"
}
@online{salesman,
author = "Stephan C. Carlson",
title = "Travelling salesman Problem",
publisher = "Encyclopedia Britannica",
date = "2023-02-05",
url = "https://www.britannica.com/science/traveling-salesman-problem",
addendum="(Accessed: 2023-03-03)"
}
@book{interact,
author = "Michael R. Garey \& David S. Johnson",
title = "Computers \& Intractability: A Guide to the Theory of NP-Completeness",
publisher = "W.H. Freeman",
date = "1979",
isbn = "0-7167-1045-5"
}
@online{halting,
author = "Karleigh Moore et al.",
title = "Halting Problem",
publisher = "Brilliant",
url = "https://brilliant.org/wiki/halting-problem/",
addendum="(Accessed: 2023-03-03)"
}
@online{npcompbrit,
author = "Erik Gregersen",
title = "NP-Complete Problem",
publisher = "Encyclopedia Britannica",
date = "2023-03-10",
url = "https://www.britannica.com/science/traveling-salesman-problem",
addendum="(Accessed: 2023-03-12)"
}
@online{cook,
author = "Stephen Cook",
title = "The complexity of theorem-proving procedures",
publisher = "Proceedings of the Third Annual ACM Symposium on Theory of Computing",
date = "1971",
doi = "10.1145/800157.805047"
}
@online{pvsnpbrit,
author = "William L. Hosch",
title = "P versus NP problem",
publisher = "Encyclopedia Britannica",
date = "2023-02-22",
url = "https://www.britannica.com/science/P-versus-NP-problem",
addendum="(Accessed: 2023-03-03)"
}
@online{poll,
author = "William I. Gasarch",
title = "The P=?NP poll",
publisher = "SIGACT News",
date = "2002-06",
doi = "10.1145/564585.564599"
}
@online{sipser,
author = "Michael Sipser",
title = "The history \& status of the P versus NP question",
publisher = "Proceedings of the twenty-fourth annual ACM Symposium on Theory of Computing",
date = "1992-07",
doi = "10.1145/129712.129771"
}

View File

@ -0,0 +1,5 @@
[0] Config.pm:306> INFO - This is Biber 2.18
[0] Config.pm:309> INFO - Logfile is 'references.bib.blg'
[47] biber:340> INFO - === Tue Mar 14, 2023, 17:38:23
[129] Utils.pm:410> ERROR - Cannot find 'references.bib.bcf'!
[129] Biber.pm:135> INFO - ERRORS: 1

View File

@ -0,0 +1,165 @@
% avm.sty -- for attribute-value matrices -- mar 29, 1992; rev. dec 6, 1993
% (c) 1992 christopher manning (manning@csli.stanford.edu) -- see avm.doc.tex
\newif\ifavmactive\newif\ifavmsorted\newif\ifavmlabeled
\newif\ifavmcenter\newif\ifavmbottom
\newif\ifavmbottomright\newif\ifavmtopleft\newif\ifavmtopright
\newdimen\avmdimen
\newbox\avmboxone\newbox\avmboxthree
\def\avmoptions#1{\avmactivefalse\avmsortedfalse\avmlabeledfalse
\avmcenterfalse\avmbottomfalse
\avmbottomrightfalse\avmtopleftfalse\avmtoprightfalse
\def\more{#1}\ifx\more\empty\else\avmjoptions#1,\@nil\fi}
\def\avmjoptions#1,#2\@nil{\def\more{#2}\csname avm#1true\endcsname
\ifx\more\empty\else\avmjoptions#2\@nil\fi}
\def\avmfont#1{\def\avmjfont{#1}}
\def\avmjfont{}
\def\avmvalfont#1{\def\avmjvalfont{#1}}
\def\avmjvalfont{}
\def\avmsortfont#1{\def\avmjsortfont{#1}}
\def\avmjsortfont{}
\def\avmhskip#1{\def\avmjhskip{#1}}
\def\avmjhskip{1em}
\def\avmbskip#1{\def\avmjbskip{#1}}
\def\avmjbskip{0em}
\def\avmvskip#1{\def\avmjvskip{#1}}
\def\avmjvskip{0.385ex}%was .3875
\def\avmjprolog#1{$\mskip-\thinmuskip
\left#1\hskip\avmjbskip\vcenter\bgroup\vskip\avmjvskip
\ialign\bgroup\avmjfont
\strut ##\unskip\hfil
&&\hskip\avmjhskip\avmjvalfont ##\unskip\hfil\cr}
\def\avmjpostlog#1{\crcr\egroup\vskip\avmjvskip\egroup
\hskip\avmjbskip\right#1\mskip-\thinmuskip$\ignorespaces}
\def\avmjcatcode{\let\lparen=(\let\rparen=)\catcode`\[=13\catcode`\]=13
\catcode`\<=13\catcode`\@=13\catcode`\(=13\catcode`\)=13
\catcode`\>=13\catcode`\|=13}
{\avmjcatcode % new group: redefine above catcodes as active
\gdef\specialavm{\avmjcatcode
\def({\avmjprolog\lparen}%
\def){\avmjpostlog\rparen}%
\def<{\avmjprolog\langle}%
\def>{\avmjpostlog\rangle}%
\ifavmsorted
\def[##1{\setbox\avmboxthree=\hbox{\avmjsortfont##1\/}\setbox2=\hbox
\bgroup\avmjprolog\lbrack}%
\def]{\avmjpostlog\rbrack\egroup\avmjsort}%
\else\ifavmlabeled
\def[##1{\def\more{##1}\setbox2=\hbox\bgroup\avmjprolog[}%
\def]{\avmjpostlog]\egroup\node{\more}{\box2}}%
\else
\def[{\avmjprolog\lbrack}%
\def]{\avmjpostlog\rbrack}%
\fi\fi
%
\def\<{$\langle$}\def\>{$\rangle$}%
\def\({\lparen}\def\){\rparen}%
\def\[{\lbrack}\def\]{\rbrack}%
\def|{$\,\vert\,$}%
\def@##1{\avmbox{##1}}%
} % end defn of \specialavm
} % restore active catcodes
\long\def\avm{\begingroup
\ifavmactive\specialavm
\else
\def\({\avmjprolog(}%
\def\){\avmjpostlog)}%
\def\<{\avmjprolog\langle}%
\def\>{\avmjpostlog\rangle}%
%
\ifavmsorted
\def\[##1{\setbox\avmboxthree=\hbox{\avmjsortfont##1\/}\setbox
2=\hbox\bgroup\avmjprolog[}%
\def\]{\avmjpostlog]\egroup\avmjsort}%
\else\ifavmlabeled
\def\[##1{\def\more{##1}\setbox2=\hbox\bgroup\avmjprolog[}%
\def\]{\avmjpostlog]\egroup\node{\more}{\box2}}%
\else
\def\[{\avmjprolog[}%
\def\]{\avmjpostlog]}%
\fi\fi
%
\def\|{$\,\vert\,$}%
\def\@##1{\avmbox{##1}}%
\fi % end not active
%
\ifx\LaTeX\undefined\def\\{\cr}% running under TeX
\else \def\\{\@tabularcr}% Leverage off LaTeX's \\*[dimen] options
\fi
\def\!{\node}%
\long\def\avmjsort{\dimen2=\ht2\advance\dimen2 by -.25\baselineskip
\global\dimen\avmdimen=\wd\avmboxthree
\ifavmtopleft \raise\dimen2\llap{\box\avmboxthree}\box2%
\else\ifavmtopright \box2\raise\dimen2\box\avmboxthree%
\else\ifavmbottomright \box2\lower\dimen2\box\avmboxthree%
\else \lower\dimen2\llap{\box\avmboxthree}\box2%
\fi\fi\fi}%
\long\def\sort##1##2{\setbox2=\hbox{##2}\setbox
\avmboxthree=\hbox{\avmjsortfont##1\/}\dimen2=\ht2
\advance\dimen2 by -.25\baselineskip
\ifavmtopleft \raise\dimen2\box\avmboxthree\box2%
\else\ifavmtopright \box2\raise\dimen2\box\avmboxthree%
\else\ifavmbottomright \box2\lower\dimen2\box\avmboxthree%
\else \lower\dimen2\box\avmboxthree\box2%
\fi\fi\fi}%
\long\def\osort##1##2{\setbox2=\hbox{##2}\setbox
\avmboxthree=\hbox{\avmjsortfont ##1\/}\avmjsort}%
\def\avml{\avmjprolog.}%
\def\avmr{\avmjpostlog.}%
\def\avmb##1{\node{##1}{\lbrack\;\rbrack}}%
\def\avmd##1{\node{##1}{---}}%
\def\q##1{\ifx ##1\{$\lbrace$\else
\ifx ##1\}$\rbrace$\else
\ifx ##1<$\langle$\else
\ifx ##1>$\rangle$\fi \fi \fi \fi}%
\def\{{\avmjprolog\lbrace}%
\def\}{\avmjpostlog\rbrace}%
\def\;{\hskip\avmjhskip}%
\def\avmspan##1{\multispan2\strut ##1\expandafter\hfil}%
\avmjfont
\openup\avmjvskip
\setbox\avmboxone=\hbox\bgroup\ignorespaces
} % end defn of \avm
\def\endavm{\egroup\ifvmode\leavevmode\fi % this if is useful!
\ifavmsorted\null\hskip\dimen\avmdimen\fi
\ifavmcenter
\box\avmboxone
\else \ifavmbottom
\lower.575\baselineskip\hbox{\vbox{\box\avmboxone\null}}%
\else
% the next bit is ripped off from Emma's \evnup in lingmacros.sty
\dimen2=\ht\avmboxone\advance\dimen2 by -.725\baselineskip
\lower\dimen2\box\avmboxone
\fi \fi \endgroup}
% based on TeXbook exercise 21.3
\def\avmbox#1{\setbox2=\hbox{$\scriptstyle #1$}\lower.2ex\vbox{\hrule
\hbox{\vrule\kern1.25pt
\vbox{\kern1.25pt\box2\kern1.25pt}\kern1.25pt\vrule}\hrule}}
% ============ COSTOM CONFIGURATION =============
\avmfont{\sc}
\avmoptions{sorted,active}
\avmvalfont{\rm}
\avmsortfont{\scriptsize\it}
% ===============================================

View File

@ -0,0 +1,131 @@
%% Last Modified: Thu Oct 18 18:26:25 2007.
\NeedsTeXFormat{LaTeX2e}
\ProvidesPackage{style/btree}
\typeout{Document Style `weiw_BTree - Support drawing B+-Tree (ver 0.999)}
\RequirePackage{tikz}
\RequirePackage{ifthen}
% use libraries
\usetikzlibrary{arrows,shapes,decorations,matrix}
%% global declaration
\tikzstyle{btreeptr} = [draw, semithick, minimum height=2em]
\tikzstyle{btreeval} = [draw, semithick, minimum size=2em]
\tikzstyle{btreevale} = [draw,semithick, minimum size=2em]
\tikzstyle{btlink} = [draw, semithick, ->, >=triangle 45]
%% macro
%% helper macros
\newcommand{\suppressemptystr}[1]{% leave blank for entries in leaf nodes
\ifthenelse{\equal{#1}{}}%
{%
\relax%
}%
% Else
{%
#1\textsuperscript{*}%
}%
}%
\newcommand{\xyshift}[3]{% help to place the nodes
\begin{scope}[xshift=#1, yshift=#2]
#3
\end{scope}%
}
%% Common btree macros
\newcommand{\btreelink}[2]{% #1: src node; #2: dest node;
\draw[btlink] ([yshift=3pt] #1.south) -- (#2-b.north);
}
\newcommand{\btreelinknorth}[2]{% #1: src node; #2: dest node;
\draw[btlink] ([yshift=3pt] #1.south) -- (#2.north);
}
\newcommand{\btreetriangle}[2]{% #1: node name; #2 text inside
\node[anchor=north, regular polygon, regular polygon sides=3, draw] (#1) {#2};
}
%%======================================================================
%% btree with capacity = 4
\newcommand{\btreeinodefour}[5]{%
\matrix [ampersand replacement=\&] (#1)
{
\node[btreeptr] (#1-1) {\vphantom{1}}; \& \node[btreeval] (#1-a) {#2}; \&
\node[btreeptr] (#1-2) {\vphantom{1}}; \& \node[btreeval] (#1-b) {#3}; \&
\node[btreeptr] (#1-3) {\vphantom{1}}; \& \node[btreeval] (#1-c) {#4}; \&
\node[btreeptr] (#1-4) {\vphantom{1}}; \& \node[btreeval] (#1-d) {#5}; \&
\node[btreeptr] (#1-5) {\vphantom{1}}; \\
};
}
\newcommand{\btreelnodefour}[5]{%
\matrix [ampersand replacement=\&, outer sep=0pt, matrix anchor=north] (#1)
{
\node[btreevale] (#1-a) {\suppressemptystr{#2}}; \&
\node[btreevale] (#1-b) {\suppressemptystr{#3}}; \&
\node[btreevale] (#1-c) {\suppressemptystr{#4}}; \&
\node[btreevale] (#1-d) {\suppressemptystr{#5}}; \\
};
}
%%======================================================================
%% btree with capacity = 3
\newcommand{\btreeinodethree}[4]{%
\matrix [ampersand replacement=\&] (#1)
{
\node[btreeptr] (#1-1) {\vphantom{1}}; \& \node[btreeval] (#1-a) {#2}; \&
\node[btreeptr] (#1-2) {\vphantom{1}}; \& \node[btreeval] (#1-b) {#3}; \&
\node[btreeptr] (#1-3) {\vphantom{1}}; \& \node[btreeval] (#1-c) {#4}; \&
\node[btreeptr] (#1-4) {\vphantom{1}}; \\
};
}
\newcommand{\btreelnodethree}[4]{%
\matrix [ampersand replacement=\&, outer sep=0pt, matrix anchor=north] (#1)
{
\node[btreevale] (#1-a) {\suppressemptystr{#2}}; \&
\node[btreevale] (#1-b) {\suppressemptystr{#3}}; \&
\node[btreevale] (#1-c) {\suppressemptystr{#4}}; \\
};
}
%%======================================================================
%% btree with capacity = 2
\newcommand{\btreeinodetwo}[4]{%
\matrix [ampersand replacement=\&] (#1)
{
\node[btreeptr] (#1-1) {\vphantom{1}}; \& \node[btreeval] (#1-a) {#2}; \&
\node[btreeptr] (#1-2) {\vphantom{1}}; \& \node[btreeval] (#1-b) {#3}; \&
\node[btreeptr] (#1-3) {\vphantom{1}}; \\
};
}
\newcommand{\btreelnodetwo}[3]{%
\matrix [ampersand replacement=\&, outer sep=0pt, matrix anchor=north] (#1)
{
\node[btreevale] (#1-a) {\suppressemptystr{#2}}; \&
\node[btreevale] (#1-b) {\suppressemptystr{#3}}; \\
};
}
%%======================================================================
%% simple example
% \begin{center}
% \scalebox{0.7}{
% \begin{tikzpicture}
% %
% \btreeinodefour{root}{13}{17}{24}{30};
% \xyshift{-40mm}{-20mm}{\btreelnodefour{n1}{2}{3}{5}{7}}
% \xyshift{-0mm}{-20mm}{\btreelnodefour{n2}{14}{16}{}{}}
% \xyshift{40mm}{-20mm}{\btreelnodefour{n3}{19}{20}{22}{}}
% \xyshift{80mm}{-20mm}{\btreelnodefour{n4}{24}{27}{29}{}}
% \xyshift{120mm}{-20mm}{\btreelnodefour{n5}{33}{34}{38}{39}}
% %
% \foreach \x in {1,2,...,5} { \btreelink{root-\x}{n\x} }
% \end{tikzpicture}
% }
% \end{center}

Binary file not shown.

After

Width:  |  Height:  |  Size: 66 KiB

View File

@ -0,0 +1,38 @@
% Source: ss17_wissschreib (Eva)
\lstset{
basicstyle=\ttfamily\scriptsize\mdseries,
keywordstyle=\bfseries\color[rgb]{0.171875, 0.242188, 0.3125},
identifierstyle=,
commentstyle=\color[rgb]{0.257813, 0.15625, 0},
stringstyle=\itshape\color[rgb]{0.0195313, 0.195313, 0.0117188},
numbers=left,
numberstyle=\tiny,
stepnumber=1,
breaklines=true,
frame=none,
showstringspaces=false,
tabsize=4,
backgroundcolor=\color[rgb]{0.98,0.98,0.98},
captionpos=b,
float=htbp,
language=Python,
xleftmargin=15pt,
xrightmargin=15pt
}
%(deutsche) Sonderzeichen
\lstset{literate=%
{Ä}{{\"A}}1
{Ö}{{\"O}}1
{Ü}{{\"U}}1
{ä}{{\"a}}1
{ö}{{\"o}}1
{ü}{{\"u}}1
{ß}{{\ss}}1
}
%Verwendung im Text:
%-> \begin{lstlisting}[language=Python,firstnumber=27] ... \end{lstlisting}
%-> \begin{lstlisting}[language=Python,numbers=none] ... \end{lstlisting}
%-> \lstinline[language=JAVA]{...}

View File

@ -0,0 +1,123 @@
/**
* A class that represents nodes in a binary tree.
*
* @author Frank M. Carrano
* @version 2.0
*/
class BinaryNode<T> implements BinaryNodeInterface<T>, java.io.Serializable
{
private static final long serialVersionUID = 6828929352995534482L; // needed for serializable objects
private T data;
private BinaryNode<T> left;
private BinaryNode<T> right;
public BinaryNode()
{
this(null); // call next constructor
} // end default constructor
public BinaryNode(T dataPortion)
{
this(dataPortion, null, null); // call next constructor
} // end constructor
public BinaryNode(T dataPortion, BinaryNode<T> leftChild,
BinaryNode<T> rightChild)
{
data = dataPortion;
left = leftChild;
right = rightChild;
} // end constructor
public T getData()
{
return data;
} // end getData
public void setData(T newData)
{
data = newData;
} // end setData
public BinaryNodeInterface<T> getLeftChild()
{
return left;
} // end getLeftChild
public BinaryNodeInterface<T> getRightChild()
{
return right;
} // end getRightChild
public void setLeftChild(BinaryNodeInterface<T> leftChild)
{
left = (BinaryNode<T>)leftChild;
} // end setLeftChild
public void setRightChild(BinaryNodeInterface<T> rightChild)
{
right = (BinaryNode<T>)rightChild;
} // end setRightChild
public boolean hasLeftChild()
{
return left != null;
} // end hasLeftChild
public boolean hasRightChild()
{
return right != null;
} // end hasRightChild
public boolean isLeaf()
{
return (left == null) && (right == null);
} // end isLeaf
// 26.06
public BinaryNodeInterface<T> copy()
{
BinaryNode<T> newRoot = new BinaryNode<T>(data);
if (left != null)
newRoot.left = (BinaryNode<T>)left.copy();
if (right != null)
newRoot.right = (BinaryNode<T>)right.copy();
return newRoot;
} // end copy
// 26.11
public int getHeight()
{
return getHeight(this); // call private getHeight
} // end getHeight
// 26.11
private int getHeight(BinaryNode<T> node)
{
int height = 0;
if (node != null)
height = 1 + Math.max(getHeight(node.left), getHeight(node.right));
return height;
} // end getHeight
// 26.11
public int getNumberOfNodes()
{
int leftNumber = 0;
int rightNumber = 0;
if (left != null)
leftNumber = left.getNumberOfNodes();
if (right != null)
rightNumber = right.getNumberOfNodes();
return 1 + leftNumber + rightNumber;
} // end getNumberOfNodes
} // end BinaryNode

View File

@ -0,0 +1,56 @@
/**
* An interface for a node in a binary tree.
*
* @author Frank M. Carrano
* @version 2.0
*/
interface BinaryNodeInterface<T>
{
/** Task: Retrieves the data portion of the node.
* @return the object in the data portion of the node */
public T getData();
/** Task: Sets the data portion of the node.
* @param newData the data object */
public void setData(T newData);
/** Task: Retrieves the left child of the node.
* @return the node that is this nodeÕs left child */
public BinaryNodeInterface<T> getLeftChild();
/** Task: Retrieves the right child of the node.
* @return the node that is this nodeÕs right child */
public BinaryNodeInterface<T> getRightChild();
/** Task: Sets the nodeÕs left child to a given node.
* @param leftChild a node that will be the left child */
public void setLeftChild(BinaryNodeInterface<T> leftChild);
/** Task: Sets the nodeÕs right child to a given node.
* @param rightChild a node that will be the right child */
public void setRightChild(BinaryNodeInterface<T> rightChild);
/** Task: Detects whether the node has a left child.
* @return true if the node has a left child */
public boolean hasLeftChild();
/** Task: Detects whether the node has a right child.
* @return true if the node has a right child */
public boolean hasRightChild();
/** Task: Detects whether the node is a leaf.
* @return true if the node is a leaf */
public boolean isLeaf();
/** Task: Counts the nodes in the subtree rooted at this node.
* @return the number of nodes in the subtree rooted at this node */
public int getNumberOfNodes();
/** Task: Computes the height of the subtree rooted at this node.
* @return the height of the subtree rooted at this node */
public int getHeight();
/** Task: Copies the subtree rooted at this node.
* @return the root of a copy of the subtree rooted at this node */
public BinaryNodeInterface<T> copy();
} // end BinaryNodeInterface

View File

@ -0,0 +1,139 @@
/**
* A class that implements the ADT binary tree.
*
* @author Frank M. Carrano
* @version 2.0
*/
public class BinaryTree<T> implements BinaryTreeInterface<T>, java.io.Serializable
{
private static final long serialVersionUID = -1932834476575953631L;
private BinaryNodeInterface<T> root;
public BinaryTree()
{
root = null;
} // end default constructor
public BinaryTree(T rootData)
{
root = new BinaryNode<T>(rootData);
} // end constructor
public BinaryTree(T rootData, BinaryTree<T> leftTree,
BinaryTree<T> rightTree)
{
privateSetTree(rootData, leftTree, rightTree);
} // end constructor
public void setTree(T rootData)
{
root = new BinaryNode<T>(rootData);
} // end setTree
public void setTree(T rootData, BinaryTreeInterface<T> leftTree,
BinaryTreeInterface<T> rightTree)
{
privateSetTree(rootData, (BinaryTree<T>)leftTree,
(BinaryTree<T>)rightTree);
} // end setTree
// 26.08
private void privateSetTree(T rootData, BinaryTree<T> leftTree,
BinaryTree<T> rightTree)
{
root = new BinaryNode<T>(rootData);
if ((leftTree != null) && !leftTree.isEmpty())
root.setLeftChild(leftTree.root);
if ((rightTree != null) && !rightTree.isEmpty())
{
if (rightTree != leftTree)
root.setRightChild(rightTree.root);
else
root.setRightChild(rightTree.root.copy());
} // end if
if ((leftTree != null) && (leftTree != this))
leftTree.clear();
if ((rightTree != null) && (rightTree != this))
rightTree.clear();
} // end privateSetTree
private BinaryNode<T> copyNodes() // not essential
{
return (BinaryNode<T>)root.copy();
} // end copyNodes
// 26.09
public T getRootData()
{
T rootData = null;
if (root != null)
rootData = root.getData();
return rootData;
} // end getRootData
// 26.09
public boolean isEmpty()
{
return root == null;
} // end isEmpty
// 26.09
public void clear()
{
root = null;
} // end clear
// 26.09
protected void setRootData(T rootData)
{
root.setData(rootData);
} // end setRootData
// 26.09
protected void setRootNode(BinaryNodeInterface<T> rootNode)
{
root = rootNode;
} // end setRootNode
// 26.09
protected BinaryNodeInterface<T> getRootNode()
{
return root;
} // end getRootNode
// 26.10
public int getHeight()
{
return root.getHeight();
} // end getHeight
// 26.10
public int getNumberOfNodes()
{
return root.getNumberOfNodes();
} // end getNumberOfNodes
// 26.12
public void inorderTraverse()
{
inorderTraverse(root);
} // end inorderTraverse
private void inorderTraverse(BinaryNodeInterface<T> node)
{
if (node != null)
{
inorderTraverse(node.getLeftChild());
System.out.println(node.getData());
inorderTraverse(node.getRightChild());
} // end if
} // end inorderTraverse
} // end BinaryTree

View File

@ -0,0 +1,20 @@
/**
* An interface for the ADT binary tree.
*
* @author Frank M. Carrano
* @version 2.0
*/
public interface BinaryTreeInterface<T> extends TreeInterface<T>
{
/** Task: Sets an existing binary tree to a new one-node binary tree.
* @param rootData an object that is the data in the new treeÕs root
*/
public void setTree(T rootData);
/** Task: Sets an existing binary tree to a new binary tree.
* @param rootData an object that is the data in the new treeÕs root
* @param leftTree the left subtree of the new tree
* @param rightTree the right subtree of the new tree */
public void setTree(T rootData, BinaryTreeInterface<T> leftTree,
BinaryTreeInterface<T> rightTree);
} // end BinaryTreeInterface

View File

@ -0,0 +1,217 @@
import java.util.*;
import java.io.*;
@SuppressWarnings("unchecked") // ignoring warnings lol
public class GuessingGame implements Serializable {
private static BinaryTree<String> tree = new BinaryTree<String>();
private static String input; // string to which input will be read
private static Scanner sc = new Scanner(System.in); // scanner to read in input
public static void main(String[] args) {
while (1 == 1) {
// pick the tree that will be used for the game, either from a file or built-in
loadTree();
// play the game
gameplay();
playAgainLoop: while (1 == 1) {
System.out.printf("Enter '1' to play again, '2' to quit, or '3' to save the tree to a file\n> ");
input = sc.nextLine();
switch (input) {
case "1": // going back to start of loop
break playAgainLoop;
case "2":
System.exit(0);
break playAgainLoop;
case "3": // storing the tree, this should not break the loop
storeTree();
break;
default:
// loop
}
}
}
}
// method that serializes a tree object to a file
public static void storeTree() {
// scanning in the name of the file from the user
System.out.printf("Enter the name of the file that it the tree should be stored as\n> ");
input = sc.nextLine();
try {
// creating output streams
FileOutputStream fos = new FileOutputStream(input);
ObjectOutputStream oos = new ObjectOutputStream(fos);
// writing the tree object ot the file
oos.writeObject(tree);
// closing output streams
oos.close();
fos.close();
}
// catching IOExceptions
catch (IOException E) {
System.out.println(E);
System.exit(1);
}
}
// method to load a tree, either from a file, from memory, or hardcoded in
public static void loadTree() {
// looping until an appropriate choice is made
loadTreeLoop: while (1 == 1) {
System.out.printf("Load a tree from a file? If no, then the built-in tree will be used. y/n\n> ");
input = sc.nextLine();
switch (input) {
case "y":
// looping until valid filename is entered
while (1 == 1) {
System.out.printf("Enter the file from which the tree should be loaded\n> ");
input = sc.nextLine();
File treefile = new File(input);
// breaking if the file exists
if (treefile.exists()) {
break;
}
}
try {
// creating input streams
FileInputStream fis = new FileInputStream(input);
ObjectInputStream ois = new ObjectInputStream(fis);
// deserializing tree object
tree = (BinaryTree<String>) ois.readObject();
// closing input streams
ois.close();
fis.close();
}
// printing errors and crashing
catch(IOException E) {
System.out.println(E);
System.exit(1);
}
catch (ClassNotFoundException E) {
System.out.println(E);
System.exit(1);
}
break loadTreeLoop;
case "n":
// if no tree is defined building the default tree
if (tree.getRootNode() == null) {
// first the leaves
BinaryTree<String> cowTree = new BinaryTree<String>("Is it a cow?");
BinaryTree<String> dogTree = new BinaryTree<String>("Is it a dog?");
BinaryTree<String> fishTree = new BinaryTree<String>("Is it a goldfish?");
BinaryTree<String> geckoTree = new BinaryTree<String>("Is it a gecko?");
// Now the subtrees joining leaves:
BinaryTree<String> mammalTree = new BinaryTree<String>("Is it a farm animal?", cowTree, dogTree);
BinaryTree<String> notMammalTree = new BinaryTree<String>("Is it a type of fish?", fishTree, geckoTree);
// Now the root
tree.setTree("Is it a mammal?", mammalTree, notMammalTree);
}
break loadTreeLoop;
default:
// loop
}
}
}
public static void gameplay() {
System.out.println("Enter 'y' for 'yes', 'n' for 'no'");
BinaryNodeInterface<String> curr = tree.getRootNode(); // current node
// looping until a leaf node is reached
while (!curr.isLeaf()) {
// looping until an appropriate reply is given by the user
answerloop: while (1 == 1) {
// printing the question & scanning in the answer
System.out.printf(curr.getData() + "\n> ");
input = sc.nextLine();
switch (input) {
case "y": // continuing via left node if answer to question is yes
curr = curr.getLeftChild();
break answerloop;
case "n": // continuing via right node if answer to question is no
curr = curr.getRightChild();
break answerloop;
default:
// loop
}
}
}
// making a guess
// looping until an appropriate reply is given by the user
guessloop: while (1 == 1) {
// printing the question & scanning in the answer
System.out.printf(curr.getData() + "\n> ");
input = sc.nextLine();
switch (input) {
case "y": // printing a success message if the answer is yes
System.out.println("Success! The guess was correct");
break guessloop;
case "n": // inserting a new question and putting the two guesses beneath it if wrong
System.out.printf("Enter the animal that you were thinking of\n> ");
String thinkingOf = sc.nextLine();
String wrong = curr.getData();
// ask the user for a question to distinguish the wrong guess from the correct answer
System.out.printf("Enter a question to distinguish %s from '%s'\n> ", thinkingOf, wrong);
String question = sc.nextLine();
// replacing the current node with the question to distinguish it
curr.setData(question);
// asking the user for the correct answer to the question for the animal they were thinking of
addNodeLoop: while (1 == 1) { // looping until an appropriate answer is given
System.out.printf("Enter the correct answer to the question that you entered for %s (y or n)\n> ", thinkingOf);
input = sc.nextLine();
switch (input) {
case "y": // adding thinkingOf to the left of the question node if the answer is yes
curr.setLeftChild(new BinaryNode<String>("Is it a " + thinkingOf + "?"));
curr.setRightChild(new BinaryNode<String>(wrong));
break addNodeLoop;
case "n": // adding thinkingOf to the left of the question node if the answer is no
curr.setLeftChild(new BinaryNode<String>(wrong));
curr.setRightChild(new BinaryNode<String>("Is it a " + thinkingOf + "?"));
break addNodeLoop;
default:
// loop
}
}
break guessloop;
default:
// loop
}
}
}
}

View File

@ -0,0 +1,14 @@
/**
* An interface for basic operations of a tree.
*
* @author Frank M. Carrano
* @version 2.0
*/
public interface TreeInterface<T>
{
public T getRootData();
public int getHeight();
public int getNumberOfNodes();
public boolean isEmpty();
public void clear();
} // end TreeInterface

View File

@ -0,0 +1,85 @@
<?xml version="1.0" standalone="yes"?>
<!-- logreq request file -->
<!-- logreq version 1.0 / dtd version 1.0 -->
<!-- Do not edit this file! -->
<!DOCTYPE requests [
<!ELEMENT requests (internal | external)*>
<!ELEMENT internal (generic, (provides | requires)*)>
<!ELEMENT external (generic, cmdline?, input?, output?, (provides | requires)*)>
<!ELEMENT cmdline (binary, (option | infile | outfile)*)>
<!ELEMENT input (file)+>
<!ELEMENT output (file)+>
<!ELEMENT provides (file)+>
<!ELEMENT requires (file)+>
<!ELEMENT generic (#PCDATA)>
<!ELEMENT binary (#PCDATA)>
<!ELEMENT option (#PCDATA)>
<!ELEMENT infile (#PCDATA)>
<!ELEMENT outfile (#PCDATA)>
<!ELEMENT file (#PCDATA)>
<!ATTLIST requests
version CDATA #REQUIRED
>
<!ATTLIST internal
package CDATA #REQUIRED
priority (9) #REQUIRED
active (0 | 1) #REQUIRED
>
<!ATTLIST external
package CDATA #REQUIRED
priority (1 | 2 | 3 | 4 | 5 | 6 | 7 | 8) #REQUIRED
active (0 | 1) #REQUIRED
>
<!ATTLIST provides
type (static | dynamic | editable) #REQUIRED
>
<!ATTLIST requires
type (static | dynamic | editable) #REQUIRED
>
<!ATTLIST file
type CDATA #IMPLIED
>
]>
<requests version="1.0">
<internal package="biblatex" priority="9" active="0">
<generic>latex</generic>
<provides type="dynamic">
<file>CT2109-Assignment-05.bcf</file>
</provides>
<requires type="dynamic">
<file>CT2109-Assignment-05.bbl</file>
</requires>
<requires type="static">
<file>blx-dm.def</file>
<file>blx-compat.def</file>
<file>biblatex.def</file>
<file>standard.bbx</file>
<file>numeric.bbx</file>
<file>numeric.cbx</file>
<file>biblatex.cfg</file>
<file>english.lbx</file>
</requires>
</internal>
<external package="biblatex" priority="5" active="0">
<generic>biber</generic>
<cmdline>
<binary>biber</binary>
<infile>CT2109-Assignment-05</infile>
</cmdline>
<input>
<file>CT2109-Assignment-05.bcf</file>
</input>
<output>
<file>CT2109-Assignment-05.bbl</file>
</output>
<provides type="dynamic">
<file>CT2109-Assignment-05.bbl</file>
</provides>
<requires type="dynamic">
<file>CT2109-Assignment-05.bcf</file>
</requires>
<requires type="editable">
<file>ecl.bib</file>
</requires>
</external>
</requests>

View File

@ -0,0 +1,187 @@
% THIS DOCUMENT HAS BEEN EDITED FOR EXPERIMENTATION PURPOSES AND THUS NO LONGER IS THE SAME AS THE DOCUMENT SUBMITTED FOR GRADING
\documentclass[a4paper]{article}
\usepackage{listings}
\usepackage{xcolor}
\definecolor{codegreen}{rgb}{0,0.6,0}
\definecolor{codegray}{rgb}{0.5,0.5,0.5}
\definecolor{codeorange}{rgb}{1,0.49,0}
\definecolor{backcolour}{rgb}{0.95,0.95,0.96}
\usepackage{sourcecodepro}
\usepackage{pgfplots}
\pgfplotsset{width=\textwidth,compat=1.9}
\lstdefinestyle{mystyle}{
backgroundcolor=\color{backcolour},
commentstyle=\color{codegray},
keywordstyle=\color{codeorange},
numberstyle=\tiny\color{codegray},
stringstyle=\color{codegreen},
basicstyle=\ttfamily\footnotesize,
breakatwhitespace=false,
breaklines=true,
captionpos=b,
keepspaces=true,
numbers=left,
numbersep=5pt,
showspaces=false,
showstringspaces=false,
showtabs=false,
tabsize=2,
xleftmargin=10pt,
}
\lstset{style=mystyle}
\input{head}
\hypersetup{
colorlinks,
urlcolor = black
}
\raggedbottom
\begin{document}
% \renewcommand{\verbatim@font}{\ttfamily\small}
%-------------------------------
% TITLE SECTION
%-------------------------------
\fancyhead[C]{}
\hrule \medskip % Upper rule
\begin{minipage}{0.295\textwidth}
\begin{raggedright}
\footnotesize
Andrew Hayes \hfill\\
21321503 \hfill\\
\href{mailto:a.hayes18@nuigalway.ie}{a.hayes18@nuigalway.ie}
\end{raggedright}
\end{minipage}
\begin{minipage}{0.4\textwidth}
\begin{centering}
\large
CT2109 Assignment 3\\
\normalsize
\end{centering}
\end{minipage}
\begin{minipage}{0.295\textwidth}
\begin{raggedleft}
\footnotesize
\today \hfill\\
\end{raggedleft}
\end{minipage}
\medskip\hrule
\medskip
\begin{centering}
Expandable Binary Tree Guessing Game\\
\end{centering}
\medskip\hrule
\bigskip
\section{Problem Statement}
The problem of this assignment is to create an expandable binary tree guessing game, not unlike the popular web game ``Akinator''.
There will be a tree which will consist of question nodes.
Each node will contain some String data: this will be the question that the node represents.
These questions will be ``yes'' or ``no'' questions.
Each node will have a maximum of two children.
These children will represent the next question after the parent has been answered.
\\\\
The tree will be traversed node by node, starting at the root node.
Each node's data will be printed to the user, and they will be prompted to answer the question by entering either ``y'' or ``n''.
If the user answers ``y'', then the next node traversed will be the left child of the current node, but if the answer is ``n'', then the next node will be the right child.
Nodes on the left represent an affirmative answer to the parent's question, and nodes on the right will represent a negative answer to the parent's question.
\\\\
Eventually, a leaf node will be reached (a node with no children).
If a node is a leaf node, then this means that this node represents a guess by the game.
These guesses will be in the form of a ``yes'' or ``no'' question, e.g., ``Is it a dog?''.
If the user enters ``y'', then the program has won, and the game will be over.
If the user enters ``n'', then the user won the game, and the program will expand it's knowledge by asking the user for a question that distinguishes the game's guess from the correct answer.
This question will then be inserted in the tree to replace the leaf node that was the game's guess.
The user will then be asked if the answer to the distinguishing question for the correct answer should be ``y'' or ``n'', and the initial incorrect guess \& the correct answer will be inserted as children
of this parent node in the appropriate positions, depending on what the answer to the distinguishing question is.
\\\\
This program will also implement the ability to save the binary tree to a file and to load a binary tree from a file.
The standard way of doing such a thing in Java is to implement the \verb|Serializable| interface.
This allows for an object to be written to a file and recovered at a later date, after an indefinite time period has elapsed, regardless of whether the program has been running or not.
\section{Analysis \& Design Notes}
The main method of the program will consist of an infinite loop.
The loop will firstly call a \verb|loadTree()| method which does one of three things: load a tree from a file, generate a pre-built tree that's hardcoded in, or use an already defined tree in memory, if one
exists.
The user will be asked whether or not the tree should be loaded from a file.
A case statement will be used to react to the user's inputs, ``y'' for ``yes'', ``n'' for ``no''.
This will loop until a valid input is given.
If the answer is ``y'', then the user will be prompted to enter the name of the file from which the tree should be loaded.
This will loop until a valid filename is given (one that exists).
Then, the program will attempt to de-serialize the file into a \verb|BinaryTree<String>| object, throwing an error and exiting if any problems are encountered.
Because this is not necessarily a safe operation, we presume that the user knows only to supply the program with valid files, and do not check for safety, instead opting to use \verb|@SuppressWarnings("unchecked")|
at the top of the class definition.
Although it would of course be better practise to ensure file safety, this is somewhat beyond the scope of the assignment, and not really relevant to the theory at hand.
If the user opts to not load the tree from a file, one will be generated from some hardcoded values, provided that the existing tree is \verb|null|.
If the existing tree is not \verb|null|, then the existing tree is used instead.
This will only occur on rematches.
\\\\
After the tree has been loaded, the \verb|gameplay()| method will be called, and the game will begin.
This method will loop over each node, starting at the root node, while the current node is not a leaf node (i.e., while the current node has children).
The data of this node (a question String) will be printed out, and the user will enter ``y'' or ``n'' to answer the question.
If the user enters anything else, it will loop on this question until an appropriate answer is given.
Then, depending on the input, the current node will be replaced with the left or the right child of the current node, left for ``y'', right for ``n''.
An appropriate answer will break out of the loop using a label.
\\\\
When a leaf node is reached, the loop will end and a guess will be made.
The user will be asked to verify the guess, and this will loop until an appropriate answer is given.
If the user confirms the guess as correct, the game ends, and the user will be presented with a game menu.
Otherwise, the user will be asked what they were thinking of.
They will then be asked to provide a question to distinguish what they were thinking of from the program's guess, and the appropriate answer to that distinguishing question for the answer they were thinking of.
The current node will then be replaced with the distinguishing question, and the guessed answer \& the real answer will become child nodes of this node, placed appropriately on the right or left according
to the user's instructions.
\\\\
Finally, after the \verb|gameplay()| method has completed execution, the user will be presented with the options to play again, quit, or save the tree to a file.
If they choose play again, the infinite loop simply repeats, and they are presented with the \verb|loadTree()| operations again.
If they choose to quit, the program will exit with code \verb|0|.
If they choose to save the tree to a file, the \verb|storeTree()| method will be called.
This method prompts the user to enter a filename to which the serialized tree should be saved.
The serialized object is then written to this file, overwriting any data that was already in that file, if it existed.
\section{Code}
\lstinputlisting[language=Java, breaklines=true, title={GuessingGame.java}]{../code/GuessingGame.java}
\newpage
\section{Testing}
The first thing to be tested is just basic functionality of the game.
The screenshot below shows basic testing with valid \& invalid input, but only with animals known to the game.
Invalid input should just be re-prompted to be entered.
\begin{figure}[h]
\centering \includegraphics[width=0.7\textwidth]{./images/first.png}
\caption{Basic Testing of the Game with the In-Built Tree}
\end{figure}
The next bit of testing is testing of an animal that the game doesn't know, adding it to the tree, and saving it to a file, as shown in the screenshot below.
\begin{figure}[h]
\centering \includegraphics[width=0.7\textwidth]{./images/saving.png}
\caption{Testing of the Saving a Tree to a File}
\end{figure}
\newpage
The next bit of testing is testing restoring a binary tree from a file on disk, using the file made above.
\begin{figure}[h]
\centering \includegraphics[width=0.7\textwidth]{./images/restore.png}
\caption{Testing of the Restoring a Tree from a File}
\end{figure}
Testing trying to load a tree from a non-existent file on disk. This should loop until a valid input is given.
\begin{figure}[h]
\centering \includegraphics[width=0.7\textwidth]{./images/invalidtree.png}
\caption{Testing Trying to Load a Non-Existent Tree File from Disk}
\end{figure}
Testing trying to load a normal text file as a binary tree file.
Should throw an error and exit gracefully.
\begin{figure}[h]
\centering \includegraphics[width=0.7\textwidth]{./images/faketree.png}
\caption{Testing Trying to Load a Non-Binary Tree File from Disk}
\end{figure}
\end{document}

View File

@ -0,0 +1,49 @@
\addtolength{\hoffset}{-2.25cm}
\addtolength{\textwidth}{4.5cm}
\addtolength{\voffset}{-3.25cm}
\addtolength{\textheight}{5cm}
\setlength{\parskip}{0pt}
\setlength{\parindent}{0in}
%----------------------------------------------------------------------------------------
% PACKAGES AND OTHER DOCUMENT CONFIGURATIONS
%----------------------------------------------------------------------------------------
\usepackage{blindtext} % Package to generate dummy text
\usepackage{charter} % Use the Charter font
\usepackage[utf8]{inputenc} % Use UTF-8 encoding
\usepackage{microtype} % Slightly tweak font spacing for aesthetics
\usepackage[english]{babel} % Language hyphenation and typographical rules
\usepackage{amsthm, amsmath, amssymb} % Mathematical typesetting
\usepackage{float} % Improved interface for floating objects
\usepackage[final, colorlinks = true,
linkcolor = black,
citecolor = black]{hyperref} % For hyperlinks in the PDF
\usepackage{graphicx, multicol} % Enhanced support for graphics
\usepackage{xcolor} % Driver-independent color extensions
\usepackage{marvosym, wasysym} % More symbols
\usepackage{rotating} % Rotation tools
\usepackage{censor} % Facilities for controlling restricted text
\usepackage{listings, style/lstlisting} % Environment for non-formatted code, !uses style file!
\usepackage{pseudocode} % Environment for specifying algorithms in a natural way
\usepackage{style/avm} % Environment for f-structures, !uses style file!
\usepackage{booktabs} % Enhances quality of tables
\usepackage{tikz-qtree} % Easy tree drawing tool
\tikzset{every tree node/.style={align=center,anchor=north},
level distance=2cm} % Configuration for q-trees
\usepackage{style/btree} % Configuration for b-trees and b+-trees, !uses style file!
\usepackage[backend=biber,style=numeric,
sorting=nyt]{biblatex} % Complete reimplementation of bibliographic facilities
\addbibresource{ecl.bib}
\usepackage{csquotes} % Context sensitive quotation facilities
\usepackage[yyyymmdd]{datetime} % Uses YEAR-MONTH-DAY format for dates
\renewcommand{\dateseparator}{-} % Sets dateseparator to '-'
\usepackage{fancyhdr} % Headers and footers
\pagestyle{fancy} % All pages have headers and footers
\fancyhead{}\renewcommand{\headrulewidth}{0pt} % Blank out the default header
\fancyfoot[L]{} % Custom footer text
\fancyfoot[C]{} % Custom footer text
\fancyfoot[R]{\thepage} % Custom footer text
\newcommand{\note}[1]{\marginpar{\scriptsize \textcolor{red}{#1}}} % Enables comments in red on margin
%----------------------------------------------------------------------------------------

Binary file not shown.

After

Width:  |  Height:  |  Size: 45 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 39 KiB

View File

@ -0,0 +1,165 @@
% avm.sty -- for attribute-value matrices -- mar 29, 1992; rev. dec 6, 1993
% (c) 1992 christopher manning (manning@csli.stanford.edu) -- see avm.doc.tex
\newif\ifavmactive\newif\ifavmsorted\newif\ifavmlabeled
\newif\ifavmcenter\newif\ifavmbottom
\newif\ifavmbottomright\newif\ifavmtopleft\newif\ifavmtopright
\newdimen\avmdimen
\newbox\avmboxone\newbox\avmboxthree
\def\avmoptions#1{\avmactivefalse\avmsortedfalse\avmlabeledfalse
\avmcenterfalse\avmbottomfalse
\avmbottomrightfalse\avmtopleftfalse\avmtoprightfalse
\def\more{#1}\ifx\more\empty\else\avmjoptions#1,\@nil\fi}
\def\avmjoptions#1,#2\@nil{\def\more{#2}\csname avm#1true\endcsname
\ifx\more\empty\else\avmjoptions#2\@nil\fi}
\def\avmfont#1{\def\avmjfont{#1}}
\def\avmjfont{}
\def\avmvalfont#1{\def\avmjvalfont{#1}}
\def\avmjvalfont{}
\def\avmsortfont#1{\def\avmjsortfont{#1}}
\def\avmjsortfont{}
\def\avmhskip#1{\def\avmjhskip{#1}}
\def\avmjhskip{1em}
\def\avmbskip#1{\def\avmjbskip{#1}}
\def\avmjbskip{0em}
\def\avmvskip#1{\def\avmjvskip{#1}}
\def\avmjvskip{0.385ex}%was .3875
\def\avmjprolog#1{$\mskip-\thinmuskip
\left#1\hskip\avmjbskip\vcenter\bgroup\vskip\avmjvskip
\ialign\bgroup\avmjfont
\strut ##\unskip\hfil
&&\hskip\avmjhskip\avmjvalfont ##\unskip\hfil\cr}
\def\avmjpostlog#1{\crcr\egroup\vskip\avmjvskip\egroup
\hskip\avmjbskip\right#1\mskip-\thinmuskip$\ignorespaces}
\def\avmjcatcode{\let\lparen=(\let\rparen=)\catcode`\[=13\catcode`\]=13
\catcode`\<=13\catcode`\@=13\catcode`\(=13\catcode`\)=13
\catcode`\>=13\catcode`\|=13}
{\avmjcatcode % new group: redefine above catcodes as active
\gdef\specialavm{\avmjcatcode
\def({\avmjprolog\lparen}%
\def){\avmjpostlog\rparen}%
\def<{\avmjprolog\langle}%
\def>{\avmjpostlog\rangle}%
\ifavmsorted
\def[##1{\setbox\avmboxthree=\hbox{\avmjsortfont##1\/}\setbox2=\hbox
\bgroup\avmjprolog\lbrack}%
\def]{\avmjpostlog\rbrack\egroup\avmjsort}%
\else\ifavmlabeled
\def[##1{\def\more{##1}\setbox2=\hbox\bgroup\avmjprolog[}%
\def]{\avmjpostlog]\egroup\node{\more}{\box2}}%
\else
\def[{\avmjprolog\lbrack}%
\def]{\avmjpostlog\rbrack}%
\fi\fi
%
\def\<{$\langle$}\def\>{$\rangle$}%
\def\({\lparen}\def\){\rparen}%
\def\[{\lbrack}\def\]{\rbrack}%
\def|{$\,\vert\,$}%
\def@##1{\avmbox{##1}}%
} % end defn of \specialavm
} % restore active catcodes
\long\def\avm{\begingroup
\ifavmactive\specialavm
\else
\def\({\avmjprolog(}%
\def\){\avmjpostlog)}%
\def\<{\avmjprolog\langle}%
\def\>{\avmjpostlog\rangle}%
%
\ifavmsorted
\def\[##1{\setbox\avmboxthree=\hbox{\avmjsortfont##1\/}\setbox
2=\hbox\bgroup\avmjprolog[}%
\def\]{\avmjpostlog]\egroup\avmjsort}%
\else\ifavmlabeled
\def\[##1{\def\more{##1}\setbox2=\hbox\bgroup\avmjprolog[}%
\def\]{\avmjpostlog]\egroup\node{\more}{\box2}}%
\else
\def\[{\avmjprolog[}%
\def\]{\avmjpostlog]}%
\fi\fi
%
\def\|{$\,\vert\,$}%
\def\@##1{\avmbox{##1}}%
\fi % end not active
%
\ifx\LaTeX\undefined\def\\{\cr}% running under TeX
\else \def\\{\@tabularcr}% Leverage off LaTeX's \\*[dimen] options
\fi
\def\!{\node}%
\long\def\avmjsort{\dimen2=\ht2\advance\dimen2 by -.25\baselineskip
\global\dimen\avmdimen=\wd\avmboxthree
\ifavmtopleft \raise\dimen2\llap{\box\avmboxthree}\box2%
\else\ifavmtopright \box2\raise\dimen2\box\avmboxthree%
\else\ifavmbottomright \box2\lower\dimen2\box\avmboxthree%
\else \lower\dimen2\llap{\box\avmboxthree}\box2%
\fi\fi\fi}%
\long\def\sort##1##2{\setbox2=\hbox{##2}\setbox
\avmboxthree=\hbox{\avmjsortfont##1\/}\dimen2=\ht2
\advance\dimen2 by -.25\baselineskip
\ifavmtopleft \raise\dimen2\box\avmboxthree\box2%
\else\ifavmtopright \box2\raise\dimen2\box\avmboxthree%
\else\ifavmbottomright \box2\lower\dimen2\box\avmboxthree%
\else \lower\dimen2\box\avmboxthree\box2%
\fi\fi\fi}%
\long\def\osort##1##2{\setbox2=\hbox{##2}\setbox
\avmboxthree=\hbox{\avmjsortfont ##1\/}\avmjsort}%
\def\avml{\avmjprolog.}%
\def\avmr{\avmjpostlog.}%
\def\avmb##1{\node{##1}{\lbrack\;\rbrack}}%
\def\avmd##1{\node{##1}{---}}%
\def\q##1{\ifx ##1\{$\lbrace$\else
\ifx ##1\}$\rbrace$\else
\ifx ##1<$\langle$\else
\ifx ##1>$\rangle$\fi \fi \fi \fi}%
\def\{{\avmjprolog\lbrace}%
\def\}{\avmjpostlog\rbrace}%
\def\;{\hskip\avmjhskip}%
\def\avmspan##1{\multispan2\strut ##1\expandafter\hfil}%
\avmjfont
\openup\avmjvskip
\setbox\avmboxone=\hbox\bgroup\ignorespaces
} % end defn of \avm
\def\endavm{\egroup\ifvmode\leavevmode\fi % this if is useful!
\ifavmsorted\null\hskip\dimen\avmdimen\fi
\ifavmcenter
\box\avmboxone
\else \ifavmbottom
\lower.575\baselineskip\hbox{\vbox{\box\avmboxone\null}}%
\else
% the next bit is ripped off from Emma's \evnup in lingmacros.sty
\dimen2=\ht\avmboxone\advance\dimen2 by -.725\baselineskip
\lower\dimen2\box\avmboxone
\fi \fi \endgroup}
% based on TeXbook exercise 21.3
\def\avmbox#1{\setbox2=\hbox{$\scriptstyle #1$}\lower.2ex\vbox{\hrule
\hbox{\vrule\kern1.25pt
\vbox{\kern1.25pt\box2\kern1.25pt}\kern1.25pt\vrule}\hrule}}
% ============ COSTOM CONFIGURATION =============
\avmfont{\sc}
\avmoptions{sorted,active}
\avmvalfont{\rm}
\avmsortfont{\scriptsize\it}
% ===============================================

View File

@ -0,0 +1,131 @@
%% Last Modified: Thu Oct 18 18:26:25 2007.
\NeedsTeXFormat{LaTeX2e}
\ProvidesPackage{style/btree}
\typeout{Document Style `weiw_BTree - Support drawing B+-Tree (ver 0.999)}
\RequirePackage{tikz}
\RequirePackage{ifthen}
% use libraries
\usetikzlibrary{arrows,shapes,decorations,matrix}
%% global declaration
\tikzstyle{btreeptr} = [draw, semithick, minimum height=2em]
\tikzstyle{btreeval} = [draw, semithick, minimum size=2em]
\tikzstyle{btreevale} = [draw,semithick, minimum size=2em]
\tikzstyle{btlink} = [draw, semithick, ->, >=triangle 45]
%% macro
%% helper macros
\newcommand{\suppressemptystr}[1]{% leave blank for entries in leaf nodes
\ifthenelse{\equal{#1}{}}%
{%
\relax%
}%
% Else
{%
#1\textsuperscript{*}%
}%
}%
\newcommand{\xyshift}[3]{% help to place the nodes
\begin{scope}[xshift=#1, yshift=#2]
#3
\end{scope}%
}
%% Common btree macros
\newcommand{\btreelink}[2]{% #1: src node; #2: dest node;
\draw[btlink] ([yshift=3pt] #1.south) -- (#2-b.north);
}
\newcommand{\btreelinknorth}[2]{% #1: src node; #2: dest node;
\draw[btlink] ([yshift=3pt] #1.south) -- (#2.north);
}
\newcommand{\btreetriangle}[2]{% #1: node name; #2 text inside
\node[anchor=north, regular polygon, regular polygon sides=3, draw] (#1) {#2};
}
%%======================================================================
%% btree with capacity = 4
\newcommand{\btreeinodefour}[5]{%
\matrix [ampersand replacement=\&] (#1)
{
\node[btreeptr] (#1-1) {\vphantom{1}}; \& \node[btreeval] (#1-a) {#2}; \&
\node[btreeptr] (#1-2) {\vphantom{1}}; \& \node[btreeval] (#1-b) {#3}; \&
\node[btreeptr] (#1-3) {\vphantom{1}}; \& \node[btreeval] (#1-c) {#4}; \&
\node[btreeptr] (#1-4) {\vphantom{1}}; \& \node[btreeval] (#1-d) {#5}; \&
\node[btreeptr] (#1-5) {\vphantom{1}}; \\
};
}
\newcommand{\btreelnodefour}[5]{%
\matrix [ampersand replacement=\&, outer sep=0pt, matrix anchor=north] (#1)
{
\node[btreevale] (#1-a) {\suppressemptystr{#2}}; \&
\node[btreevale] (#1-b) {\suppressemptystr{#3}}; \&
\node[btreevale] (#1-c) {\suppressemptystr{#4}}; \&
\node[btreevale] (#1-d) {\suppressemptystr{#5}}; \\
};
}
%%======================================================================
%% btree with capacity = 3
\newcommand{\btreeinodethree}[4]{%
\matrix [ampersand replacement=\&] (#1)
{
\node[btreeptr] (#1-1) {\vphantom{1}}; \& \node[btreeval] (#1-a) {#2}; \&
\node[btreeptr] (#1-2) {\vphantom{1}}; \& \node[btreeval] (#1-b) {#3}; \&
\node[btreeptr] (#1-3) {\vphantom{1}}; \& \node[btreeval] (#1-c) {#4}; \&
\node[btreeptr] (#1-4) {\vphantom{1}}; \\
};
}
\newcommand{\btreelnodethree}[4]{%
\matrix [ampersand replacement=\&, outer sep=0pt, matrix anchor=north] (#1)
{
\node[btreevale] (#1-a) {\suppressemptystr{#2}}; \&
\node[btreevale] (#1-b) {\suppressemptystr{#3}}; \&
\node[btreevale] (#1-c) {\suppressemptystr{#4}}; \\
};
}
%%======================================================================
%% btree with capacity = 2
\newcommand{\btreeinodetwo}[4]{%
\matrix [ampersand replacement=\&] (#1)
{
\node[btreeptr] (#1-1) {\vphantom{1}}; \& \node[btreeval] (#1-a) {#2}; \&
\node[btreeptr] (#1-2) {\vphantom{1}}; \& \node[btreeval] (#1-b) {#3}; \&
\node[btreeptr] (#1-3) {\vphantom{1}}; \\
};
}
\newcommand{\btreelnodetwo}[3]{%
\matrix [ampersand replacement=\&, outer sep=0pt, matrix anchor=north] (#1)
{
\node[btreevale] (#1-a) {\suppressemptystr{#2}}; \&
\node[btreevale] (#1-b) {\suppressemptystr{#3}}; \\
};
}
%%======================================================================
%% simple example
% \begin{center}
% \scalebox{0.7}{
% \begin{tikzpicture}
% %
% \btreeinodefour{root}{13}{17}{24}{30};
% \xyshift{-40mm}{-20mm}{\btreelnodefour{n1}{2}{3}{5}{7}}
% \xyshift{-0mm}{-20mm}{\btreelnodefour{n2}{14}{16}{}{}}
% \xyshift{40mm}{-20mm}{\btreelnodefour{n3}{19}{20}{22}{}}
% \xyshift{80mm}{-20mm}{\btreelnodefour{n4}{24}{27}{29}{}}
% \xyshift{120mm}{-20mm}{\btreelnodefour{n5}{33}{34}{38}{39}}
% %
% \foreach \x in {1,2,...,5} { \btreelink{root-\x}{n\x} }
% \end{tikzpicture}
% }
% \end{center}

Binary file not shown.

After

Width:  |  Height:  |  Size: 66 KiB

View File

@ -0,0 +1,38 @@
% Source: ss17_wissschreib (Eva)
\lstset{
basicstyle=\ttfamily\scriptsize\mdseries,
keywordstyle=\bfseries\color[rgb]{0.171875, 0.242188, 0.3125},
identifierstyle=,
commentstyle=\color[rgb]{0.257813, 0.15625, 0},
stringstyle=\itshape\color[rgb]{0.0195313, 0.195313, 0.0117188},
numbers=left,
numberstyle=\tiny,
stepnumber=1,
breaklines=true,
frame=none,
showstringspaces=false,
tabsize=4,
backgroundcolor=\color[rgb]{0.98,0.98,0.98},
captionpos=b,
float=htbp,
language=Python,
xleftmargin=15pt,
xrightmargin=15pt
}
%(deutsche) Sonderzeichen
\lstset{literate=%
{Ä}{{\"A}}1
{Ö}{{\"O}}1
{Ü}{{\"U}}1
{ä}{{\"a}}1
{ö}{{\"o}}1
{ü}{{\"u}}1
{ß}{{\ss}}1
}
%Verwendung im Text:
%-> \begin{lstlisting}[language=Python,firstnumber=27] ... \end{lstlisting}
%-> \begin{lstlisting}[language=Python,numbers=none] ... \end{lstlisting}
%-> \lstinline[language=JAVA]{...}

View File

@ -0,0 +1,49 @@
\relax
\providecommand\hyper@newdestlabel[2]{}
\providecommand\HyperFirstAtBeginDocument{\AtBeginDocument}
\HyperFirstAtBeginDocument{\ifx\hyper@anchor\@undefined
\global\let\oldnewlabel\newlabel
\gdef\newlabel#1#2{\newlabelxx{#1}#2}
\gdef\newlabelxx#1#2#3#4#5#6{\oldnewlabel{#1}{{#2}{#3}}}
\AtEndDocument{\ifx\hyper@anchor\@undefined
\let\newlabel\oldnewlabel
\fi}
\fi}
\global\let\hyper@last\relax
\gdef\HyperFirstAtBeginDocument#1{#1}
\providecommand\HyField@AuxAddToFields[1]{}
\providecommand\HyField@AuxAddToCoFields[2]{}
\@writefile{toc}{\contentsline {section}{\numberline {1}Abstract Data Types}{2}{section.1}\protected@file@percent }
\@writefile{toc}{\contentsline {subsection}{\numberline {1.1}Stacks \& Queues}{2}{subsection.1.1}\protected@file@percent }
\@writefile{toc}{\contentsline {subsubsection}{\numberline {1.1.1}Stacks}{2}{subsubsection.1.1.1}\protected@file@percent }
\@writefile{toc}{\contentsline {subsubsection}{\numberline {1.1.2}Queues}{2}{subsubsection.1.1.2}\protected@file@percent }
\@writefile{toc}{\contentsline {subsection}{\numberline {1.2}Linked Lists}{3}{subsection.1.2}\protected@file@percent }
\@writefile{toc}{\contentsline {subsubsection}{\numberline {1.2.1}Implementation of Linked Lists}{3}{subsubsection.1.2.1}\protected@file@percent }
\@writefile{toc}{\contentsline {subsubsection}{\numberline {1.2.2}Singly Linked List Class}{4}{subsubsection.1.2.2}\protected@file@percent }
\@writefile{toc}{\contentsline {section}{\numberline {2}Algorithm Analysis}{5}{section.2}\protected@file@percent }
\@writefile{toc}{\contentsline {subsection}{\numberline {2.1}Algorithm Analysis Basics}{5}{subsection.2.1}\protected@file@percent }
\@writefile{toc}{\contentsline {subsubsection}{\numberline {2.1.1}Counting Primitive Operations}{5}{subsubsection.2.1.1}\protected@file@percent }
\@writefile{toc}{\contentsline {subsection}{\numberline {2.2}O Notation}{5}{subsection.2.2}\protected@file@percent }
\@writefile{toc}{\contentsline {subsubsection}{\numberline {2.2.1}Important Functions Used in O Notation}{6}{subsubsection.2.2.1}\protected@file@percent }
\@writefile{toc}{\contentsline {subsubsection}{\numberline {2.2.2}Efficiency \& O Notation}{7}{subsubsection.2.2.2}\protected@file@percent }
\@writefile{toc}{\contentsline {subsection}{\numberline {2.3}Recursion Review}{7}{subsection.2.3}\protected@file@percent }
\@writefile{toc}{\contentsline {section}{\numberline {3}Dynamic Programming}{7}{section.3}\protected@file@percent }
\@writefile{toc}{\contentsline {subsection}{\numberline {3.1}More Big Greek Letters}{8}{subsection.3.1}\protected@file@percent }
\@writefile{toc}{\contentsline {subsection}{\numberline {3.2}P, NP, \& NP-Complete Problems}{9}{subsection.3.2}\protected@file@percent }
\@writefile{toc}{\contentsline {section}{\numberline {4}Searching \& Sorting}{10}{section.4}\protected@file@percent }
\@writefile{toc}{\contentsline {subsection}{\numberline {4.1}Keys \& Values}{10}{subsection.4.1}\protected@file@percent }
\@writefile{toc}{\contentsline {subsection}{\numberline {4.2}Java Interface: Comparator}{10}{subsection.4.2}\protected@file@percent }
\@writefile{toc}{\contentsline {subsection}{\numberline {4.3}Java Interface: Comparable}{10}{subsection.4.3}\protected@file@percent }
\@writefile{toc}{\contentsline {subsection}{\numberline {4.4}Insertion Sort}{10}{subsection.4.4}\protected@file@percent }
\@writefile{loa}{\contentsline {algorithm}{\numberline {1}{\ignorespaces Insertion Sort Pseudocode}}{11}{algorithm.1}\protected@file@percent }
\@writefile{toc}{\contentsline {subsection}{\numberline {4.5}Shell Sort}{12}{subsection.4.5}\protected@file@percent }
\@writefile{loa}{\contentsline {algorithm}{\numberline {2}{\ignorespaces Shell Sort Pseudocode}}{12}{algorithm.2}\protected@file@percent }
\@writefile{toc}{\contentsline {subsection}{\numberline {4.6}Quick Sort}{12}{subsection.4.6}\protected@file@percent }
\@writefile{toc}{\contentsline {section}{\numberline {5}Trees}{13}{section.5}\protected@file@percent }
\@writefile{toc}{\contentsline {subsection}{\numberline {5.1}Binary Trees}{13}{subsection.5.1}\protected@file@percent }
\@writefile{toc}{\contentsline {subsection}{\numberline {5.2}Generics in Java}{13}{subsection.5.2}\protected@file@percent }
\bibstyle{unsrtnat}
\bibdata{references}
\@writefile{toc}{\contentsline {section}{\numberline {6}Search Trees}{14}{section.6}\protected@file@percent }
\@writefile{toc}{\contentsline {subsection}{\numberline {6.1}Binary Search Trees}{14}{subsection.6.1}\protected@file@percent }
\gdef \@abspage@last{15}

View File

@ -0,0 +1,700 @@
This is pdfTeX, Version 3.141592653-2.6-1.40.25 (TeX Live 2023) (preloaded format=pdflatex 2023.4.9) 20 APR 2023 20:24
entering extended mode
restricted \write18 enabled.
%&-line parsing enabled.
**CT2109-Notes
(./CT2109-Notes.tex
LaTeX2e <2022-11-01> patch level 1
L3 programming layer <2023-03-30>
(/opt/texlive/2023/texmf-dist/tex/latex/base/article.cls
Document Class: article 2022/07/02 v1.4n Standard LaTeX document class
(/opt/texlive/2023/texmf-dist/tex/latex/base/size11.clo
File: size11.clo 2022/07/02 v1.4n Standard LaTeX file (size option)
)
\c@part=\count185
\c@section=\count186
\c@subsection=\count187
\c@subsubsection=\count188
\c@paragraph=\count189
\c@subparagraph=\count190
\c@figure=\count191
\c@table=\count192
\abovecaptionskip=\skip48
\belowcaptionskip=\skip49
\bibindent=\dimen140
) (./report.sty
(/opt/texlive/2023/texmf-dist/tex/latex/geometry/geometry.sty
Package: geometry 2020/01/02 v5.9 Page Geometry
(/opt/texlive/2023/texmf-dist/tex/latex/graphics/keyval.sty
Package: keyval 2022/05/29 v1.15 key=value parser (DPC)
\KV@toks@=\toks16
)
(/opt/texlive/2023/texmf-dist/tex/generic/iftex/ifvtex.sty
Package: ifvtex 2019/10/25 v1.7 ifvtex legacy package. Use iftex instead.
(/opt/texlive/2023/texmf-dist/tex/generic/iftex/iftex.sty
Package: iftex 2022/02/03 v1.0f TeX engine tests
))
\Gm@cnth=\count193
\Gm@cntv=\count194
\c@Gm@tempcnt=\count195
\Gm@bindingoffset=\dimen141
\Gm@wd@mp=\dimen142
\Gm@odd@mp=\dimen143
\Gm@even@mp=\dimen144
\Gm@layoutwidth=\dimen145
\Gm@layoutheight=\dimen146
\Gm@layouthoffset=\dimen147
\Gm@layoutvoffset=\dimen148
\Gm@dimlist=\toks17
)
(/opt/texlive/2023/texmf-dist/tex/latex/fancyhdr/fancyhdr.sty
Package: fancyhdr 2022/11/09 v4.1 Extensive control of page headers and footers
\f@nch@headwidth=\skip50
\f@nch@O@elh=\skip51
\f@nch@O@erh=\skip52
\f@nch@O@olh=\skip53
\f@nch@O@orh=\skip54
\f@nch@O@elf=\skip55
\f@nch@O@erf=\skip56
\f@nch@O@olf=\skip57
\f@nch@O@orf=\skip58
)
\@abovecaptionskip=\skip59
\@belowcaptionskip=\skip60
)
(/opt/texlive/2023/texmf-dist/tex/latex/algorithmicx/algpseudocode.sty
Package: algpseudocode
(/opt/texlive/2023/texmf-dist/tex/latex/base/ifthen.sty
Package: ifthen 2022/04/13 v1.1d Standard LaTeX ifthen package (DPC)
)
(/opt/texlive/2023/texmf-dist/tex/latex/algorithmicx/algorithmicx.sty
Package: algorithmicx 2005/04/27 v1.2 Algorithmicx
Document Style algorithmicx 1.2 - a greatly improved `algorithmic' style
\c@ALG@line=\count196
\c@ALG@rem=\count197
\c@ALG@nested=\count198
\ALG@tlm=\skip61
\ALG@thistlm=\skip62
\c@ALG@Lnr=\count199
\c@ALG@blocknr=\count266
\c@ALG@storecount=\count267
\c@ALG@tmpcounter=\count268
\ALG@tmplength=\skip63
)
Document Style - pseudocode environments for use with the `algorithmicx' style
) (/opt/texlive/2023/texmf-dist/tex/latex/algorithms/algorithm.sty
Package: algorithm 2009/08/24 v0.1 Document Style `algorithm' - floating enviro
nment
(/opt/texlive/2023/texmf-dist/tex/latex/float/float.sty
Package: float 2001/11/08 v1.3d Float enhancements (AL)
\c@float@type=\count269
\float@exts=\toks18
\float@box=\box51
\@float@everytoks=\toks19
\@floatcapt=\box52
)
\@float@every@algorithm=\toks20
\c@algorithm=\count270
)
(/opt/texlive/2023/texmf-dist/tex/latex/base/inputenc.sty
Package: inputenc 2021/02/14 v1.3d Input encoding file
\inpenc@prehook=\toks21
\inpenc@posthook=\toks22
)
(/opt/texlive/2023/texmf-dist/tex/latex/base/fontenc.sty
Package: fontenc 2021/04/29 v2.0v Standard LaTeX package
LaTeX Font Info: Trying to load font information for T1+ptm on input line 11
2.
(/opt/texlive/2023/texmf-dist/tex/latex/psnfss/t1ptm.fd
File: t1ptm.fd 2001/06/04 font definitions for T1/ptm.
))
(/opt/texlive/2023/texmf-dist/tex/latex/hyperref/hyperref.sty
Package: hyperref 2023-02-07 v7.00v Hypertext links for LaTeX
(/opt/texlive/2023/texmf-dist/tex/generic/ltxcmds/ltxcmds.sty
Package: ltxcmds 2020-05-10 v1.25 LaTeX kernel commands for general use (HO)
)
(/opt/texlive/2023/texmf-dist/tex/generic/pdftexcmds/pdftexcmds.sty
Package: pdftexcmds 2020-06-27 v0.33 Utility functions of pdfTeX for LuaTeX (HO
)
(/opt/texlive/2023/texmf-dist/tex/generic/infwarerr/infwarerr.sty
Package: infwarerr 2019/12/03 v1.5 Providing info/warning/error messages (HO)
)
Package pdftexcmds Info: \pdf@primitive is available.
Package pdftexcmds Info: \pdf@ifprimitive is available.
Package pdftexcmds Info: \pdfdraftmode found.
)
(/opt/texlive/2023/texmf-dist/tex/latex/kvsetkeys/kvsetkeys.sty
Package: kvsetkeys 2022-10-05 v1.19 Key value parser (HO)
)
(/opt/texlive/2023/texmf-dist/tex/generic/kvdefinekeys/kvdefinekeys.sty
Package: kvdefinekeys 2019-12-19 v1.6 Define keys (HO)
)
(/opt/texlive/2023/texmf-dist/tex/generic/pdfescape/pdfescape.sty
Package: pdfescape 2019/12/09 v1.15 Implements pdfTeX's escape features (HO)
)
(/opt/texlive/2023/texmf-dist/tex/latex/hycolor/hycolor.sty
Package: hycolor 2020-01-27 v1.10 Color options for hyperref/bookmark (HO)
)
(/opt/texlive/2023/texmf-dist/tex/latex/letltxmacro/letltxmacro.sty
Package: letltxmacro 2019/12/03 v1.6 Let assignment for LaTeX macros (HO)
)
(/opt/texlive/2023/texmf-dist/tex/latex/auxhook/auxhook.sty
Package: auxhook 2019-12-17 v1.6 Hooks for auxiliary files (HO)
)
(/opt/texlive/2023/texmf-dist/tex/latex/hyperref/nameref.sty
Package: nameref 2022-05-17 v2.50 Cross-referencing by name of section
(/opt/texlive/2023/texmf-dist/tex/latex/refcount/refcount.sty
Package: refcount 2019/12/15 v3.6 Data extraction from label references (HO)
)
(/opt/texlive/2023/texmf-dist/tex/generic/gettitlestring/gettitlestring.sty
Package: gettitlestring 2019/12/15 v1.6 Cleanup title references (HO)
(/opt/texlive/2023/texmf-dist/tex/latex/kvoptions/kvoptions.sty
Package: kvoptions 2022-06-15 v3.15 Key value format for package options (HO)
))
\c@section@level=\count271
)
\@linkdim=\dimen149
\Hy@linkcounter=\count272
\Hy@pagecounter=\count273
(/opt/texlive/2023/texmf-dist/tex/latex/hyperref/pd1enc.def
File: pd1enc.def 2023-02-07 v7.00v Hyperref: PDFDocEncoding definition (HO)
Now handling font encoding PD1 ...
... no UTF-8 mapping file for font encoding PD1
)
(/opt/texlive/2023/texmf-dist/tex/generic/intcalc/intcalc.sty
Package: intcalc 2019/12/15 v1.3 Expandable calculations with integers (HO)
)
(/opt/texlive/2023/texmf-dist/tex/generic/etexcmds/etexcmds.sty
Package: etexcmds 2019/12/15 v1.7 Avoid name clashes with e-TeX commands (HO)
)
\Hy@SavedSpaceFactor=\count274
(/opt/texlive/2023/texmf-dist/tex/latex/hyperref/puenc.def
File: puenc.def 2023-02-07 v7.00v Hyperref: PDF Unicode definition (HO)
Now handling font encoding PU ...
... no UTF-8 mapping file for font encoding PU
)
Package hyperref Info: Option `colorlinks' set `true' on input line 4060.
Package hyperref Info: Hyper figures OFF on input line 4177.
Package hyperref Info: Link nesting OFF on input line 4182.
Package hyperref Info: Hyper index ON on input line 4185.
Package hyperref Info: Plain pages OFF on input line 4192.
Package hyperref Info: Backreferencing OFF on input line 4197.
Package hyperref Info: Implicit mode ON; LaTeX internals redefined.
Package hyperref Info: Bookmarks ON on input line 4425.
\c@Hy@tempcnt=\count275
(/opt/texlive/2023/texmf-dist/tex/latex/url/url.sty
\Urlmuskip=\muskip16
Package: url 2013/09/16 ver 3.4 Verb mode for urls, etc.
)
LaTeX Info: Redefining \url on input line 4763.
\XeTeXLinkMargin=\dimen150
(/opt/texlive/2023/texmf-dist/tex/generic/bitset/bitset.sty
Package: bitset 2019/12/09 v1.3 Handle bit-vector datatype (HO)
(/opt/texlive/2023/texmf-dist/tex/generic/bigintcalc/bigintcalc.sty
Package: bigintcalc 2019/12/15 v1.5 Expandable calculations on big integers (HO
)
))
\Fld@menulength=\count276
\Field@Width=\dimen151
\Fld@charsize=\dimen152
Package hyperref Info: Hyper figures OFF on input line 6042.
Package hyperref Info: Link nesting OFF on input line 6047.
Package hyperref Info: Hyper index ON on input line 6050.
Package hyperref Info: backreferencing OFF on input line 6057.
Package hyperref Info: Link coloring ON on input line 6060.
Package hyperref Info: Link coloring with OCG OFF on input line 6067.
Package hyperref Info: PDF/A mode OFF on input line 6072.
(/opt/texlive/2023/texmf-dist/tex/latex/base/atbegshi-ltx.sty
Package: atbegshi-ltx 2021/01/10 v1.0c Emulation of the original atbegshi
package with kernel methods
)
\Hy@abspage=\count277
\c@Item=\count278
\c@Hfootnote=\count279
)
Package hyperref Info: Driver (autodetected): hpdftex.
(/opt/texlive/2023/texmf-dist/tex/latex/hyperref/hpdftex.def
File: hpdftex.def 2023-02-07 v7.00v Hyperref driver for pdfTeX
(/opt/texlive/2023/texmf-dist/tex/latex/base/atveryend-ltx.sty
Package: atveryend-ltx 2020/08/19 v1.0a Emulation of the original atveryend pac
kage
with kernel methods
)
\Fld@listcount=\count280
\c@bookmark@seq@number=\count281
(/opt/texlive/2023/texmf-dist/tex/latex/rerunfilecheck/rerunfilecheck.sty
Package: rerunfilecheck 2022-07-10 v1.10 Rerun checks for auxiliary files (HO)
(/opt/texlive/2023/texmf-dist/tex/generic/uniquecounter/uniquecounter.sty
Package: uniquecounter 2019/12/15 v1.4 Provide unlimited unique counter (HO)
)
Package uniquecounter Info: New unique counter `rerunfilecheck' on input line 2
85.
)
\Hy@SectionHShift=\skip64
)
(/opt/texlive/2023/texmf-dist/tex/latex/booktabs/booktabs.sty
Package: booktabs 2020/01/12 v1.61803398 Publication quality tables
\heavyrulewidth=\dimen153
\lightrulewidth=\dimen154
\cmidrulewidth=\dimen155
\belowrulesep=\dimen156
\belowbottomsep=\dimen157
\aboverulesep=\dimen158
\abovetopsep=\dimen159
\cmidrulesep=\dimen160
\cmidrulekern=\dimen161
\defaultaddspace=\dimen162
\@cmidla=\count282
\@cmidlb=\count283
\@aboverulesep=\dimen163
\@belowrulesep=\dimen164
\@thisruleclass=\count284
\@lastruleclass=\count285
\@thisrulewidth=\dimen165
)
(/opt/texlive/2023/texmf-dist/tex/latex/amsfonts/amsfonts.sty
Package: amsfonts 2013/01/14 v3.01 Basic AMSFonts support
\@emptytoks=\toks23
\symAMSa=\mathgroup4
\symAMSb=\mathgroup5
LaTeX Font Info: Redeclaring math symbol \hbar on input line 98.
LaTeX Font Info: Overwriting math alphabet `\mathfrak' in version `bold'
(Font) U/euf/m/n --> U/euf/b/n on input line 106.
)
(/opt/texlive/2023/texmf-dist/tex/latex/units/nicefrac.sty
Package: nicefrac 1998/08/04 v0.9b Nice fractions
\L@UnitsRaiseDisplaystyle=\skip65
\L@UnitsRaiseTextstyle=\skip66
\L@UnitsRaiseScriptstyle=\skip67
)
(/opt/texlive/2023/texmf-dist/tex/latex/microtype/microtype.sty
Package: microtype 2023/03/13 v3.1a Micro-typographical refinements (RS)
(/opt/texlive/2023/texmf-dist/tex/latex/etoolbox/etoolbox.sty
Package: etoolbox 2020/10/05 v2.5k e-TeX tools for LaTeX (JAW)
\etb@tempcnta=\count286
)
\MT@toks=\toks24
\MT@tempbox=\box53
\MT@count=\count287
LaTeX Info: Redefining \noprotrusionifhmode on input line 1059.
LaTeX Info: Redefining \leftprotrusion on input line 1060.
\MT@prot@toks=\toks25
LaTeX Info: Redefining \rightprotrusion on input line 1078.
LaTeX Info: Redefining \textls on input line 1368.
\MT@outer@kern=\dimen166
LaTeX Info: Redefining \textmicrotypecontext on input line 1988.
\MT@listname@count=\count288
(/opt/texlive/2023/texmf-dist/tex/latex/microtype/microtype-pdftex.def
File: microtype-pdftex.def 2023/03/13 v3.1a Definitions specific to pdftex (RS)
LaTeX Info: Redefining \lsstyle on input line 902.
LaTeX Info: Redefining \lslig on input line 902.
\MT@outer@space=\skip68
)
Package microtype Info: Loading configuration file microtype.cfg.
(/opt/texlive/2023/texmf-dist/tex/latex/microtype/microtype.cfg
File: microtype.cfg 2023/03/13 v3.1a microtype main configuration file (RS)
))
(/opt/texlive/2023/texmf-dist/tex/latex/lipsum/lipsum.sty
(/opt/texlive/2023/texmf-dist/tex/latex/l3packages/l3keys2e/l3keys2e.sty
(/opt/texlive/2023/texmf-dist/tex/latex/l3kernel/expl3.sty
Package: expl3 2023-03-30 L3 programming layer (loader)
(/opt/texlive/2023/texmf-dist/tex/latex/l3backend/l3backend-pdftex.def
File: l3backend-pdftex.def 2023-03-30 L3 backend support: PDF output (pdfTeX)
\l__color_backend_stack_int=\count289
\l__pdf_internal_box=\box54
))
Package: l3keys2e 2023-02-02 LaTeX2e option processing using LaTeX3 keys
)
Package: lipsum 2021-09-20 v2.7 150 paragraphs of Lorem Ipsum dummy text
\g__lipsum_par_int=\count290
\l__lipsum_a_int=\count291
\l__lipsum_b_int=\count292
(/opt/texlive/2023/texmf-dist/tex/latex/lipsum/lipsum.ltd.tex))
(/opt/texlive/2023/texmf-dist/tex/latex/graphics/graphicx.sty
Package: graphicx 2021/09/16 v1.2d Enhanced LaTeX Graphics (DPC,SPQR)
(/opt/texlive/2023/texmf-dist/tex/latex/graphics/graphics.sty
Package: graphics 2022/03/10 v1.4e Standard LaTeX Graphics (DPC,SPQR)
(/opt/texlive/2023/texmf-dist/tex/latex/graphics/trig.sty
Package: trig 2021/08/11 v1.11 sin cos tan (DPC)
)
(/opt/texlive/2023/texmf-dist/tex/latex/graphics-cfg/graphics.cfg
File: graphics.cfg 2016/06/04 v1.11 sample graphics configuration
)
Package graphics Info: Driver file: pdftex.def on input line 107.
(/opt/texlive/2023/texmf-dist/tex/latex/graphics-def/pdftex.def
File: pdftex.def 2022/09/22 v1.2b Graphics/color driver for pdftex
))
\Gin@req@height=\dimen167
\Gin@req@width=\dimen168
)
(/opt/texlive/2023/texmf-dist/tex/latex/natbib/natbib.sty
Package: natbib 2010/09/13 8.31b (PWD, AO)
\bibhang=\skip69
\bibsep=\skip70
LaTeX Info: Redefining \cite on input line 694.
\c@NAT@ctr=\count293
)
(/opt/texlive/2023/texmf-dist/tex/latex/doi/doi.sty
Package: doi 2018/09/09 handle doi numbers
)
(/opt/texlive/2023/texmf-dist/tex/latex/tools/array.sty
Package: array 2022/09/04 v2.5g Tabular extension package (FMi)
\col@sep=\dimen169
\ar@mcellbox=\box55
\extrarowheight=\dimen170
\NC@list=\toks26
\extratabsurround=\skip71
\backup@length=\skip72
\ar@cellbox=\box56
)
(/opt/texlive/2023/texmf-dist/tex/latex/listings/listings.sty
\lst@mode=\count294
\lst@gtempboxa=\box57
\lst@token=\toks27
\lst@length=\count295
\lst@currlwidth=\dimen171
\lst@column=\count296
\lst@pos=\count297
\lst@lostspace=\dimen172
\lst@width=\dimen173
\lst@newlines=\count298
\lst@lineno=\count299
\lst@maxwidth=\dimen174
(/opt/texlive/2023/texmf-dist/tex/latex/listings/lstmisc.sty
File: lstmisc.sty 2023/02/27 1.9 (Carsten Heinz)
\c@lstnumber=\count300
\lst@skipnumbers=\count301
\lst@framebox=\box58
)
(/opt/texlive/2023/texmf-dist/tex/latex/listings/listings.cfg
File: listings.cfg 2023/02/27 1.9 listings configuration
))
Package: listings 2023/02/27 1.9 (Carsten Heinz)
(/opt/texlive/2023/texmf-dist/tex/latex/xcolor/xcolor.sty
Package: xcolor 2022/06/12 v2.14 LaTeX color extensions (UK)
(/opt/texlive/2023/texmf-dist/tex/latex/graphics-cfg/color.cfg
File: color.cfg 2016/01/02 v1.6 sample color configuration
)
Package xcolor Info: Driver file: pdftex.def on input line 227.
(/opt/texlive/2023/texmf-dist/tex/latex/graphics/mathcolor.ltx)
Package xcolor Info: Model `cmy' substituted by `cmy0' on input line 1353.
Package xcolor Info: Model `hsb' substituted by `rgb' on input line 1357.
Package xcolor Info: Model `RGB' extended on input line 1369.
Package xcolor Info: Model `HTML' substituted by `rgb' on input line 1371.
Package xcolor Info: Model `Hsb' substituted by `hsb' on input line 1372.
Package xcolor Info: Model `tHsb' substituted by `hsb' on input line 1373.
Package xcolor Info: Model `HSB' substituted by `hsb' on input line 1374.
Package xcolor Info: Model `Gray' substituted by `gray' on input line 1375.
Package xcolor Info: Model `wave' substituted by `hsb' on input line 1376.
)
(./CT2109-Notes.aux)
\openout1 = `CT2109-Notes.aux'.
LaTeX Font Info: Checking defaults for OML/cmm/m/it on input line 84.
LaTeX Font Info: ... okay on input line 84.
LaTeX Font Info: Checking defaults for OMS/cmsy/m/n on input line 84.
LaTeX Font Info: ... okay on input line 84.
LaTeX Font Info: Checking defaults for OT1/cmr/m/n on input line 84.
LaTeX Font Info: ... okay on input line 84.
LaTeX Font Info: Checking defaults for T1/cmr/m/n on input line 84.
LaTeX Font Info: ... okay on input line 84.
LaTeX Font Info: Checking defaults for TS1/cmr/m/n on input line 84.
LaTeX Font Info: ... okay on input line 84.
LaTeX Font Info: Checking defaults for OMX/cmex/m/n on input line 84.
LaTeX Font Info: ... okay on input line 84.
LaTeX Font Info: Checking defaults for U/cmr/m/n on input line 84.
LaTeX Font Info: ... okay on input line 84.
LaTeX Font Info: Checking defaults for PD1/pdf/m/n on input line 84.
LaTeX Font Info: ... okay on input line 84.
LaTeX Font Info: Checking defaults for PU/pdf/m/n on input line 84.
LaTeX Font Info: ... okay on input line 84.
*geometry* driver: auto-detecting
*geometry* detected driver: pdftex
*geometry* verbose mode - [ preamble ] result:
* driver: pdftex
* paper: letterpaper
* layout: <same size as paper>
* layoutoffset:(h,v)=(0.0pt,0.0pt)
* modes:
* h-part:(L,W,R)=(92.14519pt, 430.00462pt, 92.14519pt)
* v-part:(T,H,B)=(95.39737pt, 556.47656pt, 143.09605pt)
* \paperwidth=614.295pt
* \paperheight=794.96999pt
* \textwidth=430.00462pt
* \textheight=556.47656pt
* \oddsidemargin=19.8752pt
* \evensidemargin=19.8752pt
* \topmargin=-13.87262pt
* \headheight=12.0pt
* \headsep=25.0pt
* \topskip=11.0pt
* \footskip=30.0pt
* \marginparwidth=59.0pt
* \marginparsep=10.0pt
* \columnsep=10.0pt
* \skip\footins=9.0pt plus 4.0pt minus 2.0pt
* \hoffset=0.0pt
* \voffset=0.0pt
* \mag=1000
* \@twocolumnfalse
* \@twosidefalse
* \@mparswitchfalse
* \@reversemarginfalse
* (1in=72.27pt=25.4mm, 1cm=28.453pt)
*geometry* verbose mode - [ newgeometry ] result:
* driver: pdftex
* paper: letterpaper
* layout: <same size as paper>
* layoutoffset:(h,v)=(0.0pt,0.0pt)
* modes:
* h-part:(L,W,R)=(72.27pt, 469.75499pt, 72.27pt)
* v-part:(T,H,B)=(72.26999pt, 650.43pt, 72.27pt)
* \paperwidth=614.295pt
* \paperheight=794.96999pt
* \textwidth=469.75499pt
* \textheight=650.43pt
* \oddsidemargin=0.00002pt
* \evensidemargin=0.00002pt
* \topmargin=-39.0pt
* \headheight=14.0pt
* \headsep=25.0pt
* \topskip=11.0pt
* \footskip=30.0pt
* \marginparwidth=59.0pt
* \marginparsep=10.0pt
* \columnsep=10.0pt
* \skip\footins=9.0pt plus 4.0pt minus 2.0pt
* \hoffset=0.0pt
* \voffset=0.0pt
* \mag=1000
* \@twocolumnfalse
* \@twosidefalse
* \@mparswitchfalse
* \@reversemarginfalse
* (1in=72.27pt=25.4mm, 1cm=28.453pt)
Package hyperref Info: Link coloring ON on input line 84.
(./CT2109-Notes.out) (./CT2109-Notes.out)
\@outlinefile=\write3
\openout3 = `CT2109-Notes.out'.
LaTeX Info: Redefining \microtypecontext on input line 84.
Package microtype Info: Applying patch `item' on input line 84.
Package microtype Info: Applying patch `toc' on input line 84.
Package microtype Info: Applying patch `eqnum' on input line 84.
Package microtype Info: Applying patch `footnote' on input line 84.
Package microtype Info: Applying patch `verbatim' on input line 84.
Package microtype Info: Generating PDF output.
Package microtype Info: Character protrusion enabled (level 2).
Package microtype Info: Using default protrusion set `alltext'.
Package microtype Info: Automatic font expansion enabled (level 2),
(microtype) stretch: 20, shrink: 20, step: 1, non-selected.
Package microtype Info: Using default expansion set `alltext-nott'.
LaTeX Info: Redefining \showhyphens on input line 84.
Package microtype Info: No adjustment of tracking.
Package microtype Info: No adjustment of interword spacing.
Package microtype Info: No adjustment of character kerning.
(/opt/texlive/2023/texmf-dist/tex/latex/microtype/mt-ptm.cfg
File: mt-ptm.cfg 2006/04/20 v1.7 microtype config. file: Times (RS)
)
(/opt/texlive/2023/texmf-dist/tex/context/base/mkii/supp-pdf.mkii
[Loading MPS to PDF converter (version 2006.09.02).]
\scratchcounter=\count302
\scratchdimen=\dimen175
\scratchbox=\box59
\nofMPsegments=\count303
\nofMParguments=\count304
\everyMPshowfont=\toks28
\MPscratchCnt=\count305
\MPscratchDim=\dimen176
\MPnumerator=\count306
\makeMPintoPDFobject=\count307
\everyMPtoPDFconversion=\toks29
) (/opt/texlive/2023/texmf-dist/tex/latex/epstopdf-pkg/epstopdf-base.sty
Package: epstopdf-base 2020-01-24 v2.11 Base part for package epstopdf
Package epstopdf-base Info: Redefining graphics rule for `.eps' on input line 4
85.
(/opt/texlive/2023/texmf-dist/tex/latex/latexconfig/epstopdf-sys.cfg
File: epstopdf-sys.cfg 2010/07/13 v1.3 Configuration of (r)epstopdf for TeX Liv
e
))
\c@lstlisting=\count308
(/opt/texlive/2023/texmf-dist/tex/latex/microtype/mt-cmr.cfg
File: mt-cmr.cfg 2013/05/19 v2.2 microtype config. file: Computer Modern Roman
(RS)
)
LaTeX Font Info: Trying to load font information for U+msa on input line 86.
(/opt/texlive/2023/texmf-dist/tex/latex/amsfonts/umsa.fd
File: umsa.fd 2013/01/14 v3.01 AMS symbols A
)
(/opt/texlive/2023/texmf-dist/tex/latex/microtype/mt-msa.cfg
File: mt-msa.cfg 2006/02/04 v1.1 microtype config. file: AMS symbols (a) (RS)
)
LaTeX Font Info: Trying to load font information for U+msb on input line 86.
(/opt/texlive/2023/texmf-dist/tex/latex/amsfonts/umsb.fd
File: umsb.fd 2013/01/14 v3.01 AMS symbols B
)
(/opt/texlive/2023/texmf-dist/tex/latex/microtype/mt-msb.cfg
File: mt-msb.cfg 2005/06/01 v1.0 microtype config. file: AMS symbols (b) (RS)
) [1
{/opt/texlive/2023/texmf-var/fonts/map/pdftex/updmap/pdftex.map}{/opt/texlive/2
023/texmf-dist/fonts/enc/dvips/base/8r.enc}] (./CT2109-Notes.toc)
\tf@toc=\write4
\openout4 = `CT2109-Notes.toc'.
pdfTeX warning (ext4): destination with the same identifier (name{page.1}) has
been already used, duplicate ignored
<to be read again>
\relax
l.92 \newpage
[1]
<./images//adt.png, id=150, 241.90375pt x 217.81375pt>
File: ./images//adt.png Graphic file (type png)
<use ./images//adt.png>
Package pdftex.def Info: ./images//adt.png used on input line 101.
(pdftex.def) Requested size: 140.92792pt x 126.89705pt.
LaTeX Font Info: Trying to load font information for T1+cmtt on input line 1
18.
(/opt/texlive/2023/texmf-dist/tex/latex/base/t1cmtt.fd
File: t1cmtt.fd 2022/07/10 v2.5l Standard LaTeX font definitions
)
Package microtype Info: Loading generic protrusion settings for font family
(microtype) `cmtt' (encoding: T1).
(microtype) For optimal results, create family-specific settings.
(microtype) See the microtype manual for details.
LaTeX Font Info: Trying to load font information for TS1+ptm on input line 1
20.
(/opt/texlive/2023/texmf-dist/tex/latex/psnfss/ts1ptm.fd
File: ts1ptm.fd 2001/06/04 font definitions for TS1/ptm.
)
(/opt/texlive/2023/texmf-dist/tex/latex/listings/lstlang1.sty
File: lstlang1.sty 2023/02/27 1.9 listings language file
) [2{/opt/texlive/2023/texmf-dist/fonts/enc/dvips/cm-super/cm-super-t1.enc} <./
images//adt.png>]
<./images//ll.png, id=169, 351.3125pt x 64.24pt>
File: ./images//ll.png Graphic file (type png)
<use ./images//ll.png>
Package pdftex.def Info: ./images//ll.png used on input line 171.
(pdftex.def) Requested size: 281.85585pt x 51.54301pt.
<./images//node.png, id=170, 247.92625pt x 97.36375pt>
File: ./images//node.png Graphic file (type png)
<use ./images//node.png>
Package pdftex.def Info: ./images//node.png used on input line 192.
(pdftex.def) Requested size: 140.92792pt x 55.34488pt.
[3 <./images//ll.png> <./images//node.png>] [4] [5]
<./images//comparisonoffunctions1.png, id=244, 1014.79124pt x 577.15625pt>
File: ./images//comparisonoffunctions1.png Graphic file (type png)
<use ./images//comparisonoffunctions1.png>
Package pdftex.def Info: ./images//comparisonoffunctions1.png used on input li
ne 359.
(pdftex.def) Requested size: 375.80542pt x 213.7382pt.
<./images//comparisonoffunctions2.png, id=245, 970.62625pt x 686.565pt>
File: ./images//comparisonoffunctions2.png Graphic file (type png)
<use ./images//comparisonoffunctions2.png>
Package pdftex.def Info: ./images//comparisonoffunctions2.png used on input li
ne 363.
(pdftex.def) Requested size: 375.80542pt x 265.82118pt.
[6 <./images//comparisonoffunctions1.png>] [7 <./images//comparisonoffunctions
2.png>] [8]
<./images//pvsnp.png, id=268, 872.25874pt x 601.24625pt>
File: ./images//pvsnp.png Graphic file (type png)
<use ./images//pvsnp.png>
Package pdftex.def Info: ./images//pvsnp.png used on input line 524.
(pdftex.def) Requested size: 281.85585pt x 194.28345pt.
Underfull \vbox (badness 10000) has occurred while \output is active []
[9]
Package hyperref Info: bookmark level for unknown algorithm defaults to 0 on in
put line 563.
[10 <./images//pvsnp.png>] [11] [12]
<./images//binarytrees.png, id=302, 867.24pt x 393.47pt>
File: ./images//binarytrees.png Graphic file (type png)
<use ./images//binarytrees.png>
Package pdftex.def Info: ./images//binarytrees.png used on input line 690.
(pdftex.def) Requested size: 328.82706pt x 149.18993pt.
[13 <./images//binarytrees.png>]
No file CT2109-Notes.bbl.
[14] (./CT2109-Notes.aux)
Package rerunfilecheck Warning: File `CT2109-Notes.out' has changed.
(rerunfilecheck) Rerun to get outlines right
(rerunfilecheck) or use package `bookmark'.
Package rerunfilecheck Info: Checksums for `CT2109-Notes.out':
(rerunfilecheck) Before: C4445CAE8D3A7CA058755A04227E682D;4176
(rerunfilecheck) After: 213F3292C9B0F0D216A3C578F3C2DCCE;4442.
)
Here is how much of TeX's memory you used:
15981 strings out of 476017
251125 string characters out of 5792769
2074666 words of memory out of 5000000
35747 multiletter control sequences out of 15000+600000
577296 words of font info for 260 fonts, out of 8000000 for 9000
1141 hyphenation exceptions out of 8191
75i,13n,77p,1005b,1985s stack positions out of 10000i,1000n,20000p,200000b,200000s
</opt/texlive/2023/texmf-dist/fonts/type1/public/amsfonts/cm/cmmi10.pfb></opt
/texlive/2023/texmf-dist/fonts/type1/public/amsfonts/cm/cmmi8.pfb></opt/texlive
/2023/texmf-dist/fonts/type1/public/amsfonts/cm/cmr10.pfb></opt/texlive/2023/te
xmf-dist/fonts/type1/public/amsfonts/cm/cmr8.pfb></opt/texlive/2023/texmf-dist/
fonts/type1/public/amsfonts/cm/cmsy10.pfb></opt/texlive/2023/texmf-dist/fonts/t
ype1/public/cm-super/sftt0900.pfb></opt/texlive/2023/texmf-dist/fonts/type1/pub
lic/cm-super/sftt1095.pfb></opt/texlive/2023/texmf-dist/fonts/type1/urw/times/u
tmb8a.pfb></opt/texlive/2023/texmf-dist/fonts/type1/urw/times/utmr8a.pfb></opt/
texlive/2023/texmf-dist/fonts/type1/urw/times/utmri8a.pfb>
Output written on CT2109-Notes.pdf (15 pages, 1083233 bytes).
PDF statistics:
413 PDF objects out of 1000 (max. 8388607)
358 compressed objects within 4 object streams
148 named destinations out of 1000 (max. 500000)
60156 words of extra memory for PDF output out of 61914 (max. 10000000)

View File

@ -0,0 +1,29 @@
\BOOKMARK [1][-]{section.1}{\376\377\000A\000b\000s\000t\000r\000a\000c\000t\000\040\000D\000a\000t\000a\000\040\000T\000y\000p\000e\000s}{}% 1
\BOOKMARK [2][-]{subsection.1.1}{\376\377\000S\000t\000a\000c\000k\000s\000\040\000\046\000\040\000Q\000u\000e\000u\000e\000s}{section.1}% 2
\BOOKMARK [3][-]{subsubsection.1.1.1}{\376\377\000S\000t\000a\000c\000k\000s}{subsection.1.1}% 3
\BOOKMARK [3][-]{subsubsection.1.1.2}{\376\377\000Q\000u\000e\000u\000e\000s}{subsection.1.1}% 4
\BOOKMARK [2][-]{subsection.1.2}{\376\377\000L\000i\000n\000k\000e\000d\000\040\000L\000i\000s\000t\000s}{section.1}% 5
\BOOKMARK [3][-]{subsubsection.1.2.1}{\376\377\000I\000m\000p\000l\000e\000m\000e\000n\000t\000a\000t\000i\000o\000n\000\040\000o\000f\000\040\000L\000i\000n\000k\000e\000d\000\040\000L\000i\000s\000t\000s}{subsection.1.2}% 6
\BOOKMARK [3][-]{subsubsection.1.2.2}{\376\377\000S\000i\000n\000g\000l\000y\000\040\000L\000i\000n\000k\000e\000d\000\040\000L\000i\000s\000t\000\040\000C\000l\000a\000s\000s}{subsection.1.2}% 7
\BOOKMARK [1][-]{section.2}{\376\377\000A\000l\000g\000o\000r\000i\000t\000h\000m\000\040\000A\000n\000a\000l\000y\000s\000i\000s}{}% 8
\BOOKMARK [2][-]{subsection.2.1}{\376\377\000A\000l\000g\000o\000r\000i\000t\000h\000m\000\040\000A\000n\000a\000l\000y\000s\000i\000s\000\040\000B\000a\000s\000i\000c\000s}{section.2}% 9
\BOOKMARK [3][-]{subsubsection.2.1.1}{\376\377\000C\000o\000u\000n\000t\000i\000n\000g\000\040\000P\000r\000i\000m\000i\000t\000i\000v\000e\000\040\000O\000p\000e\000r\000a\000t\000i\000o\000n\000s}{subsection.2.1}% 10
\BOOKMARK [2][-]{subsection.2.2}{\376\377\000O\000\040\000N\000o\000t\000a\000t\000i\000o\000n}{section.2}% 11
\BOOKMARK [3][-]{subsubsection.2.2.1}{\376\377\000I\000m\000p\000o\000r\000t\000a\000n\000t\000\040\000F\000u\000n\000c\000t\000i\000o\000n\000s\000\040\000U\000s\000e\000d\000\040\000i\000n\000\040\000O\000\040\000N\000o\000t\000a\000t\000i\000o\000n}{subsection.2.2}% 12
\BOOKMARK [3][-]{subsubsection.2.2.2}{\376\377\000E\000f\000f\000i\000c\000i\000e\000n\000c\000y\000\040\000\046\000\040\000O\000\040\000N\000o\000t\000a\000t\000i\000o\000n}{subsection.2.2}% 13
\BOOKMARK [2][-]{subsection.2.3}{\376\377\000R\000e\000c\000u\000r\000s\000i\000o\000n\000\040\000R\000e\000v\000i\000e\000w}{section.2}% 14
\BOOKMARK [1][-]{section.3}{\376\377\000D\000y\000n\000a\000m\000i\000c\000\040\000P\000r\000o\000g\000r\000a\000m\000m\000i\000n\000g}{}% 15
\BOOKMARK [2][-]{subsection.3.1}{\376\377\000M\000o\000r\000e\000\040\000B\000i\000g\000\040\000G\000r\000e\000e\000k\000\040\000L\000e\000t\000t\000e\000r\000s}{section.3}% 16
\BOOKMARK [2][-]{subsection.3.2}{\376\377\000P\000,\000\040\000N\000P\000,\000\040\000\046\000\040\000N\000P\000-\000C\000o\000m\000p\000l\000e\000t\000e\000\040\000P\000r\000o\000b\000l\000e\000m\000s}{section.3}% 17
\BOOKMARK [1][-]{section.4}{\376\377\000S\000e\000a\000r\000c\000h\000i\000n\000g\000\040\000\046\000\040\000S\000o\000r\000t\000i\000n\000g}{}% 18
\BOOKMARK [2][-]{subsection.4.1}{\376\377\000K\000e\000y\000s\000\040\000\046\000\040\000V\000a\000l\000u\000e\000s}{section.4}% 19
\BOOKMARK [2][-]{subsection.4.2}{\376\377\000J\000a\000v\000a\000\040\000I\000n\000t\000e\000r\000f\000a\000c\000e\000:\000\040\000C\000o\000m\000p\000a\000r\000a\000t\000o\000r}{section.4}% 20
\BOOKMARK [2][-]{subsection.4.3}{\376\377\000J\000a\000v\000a\000\040\000I\000n\000t\000e\000r\000f\000a\000c\000e\000:\000\040\000C\000o\000m\000p\000a\000r\000a\000b\000l\000e}{section.4}% 21
\BOOKMARK [2][-]{subsection.4.4}{\376\377\000I\000n\000s\000e\000r\000t\000i\000o\000n\000\040\000S\000o\000r\000t}{section.4}% 22
\BOOKMARK [2][-]{subsection.4.5}{\376\377\000S\000h\000e\000l\000l\000\040\000S\000o\000r\000t}{section.4}% 23
\BOOKMARK [2][-]{subsection.4.6}{\376\377\000Q\000u\000i\000c\000k\000\040\000S\000o\000r\000t}{section.4}% 24
\BOOKMARK [1][-]{section.5}{\376\377\000T\000r\000e\000e\000s}{}% 25
\BOOKMARK [2][-]{subsection.5.1}{\376\377\000B\000i\000n\000a\000r\000y\000\040\000T\000r\000e\000e\000s}{section.5}% 26
\BOOKMARK [2][-]{subsection.5.2}{\376\377\000G\000e\000n\000e\000r\000i\000c\000s\000\040\000i\000n\000\040\000J\000a\000v\000a}{section.5}% 27
\BOOKMARK [1][-]{section.6}{\376\377\000S\000e\000a\000r\000c\000h\000\040\000T\000r\000e\000e\000s}{}% 28
\BOOKMARK [2][-]{subsection.6.1}{\376\377\000B\000i\000n\000a\000r\000y\000\040\000S\000e\000a\000r\000c\000h\000\040\000T\000r\000e\000e\000s}{section.6}% 29

Binary file not shown.

View File

@ -0,0 +1,745 @@
\documentclass[11pt]{article}
\usepackage{report}
\usepackage{algpseudocode}
\usepackage{algorithm}
\usepackage[utf8]{inputenc} % allow utf-8 input
\usepackage[T1]{fontenc} % use 8-bit T1 fonts
\usepackage[colorlinks=true, linkcolor=black, citecolor=blue, urlcolor=blue]{hyperref} % hyperlinks
\usepackage{url} % simple URL typesetting
\usepackage{booktabs} % professional-quality tables
\usepackage{amsfonts} % blackboard math symbols
\usepackage{nicefrac} % compact symbols for 1/2, etc.
\usepackage{microtype} % microtypography
\usepackage{lipsum} % Can be removed after putting your text content
\usepackage{graphicx}
\graphicspath{ {./images/} }
\usepackage{natbib}
\usepackage{doi}
\setcitestyle{aysep={,}}
\usepackage{array}
\usepackage{listings}
\usepackage{xcolor}
\definecolor{codegreen}{rgb}{0,0.6,0}
\definecolor{codegray}{rgb}{0.5,0.5,0.5}
\definecolor{codeorange}{rgb}{1,0.49,0}
\definecolor{backcolour}{rgb}{0.95,0.95,0.96}
\lstdefinestyle{mystyle}{
backgroundcolor=\color{backcolour},
commentstyle=\color{codegray},
keywordstyle=\color{codeorange},
numberstyle=\tiny\color{codegray},
stringstyle=\color{codegreen},
basicstyle=\ttfamily\footnotesize,
breakatwhitespace=false,
breaklines=true,
captionpos=b,
keepspaces=true,
numbers=left,
numbersep=5pt,
showspaces=false,
showstringspaces=false,
showtabs=false,
tabsize=2,
xleftmargin=10pt,
}
\lstset{style=mystyle}
\title{CT2109 - Object Oriented Programming: Data Structures \& Algorithms}
\author{Andrew Hayes\\
\AND
\AND
\AND
\AND
\AND
2BCT\\
\AND
University of Galway\\
}
% Uncomment to remove the date
% \date{February 2022}
% Uncomment to override the `A preprint' in the header
\renewcommand{\headeright}{Object Oriented Programming: Data Structures \& Algorithms}
\renewcommand{\undertitle}{Object Oriented Programming: Data Structures \& Algorithms}
\renewcommand{\shorttitle}{}
%%% Add PDF metadata to help others organize their library
%%% Once the PDF is generated, you can check the metadata with
%%% $ pdfinfo template.pdf
% \hypersetup{
% pdftitle={A template for the arxiv style},
% pdfsubject={q-bio.NC, q-bio.QM},
% pdfauthor={David S.~Hippocampus, Elias D.~Striatum},
% pdfkeywords={First keyword, Second keyword, More},
% }
\begin{document}
\maketitle
\newpage
\tableofcontents
\thispagestyle{empty}
\setcounter{page}{1}
\newpage
\section{Abstract Data Types}
An \textbf{Abstract Data Type (ADT)} is an abstract model of a data structure that specifies the data stored \& oeprations that may be performed on the data.
An ADT specifies \textit{what} each operation does, but not \textit{how}.
In object-oriented languages such as Java, this naturally corresponds to an \textbf{interface definition}.
An ADT is \textit{realised} as a concrete data structure.
In Java, this is a class that \textbf{implements} the interface.
\begin{center}
\includegraphics[width=0.3\textwidth]{adt.png}
\end{center}
\textbf{Composite ADTs} are used manage \textit{collections} of data, e.g., Arrays, Lists, Stacks, Queues, Hash Tables, etc.
\subsection{Stacks \& Queues}
\textbf{Stacks} \& \textbf{Queues} are linearly ordered ADTs for list-structured data.
\subsubsection{Stacks}
A \textbf{Stack} is a last in, first out (LIFO) data structure.
No sort order is assumed.
Items can only enter or leave via the \textit{top} of the stack.
Items can be \textbf{pushed} \& \textbf{popped} to add \& remove.
Example applications of a stack include processing nested structures or the ``undo'' operation in an editor.
Objects stored in a stack are a \textit{finite sequence} of elements of the \textbf{same type}.
Stacks have few operations.
For a stack \verb|s|, node \verb|n|, \& boolean value \verb|b|:
\begin{itemize}
\item \verb|s.push(n)| - Place item \verb|n| on top of the stack.
\item \verb|s.pop()| $\rightarrow$ \verb|n| - Remove top item from the stack \& return it.
\item \verb|s.top| $\rightarrow$ \verb|n| - Examine the top item on the stack without removing it.
\item \verb|s.isEmpty()| $\rightarrow$ \verb|b| - Returns \verb|b = true| if the stack is empty.
\item \verb|s.isFull()| $\rightarrow$ \verb|b = true| if the stack is full (relevant if storage is limited).
\end{itemize}
Java has a built-in stack interface from \verb|java.util.Stack|.
However, we will look at making our own for the sake of learning.
Our stack implementation may look something like this:
\begin{lstlisting}[language=java]
public interface Stack {
public void push(Object n);
public Oject pop();
public Object top();
public boolean isEmpty();
public boolean isFull();
\end{lstlisting}
Other stack operations include \verb|size()| \& \verb|makeEmpty()|.
We could implement this stack using an array, linked list, or other storage type.
\subsubsection{Queues}
A \textbf{Queue} is a first in, first out (FIFO) data structure.
No sort order is assumed.
Items enter at the rear of the queue, and leave at the front of the queue.
Items can be \textbf{enqueued} \& \textbf{dequeued} to add \& remove them from the queue.
Example applications of a queue include ensuring ``fair treatment'' to each of a list of pending tasks (first come, first served)
or simulation: modelling \& analysis of real-world problems.
Objects stored in a queue are a finite sequence of elements of the same type.
The item at the front of the queue has been in the queue the longest, while the item at the rear has entered the queue most recently.
Queues have few operations.
For a queue \verb|q|, element \verb|e|, \& boolean value \verb|b|:
\begin{itemize}
\item \verb|q.enqueue(e)| - Place \verb|e| at the rear of \verb|q|, assuming there is space.
\item \verb|q.dequeue()| $\rightarrow$ \verb|e| - Remove fron item \verb|e| from \verb|q| and return it.
\item \verb|q.front()| $\rightarrow$ \verb|e| - Returns front element \verb|e| without removing it.
\item \verb|q.isEmpty()| $\rightarrow$ \verb|b| - Returns \verb|b = true| if the queue is empty.
\item \verb|q.isFull()| $\rightarrow$ \verb|b| - Returns \verb|b = true| if the queue is full.
\end{itemize}
With an array implementation of a queue, items must be ``shuffled'' towards the front after a \textit{dequeue}.
Note that with an array implementation, once \verb|rear| becomes equal to $N-1$, no further items can be enqueued (array space limitation).
\subsection{Linked Lists}
A \textbf{Linked List} is an abstract data type which stores an arbitrary-length list of data objects as a sequence of \textit{nodes}.
Each node consists of data and has a \textbf{link} to the next node.
Each node, excepting the last, is links to a \textbf{successor node}.
\begin{center}
\includegraphics[width=0.6\textwidth]{ll.png}
\end{center}
Characteristics of Linked Lists:
\begin{itemize}
\item \textbf{Self-referential} structure type - Every node has a pointer to a node of the same type.
\item Very useful for \textbf{dynamically} growing/shrinking lists of data.
\item Compared to arryas, drastically reduces the effort required to add/remove items from the middle of the list.
\item Solves the potential problem of \textbf{overflow} that arrays have.
\item \textbf{Sequential access} - It is \textbf{inefficient} to retrieve an element at an arbitrary position, relative to an array.
\end{itemize}
\subsubsection{Implementation of Linked Lists}
We define a \textbf{Node} class, with members \textbf{data} (whichever variables are required) \& \textbf{next} (reference to another Node object).
Each node occcurrence is linked to a succeeding occurence by way of the member \textbf{next}.
If \verb|next| is \verb|null|, then there is no item after this node in the list (termed the \textbf{tail} node).
The starting point for the list is the \textbf{head} node.
We can trace from the head node to any other node.
\begin{center}
\includegraphics[width=0.3\textwidth]{node.png}
\end{center}
\begin{lstlisting}[language=Java]
public class Node {
// instance variables
private Object element;
private Node next;
// creates node with null refs to its element \& next node
public Node() {
this(null, null);
}
// creates node with the given element & next node
public Node(Object e, Node n) {
element = e;
next = n;
}
// accessor methods
public Object getElement() {
return element;
}
public Node getNext() {
return next;
}
// mutator methods
public void setElement(Object newElem) {
element = newElem;
}
public void setNext(Node newNext) {
next = newNext;
}
}
\end{lstlisting}
Generally, we don't create nodes manually, rather we just supply element data to a method which keeps track of the current position in the list.
Typical methods in a Linked List ADT include:
\begin{itemize}
\item \verb|long size()| - Returns the size of the list.
\item \verb|boolean isEmpty()| - Returns \verb|true| if the list is empty, \verb|false| otherwise.
\item \verb|Object getCurr()| - Returns the element at the current position.
\item \verb|boolean gotoHead()| - Sets the current position to \verb|head|, returning \verb|true| if successful.
\item \verb|boolean gotoNext()| - Moves to the next position, returning \verb|true| if successful.
\item \verb|void insertNext(Object el| - Creates a new node after the current node.
\item \verb|void deleteNext()| - Removes the node after the current node.
\item \verb|void insertHead(Object el)| - Creates a new node at the head.
\item \verb|void deleteHead()| - Removes the head node.
\end{itemize}
\subsubsection{Singly Linked List Class}
A \textbf{singly linked list} is one in which each node links to a \textit{single} other node.
The Singly Linked List Class should store the head of the list \& the current position.
For efficiency, it also keeps track of the current size of the list (alternatively, we could just count its nodes when needed).
\begin{lstlisting}[language=Java]
public class SLinkedList {
protected Node head; // head node of the list
protected Node curr; // current position in list
protected long size; // number of nodes in the list
// default constructor which creates an empty list
public SLinkedList() {
curr = head = null;
size = 0;
}
// insert, remove, & search methods go here
}
\end{lstlisting}
\section{Algorithm Analysis}
All algorithms take CPU \textbf{time} \& \textbf{memory} space.
Often, we can make tradeoffs, choosing algorithm variants that either user more memory, or more CPU.
If the memory space requirements of an algorithm are large, the program may use disk sawp space rather than RAM, which is much slower.
If the memory requirements are too large, then the program cannot run.
Often, we identify the algorithms that don't require ``too much'' spaace, and then choose the one with the lowest
CPU requirements.
The purpose of algorithm analysis is comparing the time \& space requirements of various algorithms.
``Why not just run the algorithm and measure the time \& space used?'' -
While this is sometimes done when theoretical analysis is difficult, it is better to be able to evaluate
algorithms ``on paper'' without first having to implement, debug, and test them all.
It's important to have a measure that's \textit{independent} of particular computer configurations and to be able to
compare algorithms reliably, without being influenced by variations in implementation.
We want to understand how an algorithm will perform on large problems and identify ``hot spots'' to give our attention
to when developing \& optimising programs.
\subsection{Algorithm Analysis Basics}
\textbf{Theoretical Analysis} uses a high-level \textit{pseudocode} description of the algorithm instead of a real
implementation, and characterises run-time as a function of input size $n$.
This function specifies the \textbf{order of growth} of rate of runtime as $n$ increases.
Theoretical analysis takes into account all possible inputs and evaluates speed independent of hardware or software.
\subsubsection{Counting Primitive Operations}
The basic approach is deriving the function for the \textbf{count of the primitive operations}.
The primitive operations are the individual steps performed by a program.
We assume that each step takes the same amount of time and examine any terms that control repetition.
Example: Algorithm to find the largest element of an array.
We count the maximum number of operations as function of array size $n$.
\begin{lstlisting}
Algorithm arrayMax(A, n) // Number of Operations
currentMax = A[0] // 2
for i = 1 to n -1 do // 2n
if A[i] > currentMax then // 2(n-1)
currentMax = A[i] // 2(n-1)
{increment coutner i} // 2(n-1)
return currentMax // 1
// Total: 8n-3
\end{lstlisting}
We could consider the \textbf{average}, \textbf{best}, or \textbf{worst} case.
Usually, we analyse the worst case, as we want our algorithms to work well even in bad cases.
The average case is quite important too, if different from the worst case.
These counts are the basis of (big) O notation.
\subsection{O Notation}
The basic approach to \textbf{O Notation} involves deriving an expression for the count of basic operations (as
discussed).
We focus on the \textit{dominant term}, and ignore constants.
E.g., $O(5n^2 + 1000n -3) \rightarrow O(n^2)$.
Since contants \& low-order terms are eventually dropped, we can disregard them when counting primitive operations.
O Notation is used for \textbf{asymptotic analysis of complexity} - the trend in the algorithms runtime as $n$
gets large.
We look at the \textbf{order of magnitude} of the number of actions, independent of computer/compiler/etc.
Note: We specifically care about the \textbf{tightest} upper bound.
Technically speaking, an algorithm that is $O(n^2)$ is also $O(n^3)$, but the former is more informative.
The function specified in O notation is the \textbf{upper bound} on the behaviour of the algorithm being analysed.
This can be the best/average/worst case behaviour.
Example: Let $f(n) = 6n^4 -2n^3 + 5$.
Apply the following rules:
\begin{itemize}
\item If $f(n)$ is a sum of several terms, then only the one with largest rate of growth is kept.
\item If $f(n)$ is a product of several factors, any constants that do not depend on $n$ are ommitted.
\end{itemize}
Thus, we say that $f(n)$ has a ``big-oh'' of $(n^4)$.
We can write $f(n)$ is $O(n^4)$.
\subsubsection{Important Functions Used in O Notation}
Functions commonly used include:
\begin{itemize}
\item \textbf{Constant:} $O(1)$.
\item \textbf{Logarithmic:} $O($log$n)$.
\item \textbf{Linear:} $O(n)$.
\item \textbf{n-Log-n:} $O(n$log$n)$.
\item \textbf{Quadratic:} $O(n^2)$.
\item \textbf{Cubic:} $O(n^3)$.
\item \textbf{Exponential:} $(1^n)$.
\end{itemize}
Notes:
\begin{itemize}
\item By convention, all logs are base 2 unless otherwise stated.
\item Two algorithms having the same complexity doesn't been that they are exactly the same, it means that their
running times will be \textit{proportional}.
\end{itemize}
\begin{center}
\includegraphics[width=0.8\textwidth]{comparisonoffunctions1.png}
\end{center}
\begin{center}
\includegraphics[width=0.8\textwidth]{comparisonoffunctions2.png}
\end{center}
\subsubsection{Efficiency \& O Notation}
\begin{itemize}
\item \textbf{Constant:} Most efficient possible, but only applicable to simple jobs.
\item \textbf{Logarithmic, Linear, \& n-Log-n:} If an algorithm is described as ``efficient'', this usually means
$O($log$n)$ or better.
\item \textbf{Quadratic \& Cubic:} Not very efficient, but polynomial algorithms are usually considered ``tractable''
(acceptable for problems of reasonable size).
\item \textbf{Exponential:} Very inefficient. Problems that (provably) require an algorithm of O greater than
polynomial complexity are called ``\textbf{hard}''.
\end{itemize}
\subsection{Recursion Review}
Methods can call other methods, but they can also call themselves, either directly, or indirectly, via
another method.
This creates a type of loop called \textbf{recursion}.
Iteration can be used anywhere that you can use recursion.
Sometimes, recursion can be a more elegant solution, if it reflects the way that the problem is usually thought
about, as we aim to use the most intuitive representation of the problem.
Recursion can make complexity analysis easier in some cases.
The drawbacks of recursion include:
\begin{itemize}
\item Inefficient use of the function: Large amount of concurrent, deeply nested method calls.
\item If done naively, the number of calls can explode.
\item Depending on the algorithm, we need to take care not to recompute values unnecessarily.
\end{itemize}
\section{Dynamic Programming}
The basic idea of \textbf{Dynamic Programming} is to solve complex problems by breaking them into simpler
sub-problems.
When a solution to a sub-problem is found, store it (``memo-ize'') so that it can be re-used without
recomputing it.
Combine the solutions to the sub-problems to get the overall solution.
This is particularly useful when the number of repeating sub-problems grows exponentially with the problem
size.
In general, dynamic programming takes problems that appear exponential and produces polynomial-time algorithms
for them.
The trade-off in dynamic programming is between \textit{storage} \& \textit{speed}.
Dynamic programming is widely used in heuristic optimisation problems.
For Dynamic Programming, the problem structure requires three components:
\begin{enumerate}
\item \textbf{Simple sub-problems:} Must be able to break the overall problem into indexed sub-problems
\& sub-sub-problems.
\item \textbf{Sub-problem decomposition:} Optimal/correct solution to the overall problem must be
composed from sub-problems.
\item \textbf{Sub-problem overlap:} So that elements can be re-used.
\end{enumerate}
The basic steps in the approach to DynProg:
\begin{enumerate}
\item Set up the overall problem as one that is decomposable into overlapping sub-problems that can
be indexed.
\item Solve the sub-problems as they arise and \textbf{store solutions} in a table.
\item Derive the overall solution from the solutions in the table.
\end{enumerate}
\subsection{More Big Greek Letters}
$O(n$log$n)$ (``Big Oh''):
\begin{itemize}
\item Upper bound on asymptotic complexity.
\item In this case, there is a constant $c_2$ such that $c_2 n$log$n$ is an upper bound on
asymptotic complexity.
\end{itemize}
$\Omega(n$log$n)$ (``Big Omega''):
\begin{itemize}
\item Specifies a lower bound on asymptotic complexity.
\item In this case, the algorithm has a lower bound of $c_1 n$log$n$.
\end{itemize}
$\Theta(n$log$n)$ (``Big Theta''):
\begin{itemize}
\item Specifies the upper \& lower bounds.
\item In this case, there exist two constants, $c_1$ \& $c_2$, such that $c_1n$log$n < f(n) < c_2n$log$n$.
\end{itemize}
Of these, $\Theta()$ makes the strongest claims: It specifies that the rate of growth is no better and no
worse than some level.
Requires additional analysis relative to $O$.
There are also some others that are common in Mathematics but not in Computer Science:
\begin{itemize}
\item \textbf{Little o:} $o(g(n))$ specifies a function $g(n)$ that grows much faster than the one
that we are analysing.
\item \textbf{Little omega:} $\omega(g(n))$ specifies a function $g(n)$ that grows much slower than
the one that we are analysing.
\end{itemize}
Don't confuse upper/lower bounds with best/worst case: all cases have bounds.
\newpage
\subsection{P, NP, \& NP-Complete Problems}
\textbf{P Problems} are those for which there is a \textbf{deterministic} algorithm that solves it in
\textbf{Polynomial Time}.
In other words, the algorithm's complexity is $O(p(n))$ where $p(n)$ is a polynomial function.
A (trivial) example of a P problem is searching an array of integers for a certain value.
Problems that can be solved in polynomial time are termed \textbf{tractable}, while worse problems are
termed \textbf{intractable}.
\textbf{NP Problems (Non-deterministic Polynomial)} are those algorithms which have two repeating steps:
\begin{itemize}
\item Generate a \textit{potential solution}, either randomly or systematically.
\item Verify whether the potential solution is right, and if not, repeat.
\end{itemize}
If the verification step is \textbf{polynomial}, the algorithm \& associated problem are \textbf{NP}.
An example of an NP problem is factoring large integers as used in RSA encryption.
Another example of an NP problem is the \textbf{subset problem}:
Given a set of integers, does some non-empty subset of them sum to 0?
There is no polynomial algorithm to solve this problem.
However, verification of a potential solution is polynomial ($O(n)$ (just add up the numbers in the
potential solution)).
Note that P is a subset of NP.
\textbf{NP-Complete} problems are those that are ``\textbf{as hard as} all others'' in NP, i.e. algorithms that
are comparable to (``\textbf{polynomially reducible} to'') others in NP but not reducible to P.
If an algorithm is \textbf{polynomially reducible}, there is some polynomial-time transformation that
converts the inputs for Problem $X$ to inputs for Problem $Y$.
NP-Complete is a complexity class which represents the set of all problems $X$ in NP for which it is
possible to reduce any other NP problem $Y$ to $X$ in polynomial time.
Intuitively, this means that we can solve $Y$ quickly if we know how to solve $X$ quickly.
What makes NP-complete problems inportant is that if a deterministic polynomial time algorithm can be
found to solve one of them, every NP problem is solvable in polynomial time.
\textbf{NP-Hard} problems are those that are ``\textbf{as hard or harder}'' than all others in NP.
A problem $X$ is Np-Hard if NP-Complete problems are polynomially reducible to it.
Intuitively, NP-hard problems are problems that are at least as hard as the NP-complete problems.
Note that NP-hard problems do not have to be in NP, and they do not have to be decision problems.
The precise definition here is that ``a problem $X$ is NP-hard, if there is an NP-complete problem $Y$,
such that $Y$ is reducible to $X$ in polynomial time''.
An example of an NP-hard problem is \textit{the halting problem}: Given a program $P$ and input $I$,
will it halt?
The ``P versus NP'' problem is a major unsolved problem in computer science:
``If the solution to a problem is easy to verify, is the problem also easy to solve?'' or ``whether
every problem whose solution can be \textbf{quickly verified} by a computer can also be \textbf{quickly solved}
by a computer''.
``Quickly'' here means that there exists an algorithm to solve the task that runs in polynomial time.
An answer to the $P = NP$ question would determine whether all problems that can be verified in polynomial time can also be solved in
polynomial time.
If it turned out that $P \neq NP$, then it would mean that there are problems in NP (such as NP-complete problems) that are harder to compute
than to verify.
We already know that $P \subseteq NP$.
In theoretical computer science, the problems considered for P \& NP are \textbf{decision problems}, i.e. problems that don't produce
numeric results but yes or no answers.
\begin{center}
\includegraphics[width=0.6\textwidth]{pvsnp.png}
\end{center}
\begin{itemize}
\item \textbf{P} (Polynomial): Solvable in polynomial time.
\item \textbf{NP} (Non-Deterministic Polynomial): Only \textit{verifiable} in polynomial time.
\end{itemize}
\section{Searching \& Sorting}
\subsection{Keys \& Values}
Each object to be sorted can be considered to have a \textbf{key} \& a \textbf{value}, e.g. A Student has properties Name, ID, \& grade.
\subsection{Java Interface: Comparator}
The \verb|Comparator| interface compares two objects to say which should come first.
In Java, any class that implements \verb|java.util.Comparator| interface is only required to implement one method:
\begin{lstlisting}[language=java]
int compare(Object ob1, Object ob2);
\end{lstlisting}
This returns a negative number if \verb|ob1| is less than \verb|ob2|, a positive number if \verb|ob1| is greater than \verb|ob2|, and \verb|0| if \verb|ob1| is equal to \verb|ob2|.
\subsection{Java Interface: Comparable}
The \verb|Comparable| interface compares a given object to another to see which object should come first.
The two objects that are being compared must be of a class that implements \verb|java.lang.Comparable|, which has just one method to implement:
\begin{lstlisting}[language=java]
int compareTo(Object other);
\end{lstlisting}
Standard classes such as \verb|String| implement this.
\subsection{Insertion Sort}
Consider sorting a bookshelf using \textbf{Insertion Sort}:
\begin{enumerate}
\item Remove the next unsorted book.
\item Slide the sorted books to the right one by one until you find the right sport for for the removed book.
\item Insert the book into its new position once it is found.
\end{enumerate}
\begin{algorithm}
\caption{Insertion Sort Pseudocode}
\begin{algorithmic}
\Require{$A[0 \dots N-1]$} \Comment{Unsorted Array}
\Ensure{$A[0 \dots N-1]$} \Comment{Sorted Array}
\Procedure{Insertion Sort}{$A[0 \dots N-1]$}
\For{$ToSort \gets 1$ to $N-1$ Step 1}
\State $Index = ToSort -1$
\State $ToSortEl = A[ToSort]$
\\
\While{$Index \geq First$ AND $A[Index] > ToSortEl$}
\State $A[Index+1] \gets A[Index]$ \Comment{Shuffle elements to the right}
\State $Index \gets Index - 1$
\EndWhile
\\
\State $A[Index+1] = ToSortEl$ \Comment{Insert the element to sort in its appropriate place}
\EndFor
\State \textbf{return} $A[]$ \Comment{Return the sorted array}
\EndProcedure
\end{algorithmic}
\end{algorithm}
The worst case efficiency of Insertion Sort is $O(n^2)$.
The best case efficiency of Insertion Sort is $O(n)$.
If the array is closer to sorted order, the algorithm does less work, and the operation is more efficient.
This leads to a related algorithm: Shell Sort.
\newpage
\subsection{Shell Sort}
\textbf{Shell Sort} is more efficient than Selection Sort or Insertion Sort.
It works by comparing distant items first, and works its way down to nearby items.
The interval is called the \textbf{gap}.
The gap begins at one half of the length of the list and is successively halved until each item has been compared with its neighbour.
Insertion Sort only tests elements in \textit{adjacent} locations - it might take several steps to get to the final location.
Insertion Sort is more efficient if an array is partially sorted.
By making larger jumps, Shell Sort makes the array become ``more sorted'' more quickly.
\begin{algorithm}
\caption{Shell Sort Pseudocode}
\begin{algorithmic}
\Require{$A[0 \dots N-1]$} \Comment{Unsorted Array}
\Ensure{$A[0 \dots N-1]$} \Comment{Sorted Array}
\Procedure{Shell Sort}{$A[0 \dots N-1]$}
\State $Gap \gets floor(\frac{Gap}{2})$ \Comment{Round to the nearest odd number, as it's best with an odd-sized gap}
\\
\While{$Gap \geq 1$}
\For{$ToSort \gets 1$ to $N-1$ Step 1}
\State $Index = ToSort -1$
\State $ToSortEl = A[ToSort]$
\\
\While{$Index \geq First$ AND $A[Index] > ToSortEl$}
\State $A[Index+1] \gets A[Index]$ \Comment{Shuffle elements to the right}
\State $Index \gets Index - 1$
\EndWhile
\\
\State $A[Index+1] = ToSortEl$ \Comment{Insert the element to sort in its appropriate place}
\EndFor
\\
\State $Gap \gets floor(\frac{Gap}{2})$
\EndWhile
\EndProcedure
\end{algorithmic}
\end{algorithm}
The worst-case complexity of Shell Sort is $O(n^2)$.
However, this is because the gap is sometimes even which results in sub-arrays that include all the elements of an array that was already sorted.
To avoid this, we round the gap up to the nearest odd number which gives us a worst-case complexity of $O(n^{1.5})$.
Other gap sequences can improve performance a little more, but this is beyond the scope of this topic.
\subsection{Quick Sort}
\textbf{Quick Sort} is a divide-and-conquer algorithm.
\begin{enumerate}
\item Firstly, it partitions the array into two sub-arrays that are \textbf{partially sorted}.
\item Then, it picks a \textbf{pivot value}, and re-arranges the elements such that all elements less than or equal to the pivot value are on the left of the pivot, and all elements that are greater than
it are on the right.
\item The array is now divided into sub-arrays and a pivot value.
\item This procedure is then repeated \textbf{recursively} for each sub-array, to further sort each of them.
\item When the algorithm has reached the level of a sub-array with just one element, that sub-array is sorted.
All sub-arrays are sorted relative to each other, so the whole array is sorted when all the sub-arrays are.
\end{enumerate}
\section{Trees}
The data structures that we looked at previously placed data in linear order, but we sometimes need to organise data into groups \& sub-groups.
This is called \textbf{hierarchical classification}, where data items appear at various levels within the organisation.
In Computer Science, a tree is an abstract model of a hierarchical structure which consists of nodes with a parent-child relation.
Trees have applications in organisation charts, file systems, programming environments, \& more.
A \textbf{tree} is a set of nodes, connected by edges.
The edges indicate relationships between nodes.
Nodes are arranged in \textbf{levels}, which indicate the node's position in the hierarchy.
Nodes with the same parent node are called \textbf{siblings}.
The only node with no parent is the \textbf{root} node.
All other nodes have one parent each.
A node with no child nodes is called a \textbf{leaf} node or an \textbf{external} node.
All other nodes are referred to as \textbf{internal} nodes.
A node is reached from the root by a \textbf{path}.
The length of a path is the number of edges that compose it.
This is also referred to as the depth of the node.
The \textbf{height} of a tree is the number of levels in the tree.
The number of nodes along the longest path is equal to the maximum depth plus one.
Note that we talk about the depth of a node, but the height of a tree.
The ancestors of a node include its parent, grandparent, great-grandparent, etc.
The descendants of a node include its children, grandchildren, great-grandchildren, etc.
A \textbf{subtree} of a node is a tree that has that node as its root, including the node, all its descendants, and the arcs connecting them.
\subsection{Binary Trees}
A \textbf{binary tree} is one in which each internal node has at most two children (\& exactly two if it is a ``\textbf{proper}'' binary tree).
The children of a node are an \textbf{ordered pair}.
We refer to the children of an internal node as the left child \& the right child.
Non-binary trees are termed general trees.
An alternative (recursive) definition for binary trees is a tree that is either just single node or a tree whose root has an ordered pair of children, each of which is a binary tree.
A \textbf{full binary tree} is one in which is a proper binary tree, and in which all the leaves are on the same level.
This is only achievable for certain numbers of nodes.
A \textbf{complete binary tree} is a binary tree which is full to the penultimate level and the leaves on the last level are filled frmo left to right.
This is achievable for any number of nodes.
The height of either a complete or full binary tree with $n$ nodes is log$_2(n+1)$.
\begin{center}
\includegraphics[width=0.7\textwidth]{binarytrees.png}
\end{center}
\subsection{Generics in Java}
The \verb|< >| operators relate to the concept of \textbf{generics}.
Generics are used to specify a specific type parameter for a generic collection class.
This saves us from having to cast objects in methods such as \verb|add()|, \verb|set|, \& \verb|remove|.
This is a big advantage, as type checking is now done at compile time.
Without generics, compile-time type-checking is impossible, since we don't have a type specification for the list.
Other object-oriented programming languages have similar concepts, such as templates in C++.
\verb|ArrayList|s are part of the Java Collections framework, a standard library of pre-built data structures.
The underlying storage of an \verb|ArrayList| is an array.
The \verb|ArrayList| class looks after resizing it as required.
\verb|ArrayLists| can be used with or without generics notation.
\begin{lstlisting}[language=Java]
// ArrayList code without generics:
ArrayList words = new ArrayList(); // holds objects
words.add("hello");
String a = (String) words.get(0); // return type of get() is object, so must cast to String
// ArrayList parameterised to specifically hold Strings
ArrayList<String> words = new ArrayList<String>();
words.add("hello");
String a = words.get(0); // no cast needed
\end{lstlisting}
Creating a Generics collection:
\begin{lstlisting}[language=Java]
public interface List<E> {
void add(E x);
Iterator<E> iterator();
}
public interface Iterator<E> {
E next();
boolean hasNext();
}
\end{lstlisting}
\section{Search Trees}
A \textbf{Search Tree} organises its data so that searching it is efficient.
\subsection{Binary Search Trees}
A \textbf{Binary Search Tree (BST)} is a binary tree with nodes that contain \verb|Comparable| objects.
A node's data is greater than the data in the left subtree and less than the data in the right subtree.
Usually, no duplicates are allowed.
An \textbf{in-order} traversal of a BST will visit all nodes in ascending order.
BSTs are not uniquely structured - The structure of a BST depends on what node is chosen as the root of the tree and the order in which all the other nodes are added.
\bibliographystyle{unsrtnat}
\bibliography{references}
\end{document}

View File

@ -0,0 +1,29 @@
\contentsline {section}{\numberline {1}Abstract Data Types}{2}{section.1}%
\contentsline {subsection}{\numberline {1.1}Stacks \& Queues}{2}{subsection.1.1}%
\contentsline {subsubsection}{\numberline {1.1.1}Stacks}{2}{subsubsection.1.1.1}%
\contentsline {subsubsection}{\numberline {1.1.2}Queues}{2}{subsubsection.1.1.2}%
\contentsline {subsection}{\numberline {1.2}Linked Lists}{3}{subsection.1.2}%
\contentsline {subsubsection}{\numberline {1.2.1}Implementation of Linked Lists}{3}{subsubsection.1.2.1}%
\contentsline {subsubsection}{\numberline {1.2.2}Singly Linked List Class}{4}{subsubsection.1.2.2}%
\contentsline {section}{\numberline {2}Algorithm Analysis}{5}{section.2}%
\contentsline {subsection}{\numberline {2.1}Algorithm Analysis Basics}{5}{subsection.2.1}%
\contentsline {subsubsection}{\numberline {2.1.1}Counting Primitive Operations}{5}{subsubsection.2.1.1}%
\contentsline {subsection}{\numberline {2.2}O Notation}{5}{subsection.2.2}%
\contentsline {subsubsection}{\numberline {2.2.1}Important Functions Used in O Notation}{6}{subsubsection.2.2.1}%
\contentsline {subsubsection}{\numberline {2.2.2}Efficiency \& O Notation}{7}{subsubsection.2.2.2}%
\contentsline {subsection}{\numberline {2.3}Recursion Review}{7}{subsection.2.3}%
\contentsline {section}{\numberline {3}Dynamic Programming}{7}{section.3}%
\contentsline {subsection}{\numberline {3.1}More Big Greek Letters}{8}{subsection.3.1}%
\contentsline {subsection}{\numberline {3.2}P, NP, \& NP-Complete Problems}{9}{subsection.3.2}%
\contentsline {section}{\numberline {4}Searching \& Sorting}{10}{section.4}%
\contentsline {subsection}{\numberline {4.1}Keys \& Values}{10}{subsection.4.1}%
\contentsline {subsection}{\numberline {4.2}Java Interface: Comparator}{10}{subsection.4.2}%
\contentsline {subsection}{\numberline {4.3}Java Interface: Comparable}{10}{subsection.4.3}%
\contentsline {subsection}{\numberline {4.4}Insertion Sort}{10}{subsection.4.4}%
\contentsline {subsection}{\numberline {4.5}Shell Sort}{12}{subsection.4.5}%
\contentsline {subsection}{\numberline {4.6}Quick Sort}{12}{subsection.4.6}%
\contentsline {section}{\numberline {5}Trees}{13}{section.5}%
\contentsline {subsection}{\numberline {5.1}Binary Trees}{13}{subsection.5.1}%
\contentsline {subsection}{\numberline {5.2}Generics in Java}{13}{subsection.5.2}%
\contentsline {section}{\numberline {6}Search Trees}{14}{section.6}%
\contentsline {subsection}{\numberline {6.1}Binary Search Trees}{14}{subsection.6.1}%

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

Some files were not shown because too many files have changed in this diff Show More