Rename year directories to allow natural ordering
@ -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;
|
||||
}
|
||||
|
||||
}
|
@ -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;
|
||||
}
|
||||
|
||||
}
|
@ -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}
|
After Width: | Height: | Size: 24 KiB |
After Width: | Height: | Size: 58 KiB |
After Width: | Height: | Size: 22 KiB |
@ -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
|
||||
|
@ -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);
|
||||
}
|
||||
}
|
@ -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)
|
||||
}
|
@ -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;
|
||||
}
|
||||
}
|
||||
}
|
@ -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");
|
||||
}
|
||||
|
||||
}
|
||||
}
|
@ -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}
|
@ -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
|
||||
|
||||
%----------------------------------------------------------------------------------------
|
After Width: | Height: | Size: 50 KiB |
After Width: | Height: | Size: 86 KiB |
After Width: | Height: | Size: 43 KiB |
After Width: | Height: | Size: 74 KiB |
After Width: | Height: | Size: 79 KiB |
@ -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}
|
||||
% ===============================================
|
@ -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}
|
After Width: | Height: | Size: 66 KiB |
@ -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]{...}
|
@ -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];
|
||||
}
|
||||
}
|
@ -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);
|
||||
}
|
||||
}
|
@ -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;
|
||||
}
|
||||
}
|
@ -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
|
||||
}
|
||||
}
|
@ -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
|
||||
}
|
||||
}
|
@ -0,0 +1,3 @@
|
||||
public interface PalindromeChecker {
|
||||
public boolean checkPalindrome(String str);
|
||||
}
|
@ -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
|
||||
}
|
@ -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;
|
||||
}
|
||||
}
|
||||
}
|
@ -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);
|
||||
}
|
||||
}
|
@ -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)
|
||||
}
|
@ -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;
|
||||
}
|
||||
}
|
@ -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();
|
||||
}
|
||||
}
|
||||
}
|
@ -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
|
|
@ -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
|
|
@ -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
|
|
@ -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
|
|
@ -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}
|
@ -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
|
||||
|
||||
%----------------------------------------------------------------------------------------
|
After Width: | Height: | Size: 50 KiB |
After Width: | Height: | Size: 86 KiB |
After Width: | Height: | Size: 43 KiB |
After Width: | Height: | Size: 74 KiB |
After Width: | Height: | Size: 79 KiB |
After Width: | Height: | Size: 78 KiB |
@ -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}
|
||||
% ===============================================
|
@ -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}
|
@ -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]{...}
|
@ -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
|
||||
|
||||
%----------------------------------------------------------------------------------------
|
@ -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"
|
||||
}
|
@ -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}
|
||||
% ===============================================
|
@ -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}
|
After Width: | Height: | Size: 66 KiB |
@ -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]{...}
|
@ -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
|
@ -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
|
@ -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
|
@ -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
|
@ -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
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -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
|
BIN
year2/semester2/CT2109/Assignments/Assignment-05/code/mytree.bin
Normal 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}
|
@ -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
|
||||
|
||||
%----------------------------------------------------------------------------------------
|
After Width: | Height: | Size: 45 KiB |
After Width: | Height: | Size: 22 KiB |
After Width: | Height: | Size: 36 KiB |
After Width: | Height: | Size: 24 KiB |
After Width: | Height: | Size: 23 KiB |
After Width: | Height: | Size: 39 KiB |
@ -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}
|
||||
% ===============================================
|
@ -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}
|
After Width: | Height: | Size: 66 KiB |
@ -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]{...}
|