\documentclass[12pt]{article}
    \usepackage{mathtools}
    \usepackage[hidelinks]{hyperref}
    \usepackage{color}
    \usepackage{fancyref}
    \usepackage{lastpage}
    \usepackage{fancyhdr}

    \usepackage{pagecolor}
    % \pagecolor{black}
    % \color{white}

    \pagestyle{fancy}
    \fancyhf{}
    \fancyhead[LO]{TMA4140: Homework set 7}
    \fancyhead[RO]{Henry S. Sjøen \& Toralf Tokheim}
    \fancyfoot[CO]{\thepage\ of \pageref{LastPage}}

    \definecolor{darkred}{RGB}{200, 0, 0}

  \author{Henry S. Sjøen \& Toralf Tokheim}
  \title{
  \textbf{TMA4140 - Homework Exercise Set 7}}
\begin{document}
    \maketitle
    \thispagestyle{empty}
    \pagebreak
    \tableofcontents
    \pagebreak

    \section{Section 8.1}
    % Obligatoriske: 11, 20;
    % Anbefalte: 19, 21.
    \subsection{Exercise 11}
    \textbf{a) Find a recurrence relation for the number of ways to climb n stairs if the person climbing the stairs can take one stair or two stairs at a time.}\\
    $ a_n=a_{n-1}+a_{n-2} $ when $n > 2$\\
    \textbf{b) What are the initial conditions?}\\
    % Only one way to reach "The zero-step", is not to move, witch also is a move. $a_0 = 1$\\
    To reach the first step there is only one solution, taking one single step $a_1=1$\\
    To reach the second step, we can take either two single steps or one double step. $a_2=2$\\
    \textbf{c) In how many ways can this person climb a flight of eight stairs?}\\
    A lot...
    \begin{equation}
        \begin{split}
            % 8 enere
            % 0 toer
            1+1+1+1+1+1+1+1=8\\
            % 6 enere
            % 1 toer
            % Gir oss 7 bokser
            % og også 7 permutasjoner
            2+1+1+1+1+1+1=8\\
            1+2+1+1+1+1+1=8\\
            1+1+2+1+1+1+1=8\\
            1+1+1+2+1+1+1=8\\
            1+1+1+1+2+1+1=8\\
            1+1+1+1+1+2+1=8\\
            1+1+1+1+1+1+2=8\\
            % 4 enere
            % 2 toere
            % Gir oss 6 bokser
            2+2+1+1+1+1=8\\
            2+1+2+1+1+1=8\\
            2+1+1+2+1+1=8\\
            2+1+1+1+2+1=8\\
            2+1+1+1+1+2=8\\
            %
            1+2+2+1+1+1=8\\
            1+2+1+2+1+1=8\\
            1+2+1+1+2+1=8\\
            1+2+1+1+1+2=8\\
            %
            %
            1+1+2+2+1+1=8\\
            1+1+2+1+2+1=8\\
            1+1+2+1+1+2=8\\
            %
            1+1+1+2+2+1=8\\
            1+1+1+2+1+2=8\\
            %
            1+1+1+1+2+2=8\\
            %
            % 2 enere
            % 3 toere
            2+2+2+1+1=8\\
            2+2+1+2+1=8\\
            2+2+1+1+2=8\\
            2+1+2+1+2=8\\
            2+1+1+2+2=8\\
            1+2+2+2+1=8\\
            1+2+2+1+2=8\\
            1+2+1+2+2=8\\
            1+1+2+2+2=8\\
            % 0 enere
            % 4 toere
            2+2+2+2=8\\
        \end{split}
    \end{equation}

    I missed one above, but easier to calculate it...
    $ a_n=a_{n-1}+a_{n-2} $ when $n > 2$\\

    \begin{equation}
        \begin{split}
            a_n&=a_{n-1}+a_{n-2} | n>2\\
            % a_0&=1,
            a_1&=1,a_2=2\\
            % a_2&=a_{2-1}+a_{2-2}=a_{1}+a_{0}=1+1=2\\
            a_3&=a_{3-1}+a_{3-2}=a_{2}+a_{1}=2+1=3\\
            a_4&=a_{4-1}+a_{4-2}=a_{3}+a_{2}=3+2=5\\
            a_5&=a_{5-1}+a_{5-2}=a_{4}+a_{3}=5+3=8\\
            a_6&=a_{6-1}+a_{6-2}=a_{5}+a_{4}=8+5=13\\
            a_7&=a_{7-1}+a_{7-2}=a_{6}+a_{5}=13+8=21\\
            a_8&=a_{8-1}+a_{8-2}=a_{7}+a_{6}=21+13=34
        \end{split}
    \end{equation}

    There are 34 possible ways to climb the flight of $8$ stairs using only $1$ or $2$ steps at a time.

    \subsection{Exercise 20}
    % https://www.chegg.com/homework-help/bus-driver-pays-tolls-using-nickels-dimes-throwing-one-coin-chapter-8.1-problem-20e-solution-9780073383095-exc
    A bus driver pays all tolls, using only nickels and dimes, by throwing one coin at a time into the mechanical toll collector.\\
    \textbf{a)} Find a recurrence relation for the number of different ways the bus driver can pay a toll of n cents (where the order in which the coins are used matters).\\
    1 Nickel =  5 cents, 1 Dime = 10 cents.\\
    Let $a_n$ be the number of ways the busdriver can pay a toll of $n$ cents.\\
    If last coin Nickel $a_{n-5}$, If last coin Dime $a_{n-10}$\\
    Then the recurrence relation can be given as...
    $a_n=a_{n-5}+a_{n-10} | n \geq 10$
    And since nickels and dimes are of multiple of 5 we can further write it as ...
    $a_{5n}=a_{5(n-1)} + a_{5(n-2)} | n \geq 2$.
    Where the initial conditions are $a_0=1; a_5=1;$
    \textbf{b)} In how many different ways can the driver pay a toll of 45 cents?
    We must calculate $a_{45}$
    \begin{equation}
        \begin{split}
            a_{5n}&=a_{5(n-1)} + a_{5(n-2)}\\
            a_0&=1; a_5=1\\
            a_{10}&=2\\
            a_{15}&=3\\
            a_{20}&=5\\
            a_{25}&=8\\
            a_{30}&=13\\
            a_{35}&=21\\
            a_{40}&=34\\
            a_{45}&=55
        \end{split}
    \end{equation}

    \section{Section 8.2}
    % Obligatoriske: 3c,d,e,g, 6, 11, 42;
    % Anbefalte: 40.

    \subsection{Exercise 3} %todo
    % https://www.chegg.com/homework-help/bus-driver-pays-tolls-using-nickels-dimes-throwing-one-coin-chapter-8.2-problem-3E-solution-9780073383095-exc
    Solve these recurrence relations together with the initial conditions given.\\
    \textbf{c)} $ a_n=5a_{n-1} - 6a_{n-2} $ for $ n \geq 2, a_0=1, a_1=0 $\\
    Comparing the given recurrence with the general relation we get $C_1=5,c_2=-6$ and rest of the coefficients are $0$.
    Our characteristic equation will be $r^2=5r^1-6r^0$, so...
    \begin{equation}
        \begin{split}
            r^2-5r^1+6r^0=0\\
            r^2-5r+6r=0\\
            r^2-3r-2r+6=0\\
            (r-3)(r-2)=0
        \end{split}
    \end{equation}
    That is, $r=3,2$.
    Solution will be of the form $a_n=a_1r_2^n$. Setting in the value of $r$ and use the initial condition.
    $n=0,1$...\\
    \begin{equation}
        \begin{split}
            a_n=a_1r_1^n\\
            a_n=a_1(2)^n+a_2(3)^n
        \end{split}
    \end{equation}
    When $n=0$, then...
    \begin{equation}
        \begin{split}
            a_0=a_1(2)^0+a_2(3)^0\\
            1=a_1+a_2\\
            a_1=1-a_2
        \end{split}
    \end{equation}
    When $n=1$, then...
    \begin{equation}
        \begin{split}
            a_1=a_1(2)^1+a_2(3)^1\\
            0=2a_1+3a_2
        \end{split}
    \end{equation}
    Put the value of $a_1=1-a_2$ in the equation $2a_1+3a_2=0$...
    \begin{equation}
        \begin{split}
            2(1-a_2)+3a_2=0\\
            2-2a_2+3a_2=0\\
            a_2=-2
        \end{split}
    \end{equation}
    Put the value of $a_2=-2$ in the equation $a_1=1-a_2$ and we get $a_1=3$.
    Put the value of $a_1,a_2$ in the equation $a_n=a_1r_1^n+a_2r_2^n$ to get the final solution $a_n=3 \times (2)^n-2 \times (3)^n$.

    \textbf{d)} $ a_n=4a_{n-1} - 4a_{n-2} $ for $ n \geq 2, a_0=6, a_1=8 $\\
    Comparing the given recurrence relation with the general relation we get $c_1=4$ $c_2=-4$ and the rest of the coefficients are 0.
    The corresponding characteristic equation will be $r^2=4r^1-4r^0$. So,
    \begin{equation}
        \begin{split}
            r^2-4r+4=0\\
            r^2-2r-2r+4=0\\
            (r-2)(r-2)=0
        \end{split}
    \end{equation}
    Since we have a repeated root, the solution will be of the form $a_n=a_1r_1^n+a_2nr_2^n$.
    Putting the value of $r$ and useing the initial conditions $n=0,1$ and get...
    \begin{equation}
        \begin{split}
            a_n=a_1r_1^n+a_2nr_2^n\\
            a_n=a_1(2)^n+a_2n(2)^n
        \end{split}
    \end{equation}
    when $n=0$...
    \begin{equation}
        \begin{split}
            a_0=a_1(2)^0+a_20(2)^0\\
            6=a_1
        \end{split}
    \end{equation}
When $n=1$...

\begin{equation}
    \begin{split}
        a_1=a_1(2)^1+a_21(2)^1\\
        8=2a_1+2a_2
    \end{split}
\end{equation}
Put the value of $a_1=6$ in the equation $8=2a_1+2a_2$ to get...
\begin{equation}
    \begin{split}
        2a_1+2a_2=8\\
        12+2a_2=8\\
        2a_2=8-12\\
        a_2=-2
    \end{split}
\end{equation}
Put the value of $a_1,a_2$ in the equation $a_n=a_1r_1^n+a_2nr_2^n$ to get the desired solution.
Thus, the solution is $a_n=6\cdot (2)^n-2\cdot n \cdot (2)^n$.
    \textbf{e)} $ a_n=-4a_{n-1} - 4a_{n-2} $ for $ n \geq 2, a_0=0, a_1=1 $\\
    \textbf{g)} $ a_n=\frac{a_{n-2}}{4} $ for $ n \geq 2, a_0=1, a_1=0 $
    \subsection{Exercise 6} %todo
    % https://www.chegg.com/homework-help/bus-driver-pays-tolls-using-nickels-dimes-throwing-one-coin-chapter-8.2-problem-6E-solution-9780073383095-exc
    How many different messages can be transmitted in $n$ microseconds using three different signals if one signal requires $1$ microsecond for transmittal, the other two signals require $2$ microseconds each for transmittal, and a signal in a message is followed immediately by the next signal?

    \subsection{Exercise 11}
    % https://www.chegg.com/homework-help/bus-driver-pays-tolls-using-nickels-dimes-throwing-one-coin-chapter-8.2-problem-11E-solution-9780073383095-exc
    The Lucas numbers satisfy the recurrence relation
    \begin{equation}
        L_n=L_{n-1}+L_{n-2}
    \end{equation}
    and the initial conditions $L_0 = 2$ and $L_1=1$.

    \textbf{a)} Show that $L_n = f_{N-1}+f_{n+1}$ for $n=2,3,...,$ where $f_n$ is the $n$th Fibonacci number.\\
    \textbf{b)} Find an explicit formula for the Lucas numbers.
Answer:
     $Ln = ((1+sqr(5))/2)+((1-sqr(5))/(2))$

    \subsection{Exercise 42} %todo
    % https://www.chegg.com/homework-help/bus-driver-pays-tolls-using-nickels-dimes-throwing-one-coin-chapter-8.2-problem-42E-solution-9780073383095-exc
    Show that if $a_n =a_{n-1} + a_{n-2}, a_0=s$ and $a1 =t$, where $s$ and $t$ are constants, then $a_n = sf_{n-1} + tf_n$ for all positive integers $n$.

    \section{Section 5.1}
    % Obligatoriske: 4, 6, 14, (4, 6, 14);
    % Anbefalte: 9, 10.

    \subsection{Exercise 4}
    % https://www.chegg.com/homework-help/bus-driver-pays-tolls-using-nickels-dimes-throwing-one-coin-chapter-5.1-problem-4E-solution-9780073383095-exc
    Let $P(n)$ be the statement that $1^3 + 2^3 + \cdots + n^3 = (n(n + 1)/2)^2$ for the positive integer $n$.\\
