Add second year

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

Binary file not shown.

After

Width:  |  Height:  |  Size: 50 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 86 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 43 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 74 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 79 KiB

View File

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

View File

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

Binary file not shown.

After

Width:  |  Height:  |  Size: 66 KiB

View File

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