%     \textbf{a) What is the statement $P(1)$?}\\
%     \textbf{b) Show that $P(1)$ is $true$, completing the basis step of the proof.}\\
%     \textbf{c) What is the inductive hypothesis?}\\
%     \textbf{d) What do you need to prove in the inductive step?}\\
%    \textbf{ e) Complete the inductive step, identifying where you use the inductive hypothesis.}\\
%     \textbf{f) Explain why these steps show that this formula is $true$ whenever $n$ is a positive integer.}
    %
    % \begin{enumerate}[label=\alph*)]

        $P(1): 1^3 = (\frac{1(1+1)}{2})^2$
        Basis step:
            $P(1): 1^3 = (\frac{1(1+1)}{2})^2 = 1$ \\
            $P(1)$ is true, which completes the basis step of a proof by
                induction for $P(k)$

        The inductive hypothesis consists of two parts: \\
            - $P(b)$ holds true \\
            - $P(k) \rightarrow P(k+1)$ holds true\\
            Then $P(k), \quad \forall k > b$

            In other words, if $P$ is true for the first step, and $P$ holds true for an arbitrary step implies $P$ holds true for the next step, then $P$ holds true for all steps. \\

        You need to prove the first step $P(b)$, and then you need to prove
            $P(k) \rightarrow P(k+1)$

                    \begin{align}
                        \intertext{Basis step:}
                        1^3 = (1(1+1)/2)^2 = 1 \\
                        \intertext{LHS = RHS}
                        \intertext{Inductive step:}
                        \sum_{n=1}^k{n^3} = \Big(\frac{k(k+1)}{2}\Big)^2 \\ %\label{eq:4e_k}
                        \intertext{We assume $P(k)$ is true for an arbitrary integer $k$. We can replace $k$ with $k+1$. Out goal is to show that if $P(k)$ holds then $P(k+1)$ must hold}
                        \sum_{n=1}^{k+1}{n^3} = \Big(\frac{(k+1)((k+1)+1)}{2}\Big)^2 \\
                        \sum_{n=1}^{k}{n^3} + (k+1)^3 = \Big(\frac{(k+1)(k+2)}{2}\Big)^2 \\
                        = \Big(\frac{(k^2+3k+2)}{2}\Big)^2 \\
                        = \Big(\frac{(k(k+1))}{2} + (k+1)\Big)^2 \\
                        \sum_{n=1}^{k}{n^3} + (k+1)^3 = \Big(\frac{(k(k+1))}{2}\Big)^2 + k(k+1)(k+1) + (k+1)^2 \\
                        \intertext{We subtract  $\sum_{n=1}^k{n^3} = \Big(\frac{k(k+1)}{2}\Big)^2$ from the equation and have}
                        (k+1)^3 = k(k+1)^2 + (k+1)^2 \\
                        (k+1)^3 = (k+1)(k+1)^2 = (k+1)^3 \\
                        \intertext{LHS = RHS. This means that if $P(k)$ holds true,
                        then $P(k+1)$ must also be true, which by the inductive
                        hypothesis means that $\forall k \geq 1, \quad P(k)$ holds true}
                    \end{align}

    \subsection{Exercise 6}
    % https://www.chegg.com/homework-help/bus-driver-pays-tolls-using-nickels-dimes-throwing-one-coin-chapter-5.1-problem-6E-solution-9780073383095-exc
    Prove that $s1 \cdot 1!+2 \cdot 2! + \cdots + n \cdot n! = (n+1)!-1$ whenever $n$ is a positive integer.
    \begin{align}
        \intertext{Basis step:}
        1\cdot 1\! = (1 + 1)! - 1 \\
        1 = (2)! - 1 = 2 - 1 = 1\\
        \intertext{LHS = RHS, so $P(1)$ holds true}
        \intertext{Inductive step:}
        \sum_{n = 1}^k{n\cdot n!} = (k + 1)! - 1 \\ %\label{eq:1-6-k}
        \intertext{We assume that $P(k)$ holds for all $k > 1$, and replace
            $k$ with $k+1$}
        \sum_{n = 1}^{k+1}{n\cdot n!} = ((k+1) + 1)! - 1 \\
        (k+1)\cdot(k+1)! + \sum_{n = 1}^{k}{n\cdot n!}  = (k+2)! - 1 \\
        (k+1)\cdot(k+1)! + \sum_{n = 1}^{k}{n\cdot n!}  = (k+2)(k+1)! - 1 \\
        \intertext{We subtract $\sum_{n = 1}^k{n\cdot n!} = (k + 1)! - 1$ from the equation and get}
        (k+1)\cdot(k+1)! +  = (k+2)(k+1)! - 1 - \big( (k+1)! - 1\big)\\
        (k+1)\cdot(k+1)! +  = (k+2)(k+1)!  -  (k+1)! \\
        (k+1)\cdot(k+1)! +  = k(k+1)! + 2(k+1)! - (k+1)! \\
        (k+1)\cdot(k+1)! +  = k(k+1)! + (k+1)!  \\
        (k+1)\cdot(k+1)! +  = (k+1)\cdot(k+1)!  \\
        \intertext{LHS = RHS, so $P(k)$ must hold for all $k > 1$}
    \end{align}

    \subsection{Exercise 14}
    % https://www.chegg.com/homework-help/bus-driver-pays-tolls-using-nickels-dimes-throwing-one-coin-chapter-5.1-problem-14E-solution-9780073383095-exc
    Prove that for every positive integer $n$, $\sum_{k=1}^{n}k2^k=(n-1)2^{n+1}+2$.
            \begin{align}
                \intertext{$P(k)$:}
                \sum_{n=1}^k{ n2^n} = (k-1)2^{k+1} + 2 %\label{eq:1-14-k}\
                \intertext{Basis step:}
                1\cdot 2^1 = (1-1)2^2{1+1} + 2 = 2\
                \intertext{LHS = RHS, so $P(1)$ holds true}
                \intertext{Induction step:}
                \intertext{Replacing $n$ with $k+1$ in $\sum_{n=1}^k{ n2^n} = (k-1)2^{k+1} + 2$ gives us}
                \sum_{n=1}^{k+1}{ n2^n} = ((k+1)-1)2^{(k+1)+1} + 2 \\
                (k+1)2^{k+1} + \sum_{n=1}^{k}{ n2^n} = k2^{k+2} + 2 \\
                (k+1)2^{k+1} + \sum_{n=1}^{k}{ n2^n} = 2k2^{k+1} + 2 \\
                \intertext{We subtract $\sum_{n=1}^k{ n2^n} = (k-1)2^{k+1} + 2$ from the equation and get}
                (k+1)2^{k+1} = 2k2^{k+1} + 2 - \big((k-1)2^{k+1} + 2\big) \\
                (k+1)2^{k+1} = 2k2^{k+1} - (k-1)2^{k+1} \\
                (k+1)2^{k+1} = (2k - (k-1)) 2^{k+1}\\
                (k+1)2^{k+1} = (k+1)2^{k+1}\\
                \intertext{LHS = RHS, so $P(k)$ must hold for all $k > 1$}
            \end{align}
\end{document}


% !TeX encoding = UTF-8
% !TeX program = pdflatex

\documentclass[11pt]{article}
\usepackage[english]{babel}
\usepackage{graphicx}
\usepackage{listings}
\usepackage[dvipsnames]{xcolor}
\usepackage{lineno}
\lstloadlanguages{Python}
\lstset{%
	basicstyle=\fontsize{10}{11}\ttfamily\color{black},
	commentstyle=\ttfamily\color{red},
	keywordstyle=\ttfamily\color{blue},
	stringstyle=\color{orange},
	tabsize=2,
	numbers=left,
	numberstyle=\tiny,
	firstnumber=1,
	numberfirstline=false,
	frame=single,
	showstringspaces=false,
	inputencoding=utf8,
	breaklines=true
}
\usepackage{amsmath}
\usepackage{algorithm}
\usepackage[noend]{algpseudocode}
\makeatletter
\def\BState{\State\hskip-\ALG@thistlm}
\makeatother

\title{Homework 1 - Algorithm Design \\ \bigskip \large Sapienza University of Rome}
\date{\today}
\author{Marco Costa 1691388}

\begin{document}
\maketitle

\section{Exercise 1}
The goal of this exercise is to cluster the points of \textbf{X} using the first \textit{\textbf{k}} points \textbf{C = $\mathbf{\{ \pi(X)_{1},...,\pi(X)_{k} \}}$} as center (where $\mathit{\pi(X)}$ is a permutation). For any \textit{\textbf{k}}, the output should be optimal with respect of the objective function $\mathbf{\displaystyle\max_{x \in X} \min_{c \in C} d(x,c)}$. \\
This problem is known as k-center clustering problem, and it's NP-HARD. \\
Fortunately, it is possible to find an approximation using a greedy algorithm. \\
The greedy clustering algorithm simply chooses the point farthest away from the current set of centers in each iteration as the new center. It can be described in this way:
\begin{itemize}
	\item Pick an arbitrary point $\mathbf{c_{i}}$ into $\mathbf{C}$;
	\item For every point $\mathbf{x \in X}$ compute $\mathbf{d_{i}(x,c_{i})}$;
	\item Pick the point $\mathbf{c_{i}}$ with the highest distance from $\mathbf{c_{i-1}}$ ($\displaystyle\max_{x \in X} d(x, c_{i})$).
	In this case, distance must be 3. If there are no points that have the distance 3, then the distance must be 1;
	\item Add it to the set of centers $\mathbf{C}$;
	\item Continue till \textit{\textbf{k}} centers are found (\textit{i=1,...,k}).
\end{itemize}

\subsection{Analysis of the algorithm}
\begin{itemize}
	\item The $i^{th}$ iteration of choosing the $i^{th}$ center takes $\mathbf{O(|X|)}$ time.
	\item There are  \textit{\textbf{k }} iterations, so overall the algorithm takes $\mathbf{O(k|X|)}$ time.
\end{itemize}

\subsection{Proof}
The correctness of this algorithm can be proved by contradiction.\\
Assume that $\mathbf{O^{*} = \{c^{∗}_{1},...,c^{∗}_{k}\}}$ is an optimal solution for the problem and $\mathbf{S = \{c_{1},...,c_{k}\}}$ the solution given by the greedy algorithm. If $\mathbf{S \ne O^{*}}$ so there is at
least an optimum center $\mathbf{\bar{c}}$
which belongs to $\mathbf{O^{*}}$ but not to $\mathbf{S}$. This means that, if this point was selected at the $\mathbf{(i-1)^{th}}$ iteration of the optimum
algorithm because it has distance 3 from the center, so the greedy algorithm has
not selected it as the optimum value to satisfy the objective function. But
this is not possible, it first insert into the partition all
the points of the space which have distance equals to 3 from the center
and after the points with distance equals to 1 if needed.

\subsection{2-approximation}
The solution obtained using the greedy algorithm (the set $\mathbf{C}$) is a 2-approximation to the optimal solution ($\mathbf{r^{C}_{\infty}(X) \le 2r^{opt}_{\infty}}(X,k)$).

\subsubsection{Proof}
Case 1: Every cluster of $\mathbf{C_{opt}}$ contains exactly one point of $\mathbf{C}$.
\begin{itemize}
	\item Consider a point $\mathbf{x \in X}$;
	\item Let $\mathbf{\bar{c}}$ be the center it belongs to in $\mathbf{C_{opt}}$;
	\item Let $\mathbf{\bar{k}}$ be the center of $\mathbf{C}$ that is in $\mathbf{\Pi(C_{opt},\bar{c})}$;
	\item $\mathbf{d(x,\bar{c}) = d(x,C_{opt}) \le r^{opt}_{\infty}(X,k)}$;
	\item Similarly, $\mathbf{d(\bar{k},\bar{c}) = d(\bar{k},C_{opt}) \le r^{opt}_{\infty}(X,k)}$;
	\item By the triangle inequality: $\mathbf{d(x,\bar{k}) \le d(x,\bar{c}) + d(\bar{c},\bar{k}) \le 2r^{opt}_{\infty}(X,k)}$	.
\end{itemize}

Case 2: There are two centers $\mathbf{\bar{k}}$ and $\mathbf{\bar{u}}$ of $\mathbf{C}$ that is in $\mathbf{\Pi(C_{opt},\bar{c})}$, for some $\mathbf{\bar{c} \in C_{opt}}$
\begin{itemize}
	\item Assume, without loss of generality, that $\mathbf{\bar{u}}$ was added later to the center set $\mathbf{C}$ by the greedy algorithm in the $\mathbf{i^{th}}$ iteration;
	\item But since the greedy algorithm always chooses the point furthest away from the current set of centers, we have that $\mathbf{\bar{c} \in C_{i-1}}$, and \\ $\mathbf{r^{C}_{\infty}(X) \le r^{C_{i-1}}_{\infty}(X) = d(\bar{u},C_{i-1}) \le d(\bar{u},\bar{k}) \le d(\bar{u},\bar{c}) + d(\bar{c},\bar{k}) \le 2r^{opt}_{\infty}(X,k)}$.
\end{itemize}

\section{Exercise 2}
It's possible to solve this problem using a bipartite graph \textbf{G(S,A,C)}, where \textbf{S} is the set containing streets, \textbf{A} is the set containing avenues and \textbf{C} is the set containing checkpoints (so a checkpoint is an edge that connects a street in \textbf{S} with an avenue in \textbf{A}).
The goal is to find a vertex set $\mathbf{T \subseteq S \bigcup A}$ of minimum size.
So the problem is a minimum vertex cover problem
(because we want to find a set of vertices such that every edge of the graph
has at least one endpoint in the set). It's possible to find \textbf{T} with:
\begin{itemize}
	\item Ford-Fulkerson’s algorithm to find the maximum matching;
	\item Konig's theorem, which states that in any bipartite graph, the number of edges in a maximum matching is equal to the number of vertices in a minimum vertex cover.
\end{itemize}
Let’s consider \textbf{M}, a maximum cardinality matching in \textbf{G}. A matching is an edge set $\mathbf{M \subseteq E}$ such that no two edges of M have the same endpoint. Konig's theorem proves that the size of a
maximum matching M is equal to the size of the minimum cardinality vertex cover \textbf{T}. \\
It's possible to find the maximum matching set \textbf{M} applying Ford-Fulkerson algorithm in the bipartite flow network \textbf{G(S,A,C)}.
\\
Now it's possible to derive from the maximum alternating forest, built starting
from non matched vertices in \textbf{S}, the minimum vertex cover set \textbf{T} using Konig's theorem.\\
This set represent the minimum
set of streets and avenues in which it's necessary to place cameras for covering checkpoints.

\subsection{Analysis}
The cost of this algorithm is dominated by the finding of the maximum
flow (the cost of Ford-Fulkerson’s algorithm). So the total cost is \textbf{O(\textit{f}$|C|$)}, where \textit{\textbf{f}} is the maximum flow found and \textbf{C} is the set of the checkpoints.

\section{Exercise 3}
It's possible to solve this problem considering a complete graph \textbf{G(P,R)} where $\mathbf{P = M \bigcup F}$ is the set of friends (\textbf{M} is the set of male friends and \textbf{F} is the set of female friends) and R is the set of their relations (the edges of the graph). \\
Each  edge
has weight equals to 0 if the two friends don’t like each other, 1 otherwise. \\
The goal is to find a subset I of people who
like each other and who are equally bipartite (so equal number of male and
female friends). \\
The first point of the problem can be solved considering it as a k-clique problem. The algorithm proceed in this way:
\begin{enumerate}
	\item For each $\mathbf{\textbf{\textit{k}} \in \{2,|V|\}}$ it computes the k-clique and stores the cliques with \textbf{\textit{k}} edges in a set \textbf{S};
	\item For each clique in \textbf{S} it computes the maximum bipartite matching in order to satisfy the second point (equal number of male and female);
	\item For each value of \textbf{\textit{k}} it finds the maximum bipartite matching $\mathbf{M_{k}}$ which maximizes the value \\
	$\mathbf{maxVal_{k} = \frac{1}{|M_{k}}} \sum_{(u,v) \in M_{k}}weight(u,v)$;
	\item At the end it finds the maximum value between the various $\mathbf{maxVal_{k}}$ with $\mathbf{\textbf{\textit{k}} \in \{2,|V|\}}$ and returns the maximum matching corresponding to this value.
\end{enumerate}

\subsubsection{Implementation (pseudocode)}
\begin{algorithm}
	\label{euclid}
	\begin{algorithmic}[1]
		\State $V \gets vertices$
		\State $E \gets edges$
		\State $G \gets graph$
		\State $maxD[|V|] \gets [0]$
		\State $maxI[k] \gets$ [ ]
		\For{$k \gets$ 0 to $|V|$}
		\State $S \gets$ find-all k-cliques()
		\For{s in S}
		\State I $\gets$ bipartite matching of s
		\If{sum weight(s)/$|I| >$ maxD[k]}
		\State $maxD[k] \gets weight(s)/|I|$
		\State $maxI[k] \gets I$
		\EndIf
		\EndFor
		\EndFor
		\State $index \gets max(maxD)$
		\State\Return maxI[index]
	\end{algorithmic}
\end{algorithm}

\subsection{Proof}
This algorithm uses the k-clique problem, which is NP-COMPLETE, in fact, the reduction of this problem is polynomial. For this reason the implemented algorithm is NP-COMPLETE too.

\section{Exercise 4}
The input of the algorithm is the following:
\begin{itemize}
	\item costs: a list of tuple where the first element is the timestamp of the task, the second one is the cost of outsourcing;
	\item C: hiring cost;
	\item S: severance cost;
	\item s: daily salary.
\end{itemize}
For first, the algorithm computes how many tasks with different timestamp there are. In this way it's possible to overlap tasks.
After that, it joins the overlapping tasks generating a matrix in which there are the timestamps in the first row and the outsourcing costs in the second one.
Then it generates a total cost matrix and initializes the first column, calculates the lowest cost for each instant using the costs of the previous instant and at the end returns the minimum total cost.

\subsection{Analysis}
The cost of the algorithm depends on iterative loops so it is linear: O(T), where T is the last
time unit to consider. \\

\subsection{Proof}
To prove the correctness of the algorithm we could use proof by induction.
We consider as basis step the first two couple of values inside total cost matrix , at this moment i = 0
and the min of them is the min cost so far. As induction hypothesis we suppose that for i = k the
cost computed as min of the couple of values inside total cost matrix is optimal. The inductive step is to
prove that also for i = k + 1 the cost is optimal.

\subsection{Implementation}
The algorithm is implemented in \textit{\textbf{Python}}.
\begin{lstlisting}[language=Python, caption=minCost]
def minCost(costs, C, S, s):

	# Determine the number of different tasks
	T = 0
	time = 0
	for cost in costs:
		if cost[0] != time:
			time = cost[0]
			T += 1

	# Initialize outsourcing cost matrix
	outsource = [[0 for x in range(0, T+1)] for x in range(0, 2)]

	# Initialize total cost matrix
	tc = [[0 for x in range(0, T+1)] for x in range(0, 2)]

	# Construck outsourcing cost matrix joining different tasks with the same timestamp
	time = 0
	i = 0
	j = 0
	for cost in costs:
		if j == 0:
			outsource[0][i] = cost[0]
			outsource[1][i] = cost[1]
			time = cost[0]
			j += 1
		else:
			if time == cost[0]:
				outsource[1][i] += cost[1]
			else:
				i += 1
				outsource[0][i] = cost[0]
				outsource[1][i] = cost[1]
				time = cost[0]

	# Initialize first column of total cost matrix
	tc[0][0] = s + C
	tc[1][0] = outsource[1][0]

	# Construct rest of the total cost matrix
	for i in range(1, T):
		tc[0][i] = min(tc[0][i-1] + (outsource[0][i] - outsource[0][i-1]) * s, tc[1][i-1] + C + s)
		tc[1][i] = min(tc[0][i-1] + S + outsource[1][i], tc[1][i-1] + outsource[1][i])

	# Return the minimum cost
	return min(tc[0][T-1], tc[1][T-1])
\end{lstlisting}

\section{Exercise 5}
\subsection{First part}
The first part of the exercise can be solved using the Minimum Spanning Tree cycle property: \\
\textit{For any cycle \textbf{C} in the graph,
if the weight of an edge \textbf{e} of \textbf{C} is larger than the weights of all other
edges of \textbf{C}, then e cannot belong to the MST}.
\\
The algorithm is based on a \textbf{DFS}. It determine if the
two endpoints of \textit{\textbf{e}} are connected with a cycle respecting the property
mentioned before. \\
How it works:
\begin{enumerate}
	\item Run the DFS from one of the end-points of the
input edge \textit{\textbf{e}} (\textbf{u} or \textbf{v} for the edge \textit{\textbf{(u, v, weight)}}) considering only outgoing edges which
have weight less than the one of \textit{\textbf{e}};
	\item \begin{itemize}
		\item Case 1: If at the end of the \textbf{DFS}, the two vertices \textbf{u} and \textbf{v}
get connected, then the edge \textit{\textbf{e}} can't be part of any \textbf{MST}
because of the cycle property, in fact in this case there exists
a cycle in the graph \textbf{G} containing the edge \textit{\textbf{e}} where \textit{\textbf{e}} is the
edge with maximum weight.
		\item Case 2: If at the end of the \textbf{DFS} \textbf{u} and
\textbf{v} stay disconnected, then there is not a cycle between \textbf{u} and
\textbf{v} where \textit{\textbf{e}} is the edge with maximum weight, so the edge
considered can be part of the \textbf{MST}.
	\end{itemize}
\end{enumerate}
The cost of this algorithm is dominated from the one of the \textbf{DFS}, which
is \textbf{O($|V| + |E|$)}.

\subsection{Second part}
For this second part, the algorithm described before was used to check if
the given edge \textit{\textbf{e}} could be part of a Minimum Spanning Tree. After
checking the previous condition, Kruskal’s algorithm was used to compute
the \textbf{MST} containing \textit{\textbf{e}}: the cost of this algorithm is
\textbf{O($|E|log|E|$)}.

\subsubsection{Implementation}
The algorithm is implemented in \textit{\textbf{Python}}.
\begin{lstlisting}[language=Python, caption=MST given an edge]
def give_a_mst(self, edge):
	if self.edge_in_mst(edge):
		print("The edge",str(edge),"belongs to MST!")
		print("Minimum Spanning Tree:", end="")
		return self.kruskal()
	else:
		print("The edge",str(edge),"doesn't belong to MST!")
		return None
\end{lstlisting}
This algorithm is very symple: \\
It checks if the edge is contained in the MST using the algorithm described in the first part.\\
If the result is positive, then the Kruskal's algorithm is executed and the MST is output, otherwise nothing is returned.

\begin{lstlisting}[language=Python, caption=Kruskal's algorithm]
def kruskal(self):
	parent = dict()
	rank = dict()

	for vertex in self.vertex:
		parent[vertex] = vertex
		rank[vertex] = 0

	def find(vertex):
		if parent[vertex] != vertex:
			parent[vertex] = find(parent[vertex])
		return parent[vertex]

	def union(vertex1, vertex2):
		root1 = find(vertex1)
		root2 = find(vertex2)
		if rank[root1] < rank[root2]:
			parent[root1] = root2
		elif rank[root1] > rank[root2]:
			parent[root2] = root1
		else:
			parent[root2] = root1
			rank[root2] += 1

	mst = Graph("directed")
	minimum_spanning_tree = set()
	edges = self.sorted_by_weight()
	for edge in edges:
		v1, v2, w = edge
		if find(v1) != find(v2):
			union(v1, v2)
			minimum_spanning_tree.add(edge)
	for node in self.get_nodes():
		mst.add_node(node)
	for edge in minimum_spanning_tree:
		mst.add_edge(edge)
	return mst
\end{lstlisting}

\appendix
\section{Code}
The whole implementation of the exercises are attached in the archive \\ \textit{HW1-AD\_Marco\_Costa\_1691388.tar.gz}

\end{document}


\documentclass[12pt]{article}
\author{David Alves}

\usepackage{amsfonts}
\usepackage{amsmath}
\usepackage{amsthm}
\usepackage{dirtytalk}
\usepackage[a4paper]{geometry}
\usepackage{forest}
\usepackage{listings}
\usepackage{mathtools}
\usepackage{multicol}
\usepackage{nth}
\usepackage{relsize}
\usepackage{skak}
\usepackage{tikz}
\usepackage{tikz-qtree}
\usepackage{titling}
\usepackage{wrapfig}
\usepackage{xcolor}

\usetikzlibrary{decorations.pathreplacing}
\usetikzlibrary{patterns}

\DeclarePairedDelimiter\ceil{\lceil}{\rceil}
\DeclarePairedDelimiter\floor{\lfloor}{\rfloor}

\def\multichoose#1#2{\ensuremath{\left(\kern-.3em\left(\genfrac{}{}{0pt}{}{#1}{#2}\right)\kern-.3em\right)}}

\newcommand{\ts}[1]{\textsuperscript{#1}}

\newcommand{\ProblemStatement}[1]{
\subsection*{Problem Statement}
#1
\subsection*{Solution}
}

% If uncommented, next line hides problem statements
%\renewcommand{\ProblemStatement}[1]{}

\title{Math 142 Problem Set 11}
\author{David Alves}
\date{2016-11-10}

\begin{document}
\pagenumbering{gobble}

\begin{center}
\large \thetitle \\
\theauthor \\
\thedate
\end{center}

\subsection*{Sources}

    \begin{itemize}
    \item http://tex.stackexchange.com and https://www.sharelatex.com for help with \LaTeX
    \item Wikipedia for definition of Harmonic numbers
    \item Wolfram$\vert$Alpha for help with factoring polynomials
    \end{itemize}

\section{Strange Dice (Optional)}
\ProblemStatement{
How many ways are there to make two fair 6-sided dice with natural number values (fair in the sense that each face lands up with same probability, but the sides can have freedom of numbers, including duplication) such that rolling them gives the same probability distribution on the sum of the two dice as two normal fair 6-sided dice? (for example, if we have a die with sides (0, 1, 2, 3, 4, 5) and another with sides (2,3,4,5,6,7), we get the same distribution as two normal dice (why?) but this is not legal as I wanted natural numbers)
}

There are two ways: $(1,2,3,4,5,6)\times2$ and $(1,2,2,3,3,4), (1,3,4,5,6,8)$.
\begin{proof}
You can represent normal die using the generating function $x + x^2 + x^3 + x^4 + x^5 + x^6$, since there is one way to get each possible value in $[1,6]$. Rolling two normal dice is represented by squaring the generating function as follows:

\begin{multline*}
(x + x^2 + x^3 + x^4 + x^5 + x^6)^2 = \\x^2+2 x^3+3 x^4+4 x^5+5 x^6+6 x^7+5 x^8+4 x^9+3 x^{10}+2x^{11}+x^{12}
\end{multline*}

This question asks how many ways to factor this polynomial into two polynomials $A$ and $B$ such that:
\begin{enumerate}
    \item Every side has a natural number of dots, meaning that every term in both $A$ and $B$ is at least $x$.
    \item Each die has six sides, meaning that $A$ and $B$ both contain six terms.
\end{enumerate}

We first factor the polynomial:
\begin{align*}
    (x + x^2 + x^3 + x^4 + x^5 + x^6)^2 &= \left(x(1 + x + x^2 + x^3 + x^4 + x^5)\right)^2\\
    &= \left(x\frac{(x^6-1)}{x-1}\right)^2\\
    &= \left(x\frac{(x + 1)(x^2 - x + 1)(x-1)(x^2+x+1)}{x-1}\right)^2\\
    &= \left(x(x + 1)(x^2 - x + 1)(x^2+x+1)\right)^2\\
    &= x^2(x + 1)^2(x^2 - x + 1)^2(x^2+x+1)^2\\
\end{align*}

Since we know that every term in $A$ and $B$ is at least $x$, each of them needs to get one of the two $x$ factors. Trying each of the possible ways to distribute the remaining factors gives two valid arrangements:
\begin{multline*}
    A = B = x(x+1)(x^2 - x + 1)(x^2+x+1) = (1,2,3,4,5,6)\times 2 \text{ (Normal dice)}\\
    A = x(x+1)(x^2 - x + 1)^2(x^2+x+1), B = x(x+1)(x^2+x+1)\\
    = (1,2,2,3,3,4), (1,3,4,5,6,8) \text{ (Strange dice)}\\
\end{multline*}
\end{proof}

\section{Paths Through Trees}
\ProblemStatement{
Recall that a tree has many definitions. Suppose you're only allowed to use the definition that there are $n - 1$ edges on $n$ vertices with no cycles. Prove that you can go from any vertex to any other vertex via a path (i.e. the tree is not separated into 2 parts inaccessible from each other).
}

Let a \emph{connected component} be a set of vertices and edges such that you can get from any vertex in the component to any other vertex via some path which is a subset of that component's edges. Consider the edges of the graph in some arbitrary order. We will add the edges one at a time to the graph. Before any edges have been added, the graph consists of $n$ connected components each with one vertex. Now add the first edge to the graph, which connects two separate connected components (each with 1 vertex), leaving $n-1$ connected components. Each additional edge added to the graph connects two vertices in separate connected components, turning them into a single connected component. It must connect two vertices in different connected components because if the edge connected some $u,v$ inside the same connected component then there would be two paths from $u$ to $v$: One using the new edge and one through the other edges in that connected component, which contradicts our statement that there are no cycles. Thus each edge added to the graph reduces the number of connected components by one, so after adding all $n-1$ edges there is only one connected component, and thus you can get from any vertex to any other vertex via a path.

\section{Triangle Game (Optional)}
\ProblemStatement{
Describe (and prove) an optimal strategy of playing the triangle game we played in class for n = 5 vertices.
}

Below is a diagram showing a strategy for Player 1 that can force a win regardless of how Player 2 plays. Solid edges are Player 1 moves, while dashed edges are Player 2 moves. Only one graph per isomorphic group is shown.
\colorlet{lightred}{red!45}

\begin{center}
\begin{tikzpicture}
    \node[shape=circle,draw=black] (A1) at (4+0,24+1) {};
    \node[shape=circle,draw=black] (B1) at (4+.951,24+.309) {};
    \node[shape=circle,draw=black] (C1) at (4+.588,24-.809) {};
    \node[shape=circle,draw=black] (D1) at (4-.588,24-.809) {};
    \node[shape=circle,draw=black] (E1) at (4-.951,24+.309) {} ;
    \path [-,line width=1pt,color=blue] (A1) edge node[left] {} (B1) node[yshift=-6.5em,color=black] {Initial Move};

    \draw [->,line width=2.5,black!25] (2.5,22.5) -- (1.5,21.5);
    \node[shape=circle,draw=black] (A2) at (0+0,20+1) {};
    \node[shape=circle,draw=black] (B2) at (0+.951,20+.309) {};
    \node[shape=circle,draw=black] (C2) at (0+.588,20-.809) {};
    \node[shape=circle,draw=black] (D2) at (0-.588,20-.809) {};
    \node[shape=circle,draw=black] (E2) at (0-.951,20+.309) {} ;
    \path [-,line width=1pt] (A2) edge node[left] {} (B2) node[yshift=-6.5em] {\parbox{4.5cm}{Player 2's move shares a vertex with initial move}};
    \path [-,line width=1pt,style=dashed,color=blue] (A2) edge node[left] {} (C2);

    \draw [->,line width=2.5,black!25] (5.5,22.5) -- (6.5,21.5);
    \node[shape=circle,draw=black] (A3) at (8+0,20+1) {};
    \node[shape=circle,draw=black] (B3) at (8+.951,20+.309) {};
    \node[shape=circle,draw=black] (C3) at (8+.588,20-.809) {};
    \node[shape=circle,draw=black] (D3) at (8-.588,20-.809) {};
    \node[shape=circle,draw=black] (E3) at (8-.951,20+.309) {} ;
    \path [-,line width=1pt] (A3) edge node[left] {} (B3) node[yshift=-6.5em] {\parbox{5.5cm}{Player 2's move does not share a vertex with initial move}};
    \path [-,line width=1pt,style=dashed,color=blue] (D3) edge node[left] {} (C3);

    \draw [->,line width=2.5,black!25] (0,17.5) -- (0,16.5);
    \node[shape=circle,draw=black] (A4) at (0+0,15+1) {};
    \node[shape=circle,draw=black] (B4) at (0+.951,15+.309) {};
    \node[shape=circle,draw=black] (C4) at (0+.588,15-.809) {};
    \node[shape=circle,draw=black] (D4) at (0-.588,15-.809) {};
    \node[shape=circle,draw=black] (E4) at (0-.951,15+.309) {} ;
    \path [-,line width=1pt] (A4) edge node[left] {} (B4) node[yshift=-6.5em] {};
    \path [-,line width=1pt,style=dashed] (A4) edge node[left] {} (C4);
    \path [-,line width=1pt,color=blue] (A4) edge node[left] {} (E4);

    \draw [->,line width=2.5,black!25] (8,17.5) -- (8,16.5);
    \node[shape=circle,draw=black] (A5) at (8+0,15+1) {};
    \node[shape=circle,draw=black] (B5) at (8+.951,15+.309) {};
    \node[shape=circle,draw=black] (C5) at (8+.588,15-.809) {};
    \node[shape=circle,draw=black] (D5) at (8-.588,15-.809) {};
    \node[shape=circle,draw=black] (E5) at (8-.951,15+.309) {} ;
    \path [-,line width=1pt] (A5) edge node[left] {} (B5) node[yshift=-6.5em] {};
    \path [-,line width=1pt,style=dashed] (D5) edge node[left] {} (C5);
    \path [-,line width=1pt,color=blue] (A5) edge node[left] {} (E5);

    \draw [->,line width=2.5,black!25] (0,13) -- (0,12);
    \node[shape=circle,draw=black] (A6) at (0+0,10+1) {};
    \node[shape=circle,draw=black] (B6) at (0+.951,10+.309) {};
    \node[shape=circle,draw=black] (C6) at (0+.588,10-.809) {};
    \node[shape=circle,draw=black] (D6) at (0-.588,10-.809) {};
    \node[shape=circle,draw=black] (E6) at (0-.951,10+.309) {} ;
    \path [-,line width=1pt] (A6) edge node[left] {} (B6) node[yshift=-6.3em] {Forced move for player 2};
    \path [-,line width=1pt,style=dashed] (A6) edge node[left] {} (C6);
    \path [-,line width=1pt] (A6) edge node[left] {} (E6);
    \path [-,line width=1pt,style=dashed,color=blue] (E6) edge node[left] {} (B6);

    \draw [->,line width=2.5,black!25] (8,13) -- (8,12);
    \node[shape=circle,draw=black] (A7) at (8+0,10+1) {};
    \node[shape=circle,draw=black] (B7) at (8+.951,10+.309*1.3) {};
    \node[shape=circle,draw=black] (C7) at (8+.588,10-.809*1.3) {};
    \node[shape=circle,draw=black] (D7) at (8-.588,10-.809*1.3) {};
    \node[shape=circle,draw=black] (E7) at (8-.951,10+.309*1.3) {} ;
    \path [-,line width=1pt] (A7) edge node[left] {} (B7) node[yshift=-6.3em] {Forced move for player 2};
    \path [-,line width=1pt,style=dashed] (D7) edge node[left] {} (C7);
    \path [-,line width=1pt] (A7) edge node[left] {} (E7);
    \path [-,line width=1pt,style=dashed,color=blue] (E7) edge node[left] {} (B7);

    \draw [->,line width=2.5,black!25] (0,7.75) -- (0,6.75);
    \node[shape=circle,draw=black] (A8) at (0+0,5+1) {};
    \node[shape=circle,draw=black] (B8) at (0+.951,5+.309) {};
    \node[shape=circle,draw=black] (C8) at (0+.588,5-.809) {};
    \node[shape=circle,draw=black] (D8) at (0-.588,5-.809) {};
    \node[shape=circle,draw=black] (E8) at (0-.951,5+.309) {} ;
    \path [-,line width=1pt] (A8) edge node[left] {} (B8) node[yshift=-7em] {\parbox{7.1cm}{Player 1 has forced a win because Player 2 can only play one of the moves in red; Player 1 will use the other to win}};
    \path [-,line width=1pt,style=dashed] (A8) edge node[left] {} (C8);
    \path [-,line width=1pt] (A8) edge node[left] {} (E8);
    \path [-,line width=1pt,style=dashed] (E8) edge node[left] {} (B8);
    \path [-,line width=1pt,color=blue] (A8) edge node[left] {} (D8);
    \path [-,line width=1pt,style=dashed,color=lightred] (E8) edge node[left] {} (D8);
    \path [-,line width=1pt,style=dashed,color=lightred] (B8) edge node[left] {} (D8);

    \draw [->,line width=2.5,black!25] (8,7.75) -- (8,6.75);
    \node[shape=circle,draw=black] (A9) at (8+0,5+1) {};
    \node[shape=circle,draw=black] (B9) at (8+.951,5+.309) {};
    \node[shape=circle,draw=black] (C9) at (8+.588,5-.809) {};
    \node[shape=circle,draw=black] (D9) at (8-.588,5-.809) {};
    \node[shape=circle,draw=black] (E9) at (8-.951,5+.309) {} ;
    \path [-,line width=1pt] (A9) edge node[left] {} (B9) node[yshift=-7em] {\parbox{7.1cm}{Player 1 has forced a win because Player 2 can only play one of the moves in red; Player 1 will use the other to win}};
    \path [-,line width=1pt,style=dashed] (D9) edge node[left] {} (C9);
    \path [-,line width=1pt] (A9) edge node[left] {} (E9);
    \path [-,line width=1pt,style=dashed] (E9) edge node[left] {} (B9);
    \path [-,line width=1pt,color=blue] (A9) edge node[left] {} (D9);
    \path [-,line width=1pt,style=dashed,color=lightred] (E9) edge node[left] {} (D9);
    \path [-,line width=1pt,style=dashed,color=lightred] (B9) edge node[left] {} (D9);
\end{tikzpicture}
\end{center}

\section{Sum of Choices}
\ProblemStatement{
    Calculate $\sum_{k=1}^n \binom{k}{m} \frac{1}{k}$.
}

\[
    \sum_{k=1}^n \binom{k}{m} \frac{1}{k} =
    \begin{cases}
        H_n &: m = 0\\
        \frac{1}{m} \binom{n}{m} &: m \ge 1\\
    \end{cases}
\]

\begin{proof}
For $m=0$, we have $\sum_{k=1}^n \frac{1}{k} = H_n$, the nth harmonic number by definition.
For $m \ge 1$,
\begin{align*}
    \sum_{k=1}^n \binom{k}{m} \frac{1}{k} &=\sum_{k=1}^n \frac{k!}{m!(k-m)!} \frac{1}{k}\\
    &=\sum_{k=1}^n \frac{(k-1)!}{m!(k-m)!}\\
    &=\frac{1}{m} \sum_{k=1}^n \frac{(k-1)!}{(m-1)!(k-m)!}\\
    &=\frac{1}{m} \sum_{k=1}^n \binom{k-1}{m-1}
\end{align*}

From previous work, we know that the sum of diagonal elements in Pascal's triangle is $\sum_{a=0}^b \binom{a}{c} = \binom{b+1}{c+1}$, thus by setting $a=k-1$, $c=m-1$, $b=n-1$ we obtain $\sum_{k=1}^n \binom{k-1}{m-1}=\binom{n}{m}$ and thus $
    \sum_{k=1}^n \binom{k}{m} \frac{1}{k} = \frac{1}{m} \binom{n}{m}: m \ge 1$.
\end{proof}

\section{Counting Functions}
\ProblemStatement{
How many functions $f : [n] \rightarrow [n]$ are there such that for all $i < j$, we have $f(i) \leq f(j)$?
}

There are $\binom{2n-1}{n}$ functions on $[n] \rightarrow [n]$ such that for all $i < j$, $f(i) \leq f(j)$.

\begin{proof}
There is a bijection between these functions and paths from $(0, 0)$ to ${(n, n-1)}$ which consist of single steps $(+1, 0)$ or $(0, +1)$. To construct such a path from a function, do the following:
\begin{enumerate}
    \item For each value $a$ in the domain of $f$, draw a step from at $(a-1, f(a)-1)$ to $(a, f(a)-1)$.
    \item Draw vertical lines to connect the horizontal steps, as needed.
    \item Draw vertical lines to connect $(0,0)$ to $(0, f(1)-1)$ and $(n, f(n)-1)$ to $(n,n-1)$, as needed.
\end{enumerate}

Additionally, any path from $(0,0)$ to $(n,n-1)$ consisting of only steps $(+1, 0)$ or $(0, +1)$ has a unique corresponding function $f(i)$ defined by $f(i) = 1 + y-$coordinate of the step from $x=i$ to $x=i+1$. Thus there's a bijection between these paths and these functions. We know from previous work that the number of such paths is equal to $\binom{2n-1}{n}$ since it is equivalent to having a list made up of $2n-1$ instructions, $n$ of which are \say{go right} while the rest are \say{go up}.
\end{proof}
\newcommand{\bijectpath}[3]{\scalebox{.8}{
\begin{tikzpicture}
\draw[step=1.0,black,thin,color=black,opacity=.35] (0,0) grid (3,2);
\draw [-,line width=1pt] (0,0) -- (0,#1-1) --
    (1, #1-1) node[shape=circle,fill=black,minimum width=.2cm,inner sep=0pt] {} --
    (1, #2-1) --
    (2, #2-1) node[shape=circle,fill=black,minimum width=.2cm,inner sep=0pt] {} --
    (2, #3-1) --
    (3, #3-1)node[shape=circle,fill=black,minimum width=.2cm,inner sep=0pt] {} --
    (3, 2);
\node [above] at (5.85,-.5) {\parbox{3em}{
    \begin{align*}
    \iff f(x) =
    \begin{cases}
    #1&: x=1\\
    #2&: x=2\\
    #3&: x=3\\
\end{cases}
    \end{align*}
}};
\end{tikzpicture}
}
}

\noindent\ignorespacesafterend
\bijectpath{1}{1}{1} \hspace{2em} \bijectpath{1}{1}{2}\\
\bijectpath{1}{1}{3} \hspace{2em} \bijectpath{1}{2}{2}\\
\bijectpath{1}{2}{3} \hspace{2em} \bijectpath{1}{3}{3}\\
\bijectpath{2}{2}{2} \hspace{2em} \bijectpath{2}{2}{3}\\
\bijectpath{2}{3}{3} \hspace{2em} \bijectpath{3}{3}{3}

\section{Time Spent \& Thoughts}
This was really time consuming. I either need to stop trying to do the optional problems or not attempt to take this class while working full time. :) I probably spent about 15 hours on this assignment. I enjoyed problems 1, 3, and 5 quite a bit. Problem 4 took a long time to figure out and wasn't very interesting, although it's probably good practice.
\end{document}


\documentclass[t,usenames,dvipsnames]{beamer}
\usetheme{Copenhagen}
\setbeamertemplate{headline}{} % remove toc from headers
\beamertemplatenavigationsymbolsempty

\usepackage{amsmath, tcolorbox, bm, tikz, pgfplots}
\pgfplotsset{compat = 1.16}

\everymath{\displaystyle}

\title{Radical Equations and Inequalities}
\author{}
\date{}

\AtBeginSection[]
{
  \begin{frame}
    \frametitle{Objectives}
    \tableofcontents[currentsection]
  \end{frame}
}

\begin{document}

\begin{frame}
    \maketitle
\end{frame}

\section{Solve radical equations}

\begin{frame}{Solving Radical Equations}
When solving radical equations, we want to try our best to isolate the radical on one side of the equation (if possible). \newline\\	\pause

Then we can raise both sides to the power that is the root of the radical.    \newline\\	\pause

However, sometimes you may end up with extraneous solutions.
\end{frame}

\begin{frame}{Example 1}
Solve each. Remember to check for extraneous solutions.	\newline\\
(a) \quad $\sqrt{5x+1} = 4$
\begin{align*}
\onslide<2->{\sqrt{5x+1} &= 4} \\[6pt]
\onslide<3->{\left(\sqrt{5x+1}\right)^2 &= 4^2} \\[6pt]
\onslide<4->{5x+1 &= 16} \\[6pt]
\onslide<5->{x &= 3}
\end{align*}
\onslide<6->{Check: $\sqrt{5(3)+1} = 4?$}
\onslide<7->{\quad Yes}
\end{frame}

\begin{frame}{Example 1}
(b) \quad $\sqrt{8-x} + 7 = 10$
\begin{align*}
\onslide<2->{\sqrt{8-x} + 7 &= 10} \\[6pt]
\onslide<3->{\sqrt{8-x} &= 3} \\[6pt]
\onslide<4->{8-x &= 9} \\[6pt]
\onslide<5->{x &= -1}
\end{align*}
\onslide<6->{Check: $\sqrt{8-(-1)} + 7 = 10?$}
\onslide<7->{\quad Yes}
\end{frame}

\begin{frame}{Example 1}
(c) \quad $\sqrt[3]{x-10} = 3$
\begin{align*}
\onslide<2->{\sqrt[3]{x-10} &= 3} \\[6pt]
\onslide<3->{\left(\sqrt[3]{x-10}\right)^3 &= 3^3} \\[6pt]
\onslide<4->{x - 10 &= 27} \\[6pt]
\onslide<5->{x &= 37}
\end{align*}
\end{frame}

\begin{frame}{Example 1}
(d) \quad $3\sqrt{x}+12=9$
\begin{align*}
\onslide<2->{3\sqrt{x}+12 &= 9} \\[6pt]
\onslide<3->{3\sqrt{x} &= -3} \\[6pt]
\onslide<4->{\sqrt{x} &= -1} \\[6pt]
\onslide<5->{x &= 1}
\end{align*}
\onslide<6->{Check: $3\sqrt{1}+12=9?$}
\onslide<7->{\quad No}	\newline\\
\onslide<8->{No Solution $\varnothing$}
\end{frame}

\begin{frame}{Example 1}
(e) \quad $\sqrt{2x-7}=\sqrt{3x-12}$
\begin{align*}
\onslide<2->{\sqrt{2x-7} &= \sqrt{3x-12}} \\[6pt]
\onslide<3->{2x - 7 &= 3x - 12} \\[6pt]
\onslide<4->{x &= 5}
\end{align*}
\end{frame}

\begin{frame}{Example 1}
(f) \quad $x-3=\sqrt{x-1}$
\begin{align*}
\onslide<2->{x-3 &= \sqrt{x-1}} \\[6pt]
\onslide<3->{(x-3)^2 &= \left(\sqrt{x-1}\right)^2} \\[6pt]
\onslide<4->{x^2-6x+9 &= x-1} \\[6pt]
\onslide<5->{x^2 - 7x + 10 &= 0} \\[6pt]
\onslide<6->{(x-2)(x-5) &= 0} \\[6pt]
\onslide<7->{x &= 2, 5}
\end{align*}
\end{frame}

\begin{frame}{Example 1 \quad $x-3=\sqrt{x-1}$}
\[x = 2 \quad x=5\]
Check:	\newline\\
\onslide<2->{$x=2$ is extraneous} \newline\\
\onslide<3->{$x=5$ is valid} \newline\\
\onslide<4->{Final answer: $x=5$}
\end{frame}

\section{Solve equations with rational exponents}

\begin{frame}{Equations with Rational Exponents}
When dealing with rational exponents, recall that raising a power to a power will result in multiplying the exponents together. \newline\\	\pause

Using this knowledge, we can isolate the radicand by raising both sides of the equation to the \underline{reciprocal} of the exponent.
\end{frame}

\begin{frame}{Example 2}
Solve each of the following. Remember to check for extraneous solutions.	\newline\\
(a) 	\quad $x^{2/3} = 3$
\begin{align*}
\onslide<2->{x^{2/3} &= 3} \\[8pt]
\onslide<3->{\left(x^{2/3}\right)^{3/2} &= 3^{3/2}} \\[8pt]
\onslide<4->{x &= 3^{3/2}} \\[8pt]
\onslide<5->{&= \sqrt{27}} \\[8pt]
\onslide<6->{&= 3\sqrt{3}}
\end{align*}
\end{frame}

\begin{frame}{Example 2}
(b) 	\quad $\left(x-1\right)^{-2/3} = 1$
\begin{align*}
\onslide<2->{\left(x-1\right)^{-2/3} &= 1} \\[8pt]
\onslide<3->{\left(\left(x-1\right)^{-2/3}\right)^{-3/2} &= 1^{-3/2}} \\[8pt]
\onslide<4->{x-1 &= 1} \\[8pt]
\onslide<5->{x &= 2}
\end{align*}
\end{frame}

\begin{frame}{Example 2}
(c) 	\quad $\left(x+2\right)^{3/2} = -1$
\begin{align*}
\onslide<2->{\left(x+2\right)^{3/2} &= -1} \\[8pt]
\onslide<3->{\left(\left(x+2\right)^{3/2}\right)^{2/3} &= (-1)^{2/3}} \\[8pt]
\onslide<4->{x+2 &= 1} \\[8pt]
\onslide<5->{x &= -1}
\end{align*}
\onslide<6->{\[\text{No solution } \varnothing \]}
\end{frame}

\section{Solve radical inequalities}

\begin{frame}{Solving Radical Inequalities}
When solving inequalities, use the same techniques as solving the equations, then use number lines and test values to solve inequalities.  \newline\\	\pause

This gives us the advantage of solving any inequality after learning how to solve its equation form.	\newline\\	\pause

\alert{\textbf{Important: }} Remember, when dealing with \textbf{even roots}, the domain of the radicand is $\geq 0$.
\end{frame}

\begin{frame}{Example 3}
Solve each of the following and graph your solution on a number line.	\newline\\
(a)	\quad	$\sqrt{x-3} - 3 < 4$
\begin{align*}
\onslide<2->{\sqrt{x-3} - 3 &= 4} \\[6pt]
\onslide<3->{\sqrt{x-3} &= 7} \\[6pt]
\onslide<4->{x-3 &= 49} \\[6pt]
\onslide<5->{x &= 52}
\end{align*}
\end{frame}

\begin{frame}{Example 3	\quad	$\sqrt{x-3} - 3 < 4$}
Critical value of $x$ is 52.	\newline\\
\onslide<2->{For $\sqrt{x-3}$, $x-3$ must be $\geq 0$, so $x \geq 3$}	\newline\\
\onslide<3->{
\begin{center}
\begin{tikzpicture}
\draw [<->] (-2,0) -- (2,0);
\draw (1,0.15) -- (1,-0.15) node [below] {$52$};
\draw (-1,0.15) -- (-1,-0.15) node [below] {$3$};
\onslide<4->{\draw[color=blue,fill=white] (1,0) circle [radius=2.5pt];
\draw[fill=blue,color=blue] (-1,0) circle [radius=2.5pt];}
\onslide<5->{\draw[color=blue, ultra thick, shorten >= 2.5pt, shorten >= 2.5pt] (-1,0) -- (1,0);}
\end{tikzpicture}
\end{center}
}
\onslide<6->{\[3 \leq x < 52\]}
\end{frame}

\begin{frame}{Example 3}
(b)	\quad	$\sqrt[3]{2x+3} \geq \sqrt[3]{x+12}$
\begin{align*}
\onslide<2->{\sqrt[3]{2x+3} &= \sqrt[3]{x+12}} \\[6pt]
\onslide<3->{2x+3 &= x+12} \\[6pt]
\onslide<4->{x &= 9}
\end{align*}
\onslide<5->{
\begin{center}
\begin{tikzpicture}
\draw [<->] (-2,0) -- (2,0);
\draw (0,0.15) -- (0,-0.15) node [below] {$9$};
\onslide<6->{\draw[color=blue,fill=blue] (0,0) circle [radius=2.5pt];}
\onslide<7->{\draw[color=blue,ultra thick, ->] (0,0) -- (2,0);}
\end{tikzpicture}
\end{center}
}
\onslide<8->{\[x \geq 9 \]}
\end{frame}

\begin{frame}{Example 3}
(c)	\quad	$\sqrt{2x-1} \leq 2x-1$
\begin{align*}
\onslide<2->{\sqrt{2x-1} &= 2x-1} \\[6pt]
\onslide<3->{\left(\sqrt{2x-1}\right)^2 &= (2x-1)^2} \\[6pt]
\onslide<4->{2x-1 &= 4x^2 - 4x + 1} \\[6pt]
\onslide<5->{4x^2 - 6x + 2 &= 0} \\[6pt]
\onslide<6->{x &= \frac{1}{2}, \quad 1}
\end{align*}
\end{frame}

\begin{frame}{Example 3 \quad $\sqrt{2x-1} \leq 2x-1$}
\begin{center}
\begin{tikzpicture}
\draw[<->] (-2.5,0) -- (2.5,0);
\draw (-1,0.15) -- (-1,-0.15) node [below] {$\frac{1}{2}$};
\draw (1,0.15) -- (1,-0.15) node [below] {$1$};
\onslide<2->{\draw[color=blue,fill=blue] (-1,0) circle [radius=2.5pt];
					\draw[color=blue,fill=blue] (1,0) circle [radius=2.5pt];
}
\onslide<3->{\draw[color=blue, ultra thick, ->] (1,0) -- (2.5,0);}
\end{tikzpicture}
\end{center}
\onslide<4->{\[x = \frac{1}{2} \quad \text{or} \quad x \geq 1\]}
\end{frame}

\end{document}


\vssub
\subsection{~Simple ice blocking ({\code IC0})} \label{sub:num_ice}
\opthead{IC0}{\ws}{H. L. Tolman} %\conthead{\ws}{H. L. Tolman}

\noindent
Ice covered sea is considered as `land' in \ws, assuming zero wave energy and
boundary conditions at ice edges are identical to boundary conditions at shore
lines. Grid points are taken out of the calculation if the ice concentration
becomes larger than a user-defined concentration. If the ice concentration
drops below its critical value, the corresponding grid point is
`re-activated'. The spectrum is then initialized with a PM spectrum based on
the local wind direction with a peak frequency corresponding to the
second-highest discrete frequency in the grid. A low energy spectrum is used to
assure that spectra are realistic, even for shallow coastal points.

The above discontinuous ice treatment represents the default model setting in
\ws. In the framework of the modeling of unresolved obstacles as discussed in
\para\ref{sub:num_obst}, a continuous method is also available, as given by
\cite{tol:OMOD03a}. In this method, a user-defined critical ice concentration
at which obstruction begins ($\epsilon_{c,0}$) and is complete
($\epsilon_{c,n}$) are given (defaults are $\epsilon_{c,0} = \epsilon_{c,n} =
0.5$, i.e., discontinuous treatment of ice). From these critical
concentrations, corresponding decay length scales are calculated as

\begin{equation}
l_0 = \epsilon_{c,0} \min ( \Delta x , \Delta y )
, \label{eq:l0}
\end{equation}
\begin{equation}
l_n = \epsilon_{c,n} \min ( \Delta x , \Delta y )
, \label{eq:ln}
\end{equation}

\noindent
from which cell transmissions in $x$ and $y$ ($\alpha_x$ and $\alpha_y$,
respectively) are calculated as

\begin{equation}
\alpha_x = \left \{ \begin{array}{ccl}
 1 & \mbox{for} & \epsilon \Delta x < l_0 \\
 0 & \mbox{for} & \epsilon \Delta x > l_n \\
\frac{l_n - \epsilon \Delta x}{l_n - l_0} & \multicolumn{2}{c}{\mbox{otherwise}}
\end{array} \right .
\:\:\: , \:\:\:
\alpha_y = \left \{ \begin{array}{ccl}
 1 & \mbox{for} & \epsilon \Delta y < l_0 \\
 0 & \mbox{for} & \epsilon \Delta y > l_n \\
\frac{l_n - \epsilon \Delta y}{l_n - l_0} & \multicolumn{2}{c}{\mbox{otherwise}}
\end{array} \right .
\:\:\: . \label{eq:ice_0}
\end{equation}

\noindent
Details of this model can be found in \cite{tol:OMOD03a}.

Updating of the ice map within the model takes place at the discrete model
time approximately half way in between the valid times of the old and new ice
maps. The map will not be updated, if the time stamps of both ice fields are
identical.

The above description pertains to the switch {\code IC0}. Note that either ice transmissions for propagation ({\code IC0}), or ice as a source term can be used ({\code IC1}, {\code IC2}, {\code IC3}), but not both approaches at the same time.


% -*- mode:Noweb; noweb-code-mode: sml-mode -*-% ===> this file was generated automatically by noweave --- better not edit it
\documentclass{article}
\usepackage{graphicx}
\usepackage{noweb}
\usepackage{hyperref}
\date{}
\author{}

\title{COL765 - Assignment 2}
\author{Nilaksh Agarwal \\
                2015PH10813}
\date{}
\begin{document}
\maketitle
\section{Introduction}
The purpose of this assignment was to develop a module to regenerate a Tree, given it's in-order traversal. I have used the document \href{http://www.cse.iitd.ernet.in/~sak/courses/ilfp/recover.pdf}{Rambling Through Woods on a Sunny Morning} for reference and also used the Binary Tree signature and structure given in the same.

\section{The complications with inorder traversal}

Unlike preorder or postorder traversals, inorder traversals have no structural information in them. For example, in a preorder traversal, all values occurring to the right of a given node, are the descendants of that node. Similarly, to the left for postorder traversals. \\

In an inorder traversal however, there is no such structural information available, and moreover, there is some noise added to this as well. \\

This is clearly visualized with the 3 following trees, which all have the same inorder traversal: \\[0.5cm]
\begin{center}
        \includegraphics[width=14cm]{Inorder_wrong.jpg}
\end{center}

\section{The Binary Tree Signature}

Here we define a basic datatype for bintree:

\nwfilename{2015PH10813.nw}\nwbegincode{1}\sublabel{NW6NVqj-4XyAA2-1}\nwmargintag{{\nwtagstyle{}\subpageref{NW6NVqj-4XyAA2-1}}}\moddef{Node~{\nwtagstyle{}\subpageref{NW6NVqj-4XyAA2-1}}}\endmoddef\nwstartdeflinemarkup\nwusesondefline{\\{NW6NVqj-4WBYwn-1}\\{NW6NVqj-2nTQtw-1}}\nwenddeflinemarkup
        datatype 'a bintree =
                Empty
                | Node of 'a * 'a bintree * 'a bintree
\nwused{\\{NW6NVqj-4WBYwn-1}\\{NW6NVqj-2nTQtw-1}}\nwendcode{}\nwbegindocs{2}\nwdocspar

We also define a option datatype, since we intend to store the empty Leaf nodes as well

\nwenddocs{}\nwbegincode{3}\sublabel{NW6NVqj-4JPyOG-1}\nwmargintag{{\nwtagstyle{}\subpageref{NW6NVqj-4JPyOG-1}}}\moddef{Option~{\nwtagstyle{}\subpageref{NW6NVqj-4JPyOG-1}}}\endmoddef\nwstartdeflinemarkup\nwusesondefline{\\{NW6NVqj-4WBYwn-1}\\{NW6NVqj-2nTQtw-1}}\nwenddeflinemarkup
        datatype 'a option = NONE | SOME of 'a
\nwused{\\{NW6NVqj-4WBYwn-1}\\{NW6NVqj-2nTQtw-1}}\nwendcode{}\nwbegindocs{4}\nwdocspar

We define our regular preorder \& postorder functions like in the \href{http://www.cse.iitd.ernet.in/~sak/courses/ilfp/recover.pdf}{document}. Here \textbf{'a option list} implies a list which can contain \textbf{NONE} in case of Empty subtree or \textbf{SOME of value}

\nwenddocs{}\nwbegincode{5}\sublabel{NW6NVqj-azPlp-1}\nwmargintag{{\nwtagstyle{}\subpageref{NW6NVqj-azPlp-1}}}\moddef{PrePostSig~{\nwtagstyle{}\subpageref{NW6NVqj-azPlp-1}}}\endmoddef\nwstartdeflinemarkup\nwusesondefline{\\{NW6NVqj-4WBYwn-1}}\nwenddeflinemarkup
        val preorder : 'a bintree ->  'a option list
        val postorder : 'a bintree -> 'a option list
\nwused{\\{NW6NVqj-4WBYwn-1}}\nwendcode{}\nwbegindocs{6}\nwdocspar

However, for inorder, this is not enough. We need some addition \textit{Cosmetic Sugar} to gain the missing structural information in this traversal. Hence, we include the depth of a node defined to be 0 for the root node, and the depth of any child is 1 + the depth of their parent. \\
So, our node now contains a Tuple (value, depth) which is returned from the inorder traversal. Now we can define the signatures of the inorder and inorderInverse

\nwenddocs{}\nwbegincode{7}\sublabel{NW6NVqj-2NTUdd-1}\nwmargintag{{\nwtagstyle{}\subpageref{NW6NVqj-2NTUdd-1}}}\moddef{InSig~{\nwtagstyle{}\subpageref{NW6NVqj-2NTUdd-1}}}\endmoddef\nwstartdeflinemarkup\nwusesondefline{\\{NW6NVqj-4WBYwn-1}}\nwenddeflinemarkup
        val inorder : 'a bintree -> ('a option * int) list
        val inorderInverse : ('a option * int) list -> 'a bintree
\nwused{\\{NW6NVqj-4WBYwn-1}}\nwendcode{}\nwbegindocs{8}\nwdocspar

One last function we use to check if two given trees are equal. For this, we find their preorder and postorder traversals, and check their equality.
\nwenddocs{}\nwbegincode{9}\sublabel{NW6NVqj-3QvoFw-1}\nwmargintag{{\nwtagstyle{}\subpageref{NW6NVqj-3QvoFw-1}}}\moddef{equalSig~{\nwtagstyle{}\subpageref{NW6NVqj-3QvoFw-1}}}\endmoddef\nwstartdeflinemarkup\nwusesondefline{\\{NW6NVqj-4WBYwn-1}}\nwenddeflinemarkup
        val checkTrees : ''a bintree * ''a bintree -> bool
\nwused{\\{NW6NVqj-4WBYwn-1}}\nwendcode{}\nwbegindocs{10}\nwdocspar

Now we can put everything together in our Signature

\nwenddocs{}\nwbegincode{11}\sublabel{NW6NVqj-4WBYwn-1}\nwmargintag{{\nwtagstyle{}\subpageref{NW6NVqj-4WBYwn-1}}}\moddef{bintreeSignature-complete~{\nwtagstyle{}\subpageref{NW6NVqj-4WBYwn-1}}}\endmoddef\nwstartdeflinemarkup\nwusesondefline{\\{NW6NVqj-2nTQtw-1}}\nwenddeflinemarkup
signature BINTREE =
sig
\LA{}Node~{\nwtagstyle{}\subpageref{NW6NVqj-4XyAA2-1}}\RA{}
\LA{}Option~{\nwtagstyle{}\subpageref{NW6NVqj-4JPyOG-1}}\RA{}
        exception Empty_bintree;
        exception InvalidTraversal;
\LA{}PrePostSig~{\nwtagstyle{}\subpageref{NW6NVqj-azPlp-1}}\RA{}
\LA{}InSig~{\nwtagstyle{}\subpageref{NW6NVqj-2NTUdd-1}}\RA{}
\LA{}equalSig~{\nwtagstyle{}\subpageref{NW6NVqj-3QvoFw-1}}\RA{}
end
\nwused{\\{NW6NVqj-2nTQtw-1}}\nwendcode{}\nwbegindocs{12}\nwdocspar

\section{The Binary Tree Structure}

Similarly to the \href{http://www.cse.iitd.ernet.in/~sak/courses/ilfp/recover.pdf}{document} we define the preorder \& postorder functions using the tail recursive forms. \\

We use \textbf{NONE} to indicate empty nodes and \textbf{SOME of val}
to indicate nodes with value \textbf{val}
\nwenddocs{}\nwbegincode{13}\sublabel{NW6NVqj-FYIyT-1}\nwmargintag{{\nwtagstyle{}\subpageref{NW6NVqj-FYIyT-1}}}\moddef{preorder~{\nwtagstyle{}\subpageref{NW6NVqj-FYIyT-1}}}\endmoddef\nwstartdeflinemarkup\nwusesondefline{\\{NW6NVqj-2nTQtw-1}}\nwenddeflinemarkup
    local
        fun pre(Empty, Llist) = NONE::Llist
                | pre(Node(N,Ltree, Rtree),Llist) =
                let
                        val Mlist = pre(Rtree,Llist)
                        val Nlist = pre(Ltree,Mlist)
                in
                        SOME N :: Nlist
                end
        in
                fun preorder T = pre(T,[])
        end
\nwused{\\{NW6NVqj-2nTQtw-1}}\nwendcode{}\nwbegindocs{14}\nwdocspar

\nwenddocs{}\nwbegincode{15}\sublabel{NW6NVqj-2drSLa-1}\nwmargintag{{\nwtagstyle{}\subpageref{NW6NVqj-2drSLa-1}}}\moddef{postorder~{\nwtagstyle{}\subpageref{NW6NVqj-2drSLa-1}}}\endmoddef\nwstartdeflinemarkup\nwusesondefline{\\{NW6NVqj-2nTQtw-1}}\nwenddeflinemarkup
    local
        fun post(Empty, Llist) = NONE::Llist
                | post(Node(N,Ltree, Rtree),Llist) =
                let
                        val Mlist = post(Rtree,SOME N::Llist)
                        val Nlist = post(Ltree,Mlist)
                in
                        Nlist
                end
        in
                fun postorder T = post(T,[])
        end
\nwused{\\{NW6NVqj-2nTQtw-1}}\nwendcode{}\nwbegindocs{16}\nwdocspar

In inorder however, we need to store the depth of the node as well, since we are unable to figure out any strucural information from the traversal

\nwenddocs{}\nwbegincode{17}\sublabel{NW6NVqj-N7IVZ-1}\nwmargintag{{\nwtagstyle{}\subpageref{NW6NVqj-N7IVZ-1}}}\moddef{inorder~{\nwtagstyle{}\subpageref{NW6NVqj-N7IVZ-1}}}\endmoddef\nwstartdeflinemarkup\nwusesondefline{\\{NW6NVqj-2nTQtw-1}}\nwenddeflinemarkup
        local
        fun ino(Empty, Llist,i) = (NONE,i)::Llist
                | ino(Node(N,Ltree, Rtree),Llist,i) =
                let
                        val Mlist = ino(Rtree,Llist,i+1)
                        val Nlist = ino(Ltree,(SOME N,i)::Mlist,i+1)
                in
                        Nlist
                end
        in
                fun inorder T = ino(T,[],0)
        end
\nwused{\\{NW6NVqj-2nTQtw-1}}\nwendcode{}\nwbegindocs{18}\nwdocspar

Here we store (value,depth) as a tuple in the node. \\

\subsection{The Inorder Inverse}

Before we start the inorder inverse function, we define some facts about our updated inorder Traversal (with heights)

\textit{\begin{enumerate}
    \item In any inorder traversal ($\bot$,\_) is the first and last element
    \item If any inorder traversal has more than 1 element, the tree is non-empty
    \item The descendants of a node always have a depth greater than the depth of the node. (\textbf{m},h1) \& (\textbf{n},h2) : n is a descendant of m if (h2 \textgreater h1)
    \item Any node m that has a height greater than a node l = (v,h) is either a descendant of l or a descendant of a sibling of l
    \item Any slice of the form [(\textbf{$\bot$},h+1), (\textbf{v},h), ($\neq \bot \neq$,h+1)] determines a unique leaf node in the tree with height h.
    \item Any slice of the form [(\textbf{$\bot$},h+2), (\textbf{m},h+1), (\textbf{$\bot$}, h+2), (\textbf{l},h), (\textbf{$\bot$},h+1)] where m $\neq \bot \neq$ l are values of the nodes, determines a unique subtree rooted at l whose left child is the leaf node m and the right child is empty
    \item Any slice of the form [(\textbf{$\bot$},h+1), (\textbf{l},h), (\textbf{$\bot$}, h+2), (\textbf{m},h+1), (\textbf{$\bot$},h+2)] where m $\neq \bot \neq$ l   are values of the nodes, determines a unique subtree rooted at l whose right
    child is the leaf node m and the left child is empty.
    \item Any slice of the form [(\textbf{T1},h+1), (\textbf{v},h), (\textbf{T2},h+1)] where T1  $\neq \bot \neq$ T2 are subtrees/leaf nodes determines a subtree rooted at v with T1 and T2 as it's left and right children
\end{enumerate}}

\textbf{Uniqueness of Inorder Traversal}: No two distinct binary trees can yield the same inorder traversal.
\textit{Proof:} The proof follows from the definition of inorder traversal and the previous facts (especially the if and only if
conditions) Further the statements yield an inductive proof along with a case analysis of the inductive step \\

Now we define some helper functions to create this inorder inverse. The first function converts a inorder traversal into a list of Bintree nodes.

\nwenddocs{}\nwbegincode{19}\sublabel{NW6NVqj-3s4e0t-1}\nwmargintag{{\nwtagstyle{}\subpageref{NW6NVqj-3s4e0t-1}}}\moddef{Nodify~{\nwtagstyle{}\subpageref{NW6NVqj-3s4e0t-1}}}\endmoddef\nwstartdeflinemarkup\nwusesondefline{\\{NW6NVqj-D88LJ-1}}\nwenddeflinemarkup
    fun  Nodify[] = []
                | Nodify (h::t) =
                Node(h,Empty,Empty)::Nodify(t)
\nwused{\\{NW6NVqj-D88LJ-1}}\nwendcode{}\nwbegindocs{20}\nwdocspar

The next function joins 3 nodes into a single node if the height of the middle node is one less than the other two.

\nwenddocs{}\nwbegincode{21}\sublabel{NW6NVqj-4eyur2-1}\nwmargintag{{\nwtagstyle{}\subpageref{NW6NVqj-4eyur2-1}}}\moddef{joinNodes~{\nwtagstyle{}\subpageref{NW6NVqj-4eyur2-1}}}\endmoddef\nwstartdeflinemarkup\nwusesondefline{\\{NW6NVqj-D88LJ-1}}\nwenddeflinemarkup
                fun joinNodes(T1 as Node((v1,h1),_,_), T2 as Node((v2,h2),_,_), T3 as Node((v3,h3),_,_)) =
                if(h1=h3 andalso (h1-1)=h2) then
                        [Node((v2,h2),T1,T3)]
                else
                        [T1,T2,T3]
                | joinNodes(T1,T2,T3) = raise InvalidTraversal
\nwused{\\{NW6NVqj-D88LJ-1}}\nwendcode{}\nwbegindocs{22}\nwdocspar

The next function goes over a list of notes and tries combining all the successive nodes triplets

\nwenddocs{}\nwbegincode{23}\sublabel{NW6NVqj-2W3UBo-1}\nwmargintag{{\nwtagstyle{}\subpageref{NW6NVqj-2W3UBo-1}}}\moddef{CombineIter~{\nwtagstyle{}\subpageref{NW6NVqj-2W3UBo-1}}}\endmoddef\nwstartdeflinemarkup\nwusesondefline{\\{NW6NVqj-D88LJ-1}}\nwenddeflinemarkup
        fun combineIter(h1::h2::h3::[]) =
                        joinNodes(h1,h2,h3)
                | combineIter(L as h1::h2::h3::tl) =
                let
                        val M = joinNodes(h1,h2,h3) @ tl
                in
                        List.hd(M) :: combineIter(List.tl(M))
                end
                | combineIter (L as h1::h2::[]) = L
                | combineIter L = raise InvalidTraversal
\nwused{\\{NW6NVqj-D88LJ-1}}\nwendcode{}\nwbegindocs{24}\nwdocspar

Now, a function keeps calling the iterative joining function until only one node remains

\nwenddocs{}\nwbegincode{25}\sublabel{NW6NVqj-3BQdfV-1}\nwmargintag{{\nwtagstyle{}\subpageref{NW6NVqj-3BQdfV-1}}}\moddef{Combine~{\nwtagstyle{}\subpageref{NW6NVqj-3BQdfV-1}}}\endmoddef\nwstartdeflinemarkup\nwusesondefline{\\{NW6NVqj-D88LJ-1}}\nwenddeflinemarkup
                fun combine(hd::[]) = hd
                | combine L =
                let
                        val M = combineIter L
                in
                        combine M
                end
\nwused{\\{NW6NVqj-D88LJ-1}}\nwendcode{}\nwbegindocs{26}\nwdocspar

This tree created has Complete nodes even for Empty Leaf nodes. We need to clean this up and remove the extra Empty Nodes

\nwenddocs{}\nwbegincode{27}\sublabel{NW6NVqj-8c9SM-1}\nwmargintag{{\nwtagstyle{}\subpageref{NW6NVqj-8c9SM-1}}}\moddef{treeClean~{\nwtagstyle{}\subpageref{NW6NVqj-8c9SM-1}}}\endmoddef\nwstartdeflinemarkup\nwusesondefline{\\{NW6NVqj-D88LJ-1}}\nwenddeflinemarkup
                fun treeClean(Node((SOME v,_),Ltree,Rtree)) =
                let
                        val LClean = treeClean(Ltree)
                        val RClean = treeClean(Rtree)
                in
                        Node(v, LClean, RClean)
                end
                | treeClean(T) = Empty
\nwused{\\{NW6NVqj-D88LJ-1}}\nwendcode{}\nwbegindocs{28}\nwdocspar

Now we can put it all together in our inorderInverse

\nwenddocs{}\nwbegincode{29}\sublabel{NW6NVqj-D88LJ-1}\nwmargintag{{\nwtagstyle{}\subpageref{NW6NVqj-D88LJ-1}}}\moddef{inorderInverse~{\nwtagstyle{}\subpageref{NW6NVqj-D88LJ-1}}}\endmoddef\nwstartdeflinemarkup\nwusesondefline{\\{NW6NVqj-2nTQtw-1}}\nwenddeflinemarkup
    local
        \LA{}Nodify~{\nwtagstyle{}\subpageref{NW6NVqj-3s4e0t-1}}\RA{}
        \LA{}joinNodes~{\nwtagstyle{}\subpageref{NW6NVqj-4eyur2-1}}\RA{}
        \LA{}CombineIter~{\nwtagstyle{}\subpageref{NW6NVqj-2W3UBo-1}}\RA{}
        \LA{}Combine~{\nwtagstyle{}\subpageref{NW6NVqj-3BQdfV-1}}\RA{}
        \LA{}treeClean~{\nwtagstyle{}\subpageref{NW6NVqj-8c9SM-1}}\RA{}
    in
        fun inorderInverse(L) =
                        treeClean (combine (Nodify L))

        end
\nwused{\\{NW6NVqj-2nTQtw-1}}\nwendcode{}\nwbegindocs{30}\nwdocspar

Having gotten a tree back from an inorder inverse, we would like to define a function to check if the tree is the same as our original tree. We can do the same by comparing their preorder \& postorder traversal. (Since in the \href{http://www.cse.iitd.ernet.in/~sak/courses/ilfp/recover.pdf}{document} the uniqueness of preorder/postorder traversals has been proved. For this we need to check if two lists generated by the traversals are the same

\nwenddocs{}\nwbegincode{31}\sublabel{NW6NVqj-2cpULM-1}\nwmargintag{{\nwtagstyle{}\subpageref{NW6NVqj-2cpULM-1}}}\moddef{checkList~{\nwtagstyle{}\subpageref{NW6NVqj-2cpULM-1}}}\endmoddef\nwstartdeflinemarkup\nwusesondefline{\\{NW6NVqj-1Uzkdr-1}}\nwenddeflinemarkup
    fun checkList([],[]) = true
                | checkList([],_) = false
                | checkList(_,[]) = false
                | checkList(NONE::t1, NONE::t2) = checkList(t1,t2)
                | checkList(SOME h1::t1, SOME h2::t2) =
                if(h1=h2) then
                        checkList(t1,t2)
                else
                        false
                | checkList(_,_) = false
\nwused{\\{NW6NVqj-1Uzkdr-1}}\nwendcode{}\nwbegindocs{32}\nwdocspar

\nwenddocs{}\nwbegincode{33}\sublabel{NW6NVqj-1Uzkdr-1}\nwmargintag{{\nwtagstyle{}\subpageref{NW6NVqj-1Uzkdr-1}}}\moddef{checkTrees~{\nwtagstyle{}\subpageref{NW6NVqj-1Uzkdr-1}}}\endmoddef\nwstartdeflinemarkup\nwusesondefline{\\{NW6NVqj-2nTQtw-1}}\nwenddeflinemarkup
    local
                \LA{}checkList~{\nwtagstyle{}\subpageref{NW6NVqj-2cpULM-1}}\RA{}
        in
                fun checkTrees(T1,T2) =
                let
                        val pre1 = preorder(T1)
                        val pre2 = preorder(T2)
                        val pos1 = postorder(T1)
                        val pos2 = postorder(T2)
                in
                        if(checkList(pre1,pre2) andalso checkList(pos1,pos2)) then
                                true
                        else
                                false
                end
        end
\nwused{\\{NW6NVqj-2nTQtw-1}}\nwendcode{}\nwbegindocs{34}\nwdocspar

Now we put it all together into our Bintree structure

\nwenddocs{}\nwbegincode{35}\sublabel{NW6NVqj-2nTQtw-1}\nwmargintag{{\nwtagstyle{}\subpageref{NW6NVqj-2nTQtw-1}}}\moddef{bintreeStructure-complete~{\nwtagstyle{}\subpageref{NW6NVqj-2nTQtw-1}}}\endmoddef\nwstartdeflinemarkup\nwusesondefline{\\{NW6NVqj-stHGb-1}}\nwenddeflinemarkup
\LA{}bintreeSignature-complete~{\nwtagstyle{}\subpageref{NW6NVqj-4WBYwn-1}}\RA{}
structure Bintree : BINTREE =
struct
    \LA{}Node~{\nwtagstyle{}\subpageref{NW6NVqj-4XyAA2-1}}\RA{}
    \LA{}Option~{\nwtagstyle{}\subpageref{NW6NVqj-4JPyOG-1}}\RA{}

    exception Empty_bintree
        exception InvalidTraversal

        \LA{}preorder~{\nwtagstyle{}\subpageref{NW6NVqj-FYIyT-1}}\RA{}
        \LA{}postorder~{\nwtagstyle{}\subpageref{NW6NVqj-2drSLa-1}}\RA{}
        \LA{}inorder~{\nwtagstyle{}\subpageref{NW6NVqj-N7IVZ-1}}\RA{}
    \LA{}inorderInverse~{\nwtagstyle{}\subpageref{NW6NVqj-D88LJ-1}}\RA{}
    \LA{}checkTrees~{\nwtagstyle{}\subpageref{NW6NVqj-1Uzkdr-1}}\RA{}
end
\nwused{\\{NW6NVqj-stHGb-1}}\nwendcode{}\nwbegindocs{36}\nwdocspar

\section{Test Cases}

We define the following test cases to check the performance of our inorderInverse

\begin{center}
        \includegraphics[width=14cm]{Test1.jpg}
        \\
        \includegraphics[width=14cm]{Test2.jpg}
\end{center}
\nwenddocs{}\nwbegincode{37}\sublabel{NW6NVqj-2obuBU-1}\nwmargintag{{\nwtagstyle{}\subpageref{NW6NVqj-2obuBU-1}}}\moddef{test1~{\nwtagstyle{}\subpageref{NW6NVqj-2obuBU-1}}}\endmoddef\nwstartdeflinemarkup\nwusesondefline{\\{NW6NVqj-stHGb-1}}\nwenddeflinemarkup
local
        val t7 = Node (7, Empty, Empty);
        val t6 = Node (6, t7, Empty);
        val t5 = Node (5, Empty, Empty);
        val t4 = Node (4, Empty, Empty);
        val t3 = Node (3, t5, t6);
        val t2 = Node (2, Empty, t4);
in
        val test1 = Node (1, t2, t3);
end
\nwused{\\{NW6NVqj-stHGb-1}}\nwendcode{}\nwbegindocs{38}\nwdocspar
\nwenddocs{}\nwbegincode{39}\sublabel{NW6NVqj-PItlY-1}\nwmargintag{{\nwtagstyle{}\subpageref{NW6NVqj-PItlY-1}}}\moddef{test2~{\nwtagstyle{}\subpageref{NW6NVqj-PItlY-1}}}\endmoddef\nwstartdeflinemarkup\nwusesondefline{\\{NW6NVqj-stHGb-1}}\nwenddeflinemarkup
local
        val t15 = Node (15, Empty, Empty);
        val t14 = Node (14, Empty, Empty);
        val t13 = Node (13, Empty, Empty);
        val t12 = Node (12, Empty, Empty);
        val t11 = Node (11, Empty, Empty);
        val t10 = Node (10, Empty, Empty);
        val t9 = Node (9, Empty, Empty);
        val t8 = Node (8, Empty, Empty);
        val t7 = Node(7, t14, t15);
        val t6 = Node (6, t12, t13);
        val t5 = Node (5, t10, t11);
        val t4 = Node (4, t8, t9);
        val t3 = Node (3, t6, t7);
        val t2 = Node (2, t4, t5);
in
        val test2 = Node (1, t2, t3);
end
\nwused{\\{NW6NVqj-stHGb-1}}\nwendcode{}\nwbegindocs{40}\nwdocspar
\nwenddocs{}\nwbegincode{41}\sublabel{NW6NVqj-4A3yQS-1}\nwmargintag{{\nwtagstyle{}\subpageref{NW6NVqj-4A3yQS-1}}}\moddef{test3~{\nwtagstyle{}\subpageref{NW6NVqj-4A3yQS-1}}}\endmoddef\nwstartdeflinemarkup\nwusesondefline{\\{NW6NVqj-stHGb-1}}\nwenddeflinemarkup
local
        val t11 = Node (11, Empty, Empty);
        val t10 = Node (10, Empty, Empty);
        val t9 = Node (9, Empty, Empty);
        val t8 = Node (8, Empty, Empty);
        val t5 = Node (5, t10, t11);
        val t4 = Node (4, t8, t9);
        val t2 = Node (2, t4, t5);
in
        val test3 = Node (1, t2, Empty);
end

\nwused{\\{NW6NVqj-stHGb-1}}\nwendcode{}\nwbegincode{42}\sublabel{NW6NVqj-1UZpaq-1}\nwmargintag{{\nwtagstyle{}\subpageref{NW6NVqj-1UZpaq-1}}}\moddef{test4~{\nwtagstyle{}\subpageref{NW6NVqj-1UZpaq-1}}}\endmoddef\nwstartdeflinemarkup\nwusesondefline{\\{NW6NVqj-stHGb-1}}\nwenddeflinemarkup
local
        val t15 = Node (15, Empty, Empty);
        val t14 = Node (14, Empty, Empty);
        val t13 = Node (13, Empty, Empty);
        val t12 = Node (12, Empty, Empty);
        val t7 = Node(7, t14, t15);
        val t6 = Node (6, t12, t13);
        val t3 = Node (3, t6, t7);
in
        val test4 = Node (1, Empty, t3);
end
\nwused{\\{NW6NVqj-stHGb-1}}\nwendcode{}\nwbegindocs{43}\nwdocspar
\nwenddocs{}\nwbegincode{44}\sublabel{NW6NVqj-30oemG-1}\nwmargintag{{\nwtagstyle{}\subpageref{NW6NVqj-30oemG-1}}}\moddef{test5~{\nwtagstyle{}\subpageref{NW6NVqj-30oemG-1}}}\endmoddef\nwstartdeflinemarkup\nwusesondefline{\\{NW6NVqj-stHGb-1}}\nwenddeflinemarkup
local
        val t4 = Node (4, Empty, Empty);
        val t3 = Node (3, t4, Empty);
        val t2 = Node (2, t3, Empty);
in
        val test5 = Node (1, t2, Empty);
end

\nwused{\\{NW6NVqj-stHGb-1}}\nwendcode{}\nwbegincode{45}\sublabel{NW6NVqj-mrbYu-1}\nwmargintag{{\nwtagstyle{}\subpageref{NW6NVqj-mrbYu-1}}}\moddef{test6~{\nwtagstyle{}\subpageref{NW6NVqj-mrbYu-1}}}\endmoddef\nwstartdeflinemarkup\nwusesondefline{\\{NW6NVqj-stHGb-1}}\nwenddeflinemarkup
local
        val t4 = Node (4, Empty, Empty);
        val t3 = Node (3, Empty, t4);
        val t2 = Node (2, Empty, t3);
in
        val test6 = Node (1, Empty, t2);
end
\nwused{\\{NW6NVqj-stHGb-1}}\nwendcode{}\nwbegindocs{46}\nwdocspar
\nwenddocs{}\nwbegincode{47}\sublabel{NW6NVqj-446Oh6-1}\nwmargintag{{\nwtagstyle{}\subpageref{NW6NVqj-446Oh6-1}}}\moddef{test7~{\nwtagstyle{}\subpageref{NW6NVqj-446Oh6-1}}}\endmoddef\nwstartdeflinemarkup\nwusesondefline{\\{NW6NVqj-stHGb-1}}\nwenddeflinemarkup
local
        val t7 = Node (7, Empty, Empty);
        val t6 = Node (6, Empty, Empty);
        val t5 = Node (5, Empty, t7);
        val t4 = Node (4, t6, Empty);
        val t3 = Node (3, Empty, t5);
        val t2 = Node (2, t4, Empty);
in
        val test7 = Node (1, t2, t3);
end
\nwused{\\{NW6NVqj-stHGb-1}}\nwendcode{}\nwbegindocs{48}\nwdocspar
\nwenddocs{}\nwbegincode{49}\sublabel{NW6NVqj-25u5CK-1}\nwmargintag{{\nwtagstyle{}\subpageref{NW6NVqj-25u5CK-1}}}\moddef{test8~{\nwtagstyle{}\subpageref{NW6NVqj-25u5CK-1}}}\endmoddef\nwstartdeflinemarkup\nwusesondefline{\\{NW6NVqj-stHGb-1}}\nwenddeflinemarkup
local
        val t7 = Node (7, Empty, Empty);
        val t6 = Node (6, Empty, Empty);
        val t5 = Node (5, Empty, t7);
        val t4 = Node (4, t6, Empty);
        val t3 = Node (3, t5, Empty);
        val t2 = Node (2, Empty, t4);
in
        val test8 = Node (1, t2, t3);
end
\nwused{\\{NW6NVqj-stHGb-1}}\nwendcode{}\nwbegindocs{50}\nwdocspar

After this, to check if our inorderInverse works for each test case, we simply checkTrees between the inorderInverse generated tree and the original tree

\nwenddocs{}\nwbegincode{51}\sublabel{NW6NVqj-2UuN4Q-1}\nwmargintag{{\nwtagstyle{}\subpageref{NW6NVqj-2UuN4Q-1}}}\moddef{testCheck~{\nwtagstyle{}\subpageref{NW6NVqj-2UuN4Q-1}}}\endmoddef\nwstartdeflinemarkup\nwusesondefline{\\{NW6NVqj-stHGb-1}}\nwenddeflinemarkup
val test1_check = checkTrees(inorderInverse(inorder(test1)),test1);
val test2_check = checkTrees(inorderInverse(inorder(test2)),test2);
val test3_check = checkTrees(inorderInverse(inorder(test3)),test3);
val test4_check = checkTrees(inorderInverse(inorder(test4)),test4);
val test5_check = checkTrees(inorderInverse(inorder(test5)),test5);
val test6_check = checkTrees(inorderInverse(inorder(test6)),test6);
val test7_check = checkTrees(inorderInverse(inorder(test7)),test7);
val test8_check = checkTrees(inorderInverse(inorder(test8)),test8);
\nwused{\\{NW6NVqj-stHGb-1}}\nwendcode{}\nwbegindocs{52}\nwdocspar

\nwenddocs{}\nwbegincode{53}\sublabel{NW6NVqj-stHGb-1}\nwmargintag{{\nwtagstyle{}\subpageref{NW6NVqj-stHGb-1}}}\moddef{testCase-complete~{\nwtagstyle{}\subpageref{NW6NVqj-stHGb-1}}}\endmoddef\nwstartdeflinemarkup\nwenddeflinemarkup
\LA{}bintreeStructure-complete~{\nwtagstyle{}\subpageref{NW6NVqj-2nTQtw-1}}\RA{}
open Bintree;

\LA{}test1~{\nwtagstyle{}\subpageref{NW6NVqj-2obuBU-1}}\RA{}
\LA{}test2~{\nwtagstyle{}\subpageref{NW6NVqj-PItlY-1}}\RA{}
\LA{}test3~{\nwtagstyle{}\subpageref{NW6NVqj-4A3yQS-1}}\RA{}
\LA{}test4~{\nwtagstyle{}\subpageref{NW6NVqj-1UZpaq-1}}\RA{}
\LA{}test5~{\nwtagstyle{}\subpageref{NW6NVqj-30oemG-1}}\RA{}
\LA{}test6~{\nwtagstyle{}\subpageref{NW6NVqj-mrbYu-1}}\RA{}
\LA{}test7~{\nwtagstyle{}\subpageref{NW6NVqj-446Oh6-1}}\RA{}
\LA{}test8~{\nwtagstyle{}\subpageref{NW6NVqj-25u5CK-1}}\RA{}
\LA{}testCheck~{\nwtagstyle{}\subpageref{NW6NVqj-2UuN4Q-1}}\RA{}
\nwnotused{testCase-complete}\nwendcode{}

\nwixlogsorted{c}{{bintreeSignature-complete}{NW6NVqj-4WBYwn-1}{\nwixd{NW6NVqj-4WBYwn-1}\nwixu{NW6NVqj-2nTQtw-1}}}%
\nwixlogsorted{c}{{bintreeStructure-complete}{NW6NVqj-2nTQtw-1}{\nwixd{NW6NVqj-2nTQtw-1}\nwixu{NW6NVqj-stHGb-1}}}%
\nwixlogsorted{c}{{checkList}{NW6NVqj-2cpULM-1}{\nwixd{NW6NVqj-2cpULM-1}\nwixu{NW6NVqj-1Uzkdr-1}}}%
\nwixlogsorted{c}{{checkTrees}{NW6NVqj-1Uzkdr-1}{\nwixd{NW6NVqj-1Uzkdr-1}\nwixu{NW6NVqj-2nTQtw-1}}}%
\nwixlogsorted{c}{{Combine}{NW6NVqj-3BQdfV-1}{\nwixd{NW6NVqj-3BQdfV-1}\nwixu{NW6NVqj-D88LJ-1}}}%
\nwixlogsorted{c}{{CombineIter}{NW6NVqj-2W3UBo-1}{\nwixd{NW6NVqj-2W3UBo-1}\nwixu{NW6NVqj-D88LJ-1}}}%
\nwixlogsorted{c}{{equalSig}{NW6NVqj-3QvoFw-1}{\nwixd{NW6NVqj-3QvoFw-1}\nwixu{NW6NVqj-4WBYwn-1}}}%
\nwixlogsorted{c}{{inorder}{NW6NVqj-N7IVZ-1}{\nwixd{NW6NVqj-N7IVZ-1}\nwixu{NW6NVqj-2nTQtw-1}}}%
\nwixlogsorted{c}{{inorderInverse}{NW6NVqj-D88LJ-1}{\nwixd{NW6NVqj-D88LJ-1}\nwixu{NW6NVqj-2nTQtw-1}}}%
\nwixlogsorted{c}{{InSig}{NW6NVqj-2NTUdd-1}{\nwixd{NW6NVqj-2NTUdd-1}\nwixu{NW6NVqj-4WBYwn-1}}}%
\nwixlogsorted{c}{{joinNodes}{NW6NVqj-4eyur2-1}{\nwixd{NW6NVqj-4eyur2-1}\nwixu{NW6NVqj-D88LJ-1}}}%
\nwixlogsorted{c}{{Node}{NW6NVqj-4XyAA2-1}{\nwixd{NW6NVqj-4XyAA2-1}\nwixu{NW6NVqj-4WBYwn-1}\nwixu{NW6NVqj-2nTQtw-1}}}%
\nwixlogsorted{c}{{Nodify}{NW6NVqj-3s4e0t-1}{\nwixd{NW6NVqj-3s4e0t-1}\nwixu{NW6NVqj-D88LJ-1}}}%
\nwixlogsorted{c}{{Option}{NW6NVqj-4JPyOG-1}{\nwixd{NW6NVqj-4JPyOG-1}\nwixu{NW6NVqj-4WBYwn-1}\nwixu{NW6NVqj-2nTQtw-1}}}%
\nwixlogsorted{c}{{postorder}{NW6NVqj-2drSLa-1}{\nwixd{NW6NVqj-2drSLa-1}\nwixu{NW6NVqj-2nTQtw-1}}}%
\nwixlogsorted{c}{{preorder}{NW6NVqj-FYIyT-1}{\nwixd{NW6NVqj-FYIyT-1}\nwixu{NW6NVqj-2nTQtw-1}}}%
\nwixlogsorted{c}{{PrePostSig}{NW6NVqj-azPlp-1}{\nwixd{NW6NVqj-azPlp-1}\nwixu{NW6NVqj-4WBYwn-1}}}%
\nwixlogsorted{c}{{test1}{NW6NVqj-2obuBU-1}{\nwixd{NW6NVqj-2obuBU-1}\nwixu{NW6NVqj-stHGb-1}}}%
\nwixlogsorted{c}{{test2}{NW6NVqj-PItlY-1}{\nwixd{NW6NVqj-PItlY-1}\nwixu{NW6NVqj-stHGb-1}}}%
\nwixlogsorted{c}{{test3}{NW6NVqj-4A3yQS-1}{\nwixd{NW6NVqj-4A3yQS-1}\nwixu{NW6NVqj-stHGb-1}}}%
\nwixlogsorted{c}{{test4}{NW6NVqj-1UZpaq-1}{\nwixd{NW6NVqj-1UZpaq-1}\nwixu{NW6NVqj-stHGb-1}}}%
\nwixlogsorted{c}{{test5}{NW6NVqj-30oemG-1}{\nwixd{NW6NVqj-30oemG-1}\nwixu{NW6NVqj-stHGb-1}}}%
\nwixlogsorted{c}{{test6}{NW6NVqj-mrbYu-1}{\nwixd{NW6NVqj-mrbYu-1}\nwixu{NW6NVqj-stHGb-1}}}%
\nwixlogsorted{c}{{test7}{NW6NVqj-446Oh6-1}{\nwixd{NW6NVqj-446Oh6-1}\nwixu{NW6NVqj-stHGb-1}}}%
\nwixlogsorted{c}{{test8}{NW6NVqj-25u5CK-1}{\nwixd{NW6NVqj-25u5CK-1}\nwixu{NW6NVqj-stHGb-1}}}%
\nwixlogsorted{c}{{testCase-complete}{NW6NVqj-stHGb-1}{\nwixd{NW6NVqj-stHGb-1}}}%
\nwixlogsorted{c}{{testCheck}{NW6NVqj-2UuN4Q-1}{\nwixd{NW6NVqj-2UuN4Q-1}\nwixu{NW6NVqj-stHGb-1}}}%
\nwixlogsorted{c}{{treeClean}{NW6NVqj-8c9SM-1}{\nwixd{NW6NVqj-8c9SM-1}\nwixu{NW6NVqj-D88LJ-1}}}%
\nwbegindocs{54}\nwdocspar

The reason to choose these particular test cases since it covers some particular ambiguous cases such as a fully dense tree (Test2), a highly skewed tree (Test5 and Test6) as well as a initially skewed and then dense tree (Test3 and Test4) or a highly hollow tree (Test7) as well as a tree containing alternative oriented children (Test8)

The checkTrees function checks the inorderInverse generated tree vs the original tree. For all these testcases, the output is true.

\end{document}
\nwenddocs{}


\setcounter{table}{0}
\setcounter{figure}{0}
\renewcommand{\thetable}{\mbox{E.\arabic{table}}}%
\renewcommand{\thefigure}{\mbox{E--\arabic{figure}}}%

\chapter{Operator Precedence Hierarchy}

\markboth{{\color{cyan}APPENDIX\,E\,\,$\bullet$\,\,}Operator Precedence Hierarchy}
{{\color{cyan}APPENDIX\,E\,\,$\bullet$\,\,}Operator Precedence Hierarchy}

%%\appendixright{E}{Operator Precedence Hierarchy}

\noindent Table E.1 summarizes the precedence and
associativity relationships for Java operators.   Within a single
expression, an operator of order {\it m} would be evaluated before an
operator of order {\it n} if $m < n$. Operators having the same order
are evaluated according to their association order.  For example, the
expression

\begin{jjjlisting}
\begin{lstlisting}
25 + 5 * 2 + 3
\end{lstlisting}
\end{jjjlisting}

\noindent would be evaluated in the order shown by the following
parenthesized expression:

\begin{jjjlisting}
\begin{lstlisting}
(25 + (5 * 2)) + 3   ==> (25 + 10) + 3 ==> 35 + 3  ==> 38
\end{lstlisting}
\end{jjjlisting}

\noindent In other words, because \verb|*| has higher precedence
than \verb|+|, the multiplication operation is done before either of
the addition operations.   And because addition associates from left to
right, addition operations are performed from left to right.

Most operators associate from left to right, but note that assignment
operators associate from right to left.   For example, consider the
following code segment:

\begin{jjjlisting}
\begin{lstlisting}
int i, j, k;
i = j = k = 100;     // Equivalent to i = (j = (k = 100));
\end{lstlisting}
\end{jjjlisting}

\begin{table}[h]
%\hphantom{\caption{Java operator precedence and associativity table.\index{precedence table}}}
\TBT{0pc}{Java operator precedence and associativity table.}
\hspace*{-6pt}\begin{tabular}{clll}
\multicolumn{4}{l}{\color{cyan}\rule{29pc}{1pt}}\\[2pt]
%%%%\TBCH{{\bf Order}} & \TBCH{{\bf Operator}} & \TBCH{{\bf Operation}} & \TBCH{{\bf Association}}
{\bf Order} & {\bf Operator} & {\bf Operation} & {\bf Association}
\\[-4pt]\multicolumn{4}{l}{\color{cyan}\rule{29pc}{0.5pt}}\\[2pt]
0 &\verb|(  )|&{\it Parentheses}\cr
1 &\verb|++   -- |$\;\cdot$&{\it Postincrement,  Postdecrement, Dot Operator}&{\it L to R}\cr
2 &\verb|++   --  +  -  !|&{\it Preincrement,  Predecrement, }&{\it R to L}\cr
  &&{\it Unary plus,  Unary minus,  Boolean NOT}&\cr
3 &\verb|(type)  new|&{\it Type  Cast, Object Instantiation}&{\it R to L}\cr
4 &\verb|*  /  %|&{\it Multiplication,  Division,  Modulus}&{\it L to R}\cr
5 &\verb|+ -  +|&{\it Addition,  Subtraction,  String Concatenation}&{\it L to R}\cr
6 &\verb|<  >  <=  >=|&{\it Relational  Operators}&{\it L to R}\cr
7 &\verb|==   !=|&{\it Equality  Operators}&{\it L to R}\cr
8 &$\wedge$&{\it Boolean  XOR}&{\it L to R}\cr
9 &\verb|&&|&{\it Boolean  AND}&{\it L to R}\cr
10&\verb||||&{\it Boolean  OR}&{\it L to R}\cr
11&\verb|= += -= *= /= %=|&{\it Assignment  Operators}&{\it R to L}
\\[-4pt]\multicolumn{4}{l}{\color{cyan}\rule{29pc}{1pt}}
\end{tabular}
\endTB
\end{table}

\noindent  In this case, each variable will be assigned 100 as its
value.  But it's important that this expression be evaluated from right
to left.  First, {\it k} is assigned 100. Then its value is assigned
to {\it j}. And finally {\it j}'s value is assigned to {\it i}.

For expressions containing mixed operators, it's always a good idea to
use parentheses to clarify the order of evaluation.  This will also
help avoid subtle syntax and semantic errors.