%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% UMB-CS240-2016S: Programming in C
% Copyright 2016 Pejman Ghorbanzade <pejman@ghorbanzade.com>
% Creative Commons Attribution-ShareAlike 4.0 International License
% More info: https://github.com/ghorbanzade/UMB-CS240-2016S
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\section*{Question 2}

Edgar Linton, a CS240 student, was asked to write a program that promps user for an integer and prints it on the screen.
A sample run of the program was expected to be as given below.

\begin{terminal}
$ gcc prompt-number.c -o prompt-number
$ ./prompt-number
enter number: 125
number: 125
\end{terminal}

To solve this problem, he wrote the following program.

\lstset{language=c,tabsize=4}
\begin{lstlisting}
// Edgar Linton
// <edgar.linton001@umb.edu>

#include <stdio.h>
#define MAX_LENGTH 32

int main(void)
{
	int num = getNum();
	printf("%d\n", num);
}

int getNum(void)
{
	int res;
	char ch;
	int i = 0;
	char array[MAX_LENGTH];
	while ((ch = getchar()) != '\n')
		array[i] = ch;
	i = 0;
	while (array[i] != '\0')
		res = res * 10 + array[i++] - '0';
	return res;
}
\end{lstlisting}

His program produces the following output.

\begin{terminal}
$ gcc prompt-number.c -o prompt-number
$ ./prompt-number
enter number: 125
number: 971397989
\end{terminal}

Clearly, something is wrong with Edgar's code.
This is why he is asking for your help to debug his program and fix all its bugs.
Rewrite the program \texttt{prompt-number.c} such that its output matches the expected output provided previously.


% =================================================================================================
% - this is the universal syntax of a LaTeX command: \command[options]{values}
% - in Ubuntu, installing texlive-full would provide all packages available
% =================================================================================================

% 1. set the document class
\documentclass[11pt]{article}  % article/book/letter/report/...

% 2. set the preamble
\usepackage{palatino}    % this is my favorite font
% \usepackage{tgpagella}   % this font looks similar but it doesn't apply to embedded code blocks

\usepackage{amsmath}     % for math equations
\usepackage{amssymb}     % font and typeface for math
\usepackage{mathpazo}    % font and typeface for math, this is my favorite

\usepackage{graphicx}    % for handling figures
\usepackage{subcaption}  % for handling subfigures
\usepackage{float}       % for setting the float (for strict figure positioning)

\usepackage{setspace}    % package that allows us to set the spacing for individual parts of the document

\usepackage{hyperref}    % for hyperlinks

\usepackage{listings}    % package that allows code in the document and offers source code highlighting
\usepackage{color}       % support colors in source code highlighting

\definecolor{darkgreen}{rgb}{0,0.6,0}  % define custom colors for later use in the document
\definecolor{gray}{rgb}{0.5,0.5,0.5}
\definecolor{mauve}{rgb}{0.58,0,0.82}

\usepackage{longtable}   % for multipage tables
\usepackage{booktabs}    % for prettier tables
\usepackage{multirow}    % enable a table cell to span multiple rows or multiple columns
\usepackage{siunitx}     % for numbers in a table column to be aligned at the decimal point, formatting unit and style...
\sisetup{                % specify how many decimal places should be displayed
  round-mode = places,   % round numbers
  round-precision = 2,   % to 2 decimal places
}

\usepackage[backend=bibtex,style=musuos]{biblatex}  % include biblatex, specify bibtex as the backend, and choose a style
\bibliography{latex}  % specify the bibliography database file, the .bib extension must be omitted

\title{LaTeX notebook}   % set up values for \maketitle for later use
\date{\today}            % or hard-code a date value
\author{Wentao Lu}

\setcounter{tocdepth}{2} % set the depth of table of contents(TOC)
                         % depth 1 will show only sections
                         % depth 2 will show sections and subsections
                         % depth 3 will show sections and subsections and subsubsections
                         % depth 4 = depth 3 + paragraphs
                         % depth 5 = depth 4 + subparagraphs

\lstset{  % this command predefines the default source code style settings all at once, here's a template from wikipedia
          % if we have many code blocks, each block can have its own formatting commands that override this setting
  language=c++,                             % the language of the code
  numbers=left,                             % where to put the line-numbers
  numberstyle=\tiny\color{gray},            % style of the line-numbers. \footnotesize\color{darkgray} is smaller
  stepnumber=1,                             % the step between two line-numbers. if set to 1, each line will be numbered
  numbersep=5pt,                            % how far the line-numbers are from the code
  backgroundcolor=\color{white},            % background color. \color[RGB]{245,245,244} is a little bit darker than white
  showspaces=false,                         % if set to true, underscores will be shown to indicate spaces
  showstringspaces=false,                   % if set to true, underscores will be shown to indicate spaces within strings
  showtabs=false,                           % if set to true, underscores will be shown to indicate tabs within strings
  frame=single,                             % add a frame around the code, if set to none, no frame will be displayed
  rulecolor=\color{black},                  % frame-color
  tabsize=4,                                % set default tabsize to 4 spaces
  captionpos=b,                             % set the caption-position to bottom
  breaklines=true,                          % set automatic line breaking
  breakatwhitespace=false,                  % set if automatic breaks should only happen at whitespace
  title=\lstname,                           % show the filename of the script included with \lstinputlisting
  keywordstyle=\color{blue},                % keyword style. \color[RGB]{40,40,255} is dark blue
  escapeinside={\%*}{*)},                   % if you want to add LaTeX within your code
  morekeywords={*,...},                     % if you want to add more keywords to the set
  basicstyle=\ttfamily\footnotesize,        % source code style
  commentstyle=\ttfamily\color{darkgreen},  % comment style. \it\color[RGB]{0,96,96} is italic dark green
  stringstyle=\ttfamily\color{mauve}        % string literal style. also try \rmfamily\slshape\color[RGB]{128,0,0}
}

% 3. structure the document

\begin{document}  % a \begin and \end statement defines an environment
                  % the "document" environment is always the topmost environment

  \pagenumbering{gobble}  % by convention, we suppress the page number in title and table of contents pages

  \maketitle  % create a titlepage defined in the preamble
  \newpage

  \doublespacing    % before generating TOC pages, set the spacing to double (double spacing TOC looks better)
  \tableofcontents  % create table of contents pages based on the section and subsection headings in the document
  \newpage          % to see the TOC displayed, we need to compile the .tex file twice

  \singlespacing    % after TOC pages are generated, reset the spacing back to single

  \pagenumbering{roman}   % pages should only be numbered after the titlepage and TOC. i,ii,iii,iv,v...
  \pagenumbering{Roman}   % I,II,III,IV,V...
  \pagenumbering{arabic}  % 1,2,3,4,5...

  % ------------------------------------ 1 -------------------------------------
  \section{Section 1: a sample hierarchical structure}
    Sections are numbered and will appear in the table of contents.

    \subsection{Subsection 1}
      Subsections are also numbered and will appear in the table of contents.

      \subsubsection{Subsubsection 1}
        And so forth...

        \paragraph{Paragraph 1}
        Paragraphs aren not numbered and won't show in the table of contents. Here this paragraph is given a name.\\

        By contrast, this paragraph is \textbf{not} given a name, it's an \textit{anonymous} paragraph. In practice, paragraphs do not need names unless we are writing math papers or technical documentation. It's also somewhat clumsy to start a new paragraph with \textit{\textbackslash paragraph\{\}} unless our sections and paragraphs are very deeply nested. More often, we can simply place a newline command \textit{\textbackslash newline} or \textit{\textbackslash \textbackslash} at the end of the previous paragraph.\\

        LaTeX will automatically indent the first line of each paragraph that doesn't immediately follow a section heading. Indeed, this format looks better.\\

        \noindent If you'd like to get rid of an indent anyway, use the \textit{\textbackslash noindent} command to start a paragraph, but this format does not look pretty and is not recommended since it breaks the default class structure.

  % ------------------------------------ 2 -------------------------------------
  \section{Math}
    There are two major modes of typesetting math in LaTeX one is embedding the math directly into your text by encapsulating your formula in dollar signs and the other is using a predefined math environment.

    % --------------------------------- 2.1 ---------------------------------
    \subsection{Using inline math - embed formulas in your text}
      If you need to typeset a single math symbol or formula, surround it with dollar signs: this formula $f(x) = x^2$ is an example.

    % --------------------------------- 2.2 ---------------------------------
    \subsection{The \textit{equation} and \textit{align} environment}
      The most useful math environments are the \textit{equation} environment for typesetting single equations and the \textit{align} environment for multiple equations and automatic alignment. These two environments also take care of equation numbers for us.\\

      The automatic numbering is a useful feature, but sometimes it's necessary to remove them for auxiliary calculations. LaTeX doesn't allow this by default, but we can include a package called \textit{amsmath} and add a * after the environment name. The asterisk (e.g. equation*, align*) only indicates, that I don't want the equations to be numbered. Note that it is not possible to enter two equations in a single \textit{equation} environment, it will result in a compilation error.

      \begin{equation}  % inside "document", multiple environments can be nested
        f(x) = x^2
      \end{equation}
      \begin{equation*}
        f(x) = x^3 + 3x + 13
      \end{equation*}

      The \textit{align} environment will align the equations at the ampersand \&. While it is possible to enter many equations in a single \textit{align} environment, different equations have to be separated by a linebreak \textbackslash \textbackslash. There is no alignment when using the simple \textit{equation} environment.

      \begin{align*}
        1 + 2 &= 3\\
        1 &= 3 - 2
      \end{align*}

    % --------------------------------- 2.3 ---------------------------------
    \subsection{Mathematical notation examples}
      All mathematical expressions have a unique command with unique syntax.

      \begin{align*}
        g(x) &= \frac{1}{x}\\              % \frac{u}{v} for fractions
        a(x) &= \int^a_b \frac{1}{3}x^3\\  % \int^a_b for integral symbol
        b(x) &= \frac{1}{\sqrt{x}}         % \sqrt{x} for square roots
      \end{align*}

      Use the \textit{matrix} environment to typeset matrices. \left[\begin{matrix}1 & 0\\0 & 1\end{matrix}\right]

      Scale parentheses with \textbackslash \textit{left}( \textbackslash \textit{right}) automatically. \left(\frac{1}{\sqrt{x}}\right)

  % ------------------------------------ 3 -------------------------------------
  \section{Images and figures}

    % --------------------------------- 3.1 ---------------------------------
    \subsection{Captioned images and figures}
      The \textit{figure} environment takes care of the numbering and positioning of the image within the document. All figures will be indexed automatically and tagged with successive numbers when using the \textit{figure} environment and the \textit{graphicx} package.\\

      At some point, you will notice that the figure doesn't necessarily show up in the exact place as you put your code in the .tex file. If your document contains a lot of text, it's possible that LaTeX will put the figure on the next page, or any other page where it finds sufficient space. To prevent this behavior, it's necessary to set the \textit{float} value for the \textit{figure} environment. Possible \textit{float} values are:

      \begin{itemize}
      	\item h (here) - same location
      	\item t (top) - top of page
      	\item b (bottom) - bottom of page
        \item p (page) - on an extra page
        \item ! (override) - will force the specified location
      \end{itemize}

      \begin{figure}[H]  % [h!] forces the figure to be shown here in the document, [H] is even stricter
        \includegraphics[width=\linewidth]{support/sample.JPG}  % the figure will be scaled to fit \linewidth
        \caption{This is a sample image.}  % caption of the figure is the text shown below the figure
        \label{f1}  % define a label for this figure, then later we can use \ref{f1} to reference it
      \end{figure}

    % --------------------------------- 3.2 ---------------------------------
    \subsection{Multiple images and subfigures}
      The \textit{subfigure} environment allows you to place multiple images at a certain location next to each other and the usage is pretty straightforward.\\

      First, we need to include the \textit{subcaption} package to the preamble. Next, we need to add multiple \textit{subfigure} environments within a \textit{figure} environment. Note that we must manually set the width of the image. If there are two images aligned next to each other, their widths should both be set to 0.4, but they still fill up the whole space. In such cases, we should always set the width to .1 less than we expect.

      \begin{figure}[h!]
        \centering
        \begin{subfigure}[h]{0.4\linewidth}  % must set the width of the image manually
          \includegraphics[width=\linewidth]{support/coffee.jpg}
          \caption{Coffee.}
        \end{subfigure}
        \begin{subfigure}[h]{0.4\linewidth}  % must set the width of the image manually
          \includegraphics[width=\linewidth]{support/coffee.jpg}
          \caption{More coffee.}
        \end{subfigure}
        \caption{Two cups of coffee next to each other.}
        \label{f2}
      \end{figure}

      Likewise, if there are three images aligned next to each other, we should consecutively add three subfigures, each with a 0.2 \textit{\textbackslash linewidth} (1/3 - 0.1 = 0.2).

      \begin{figure}[h!]
        \centering
        \begin{subfigure}[h]{0.2\linewidth}
          \includegraphics[width=\linewidth]{support/coffee.jpg}
          \caption{Coffee.}
        \end{subfigure}
        \begin{subfigure}[h]{0.2\linewidth}
          \includegraphics[width=\linewidth]{support/coffee.jpg}
          \caption{More coffee.}
        \end{subfigure}
        \begin{subfigure}[h]{0.2\linewidth}
          \includegraphics[width=\linewidth]{support/coffee.jpg}
          \caption{Tasty coffee.}
        \end{subfigure}
        \begin{subfigure}[h]{0.5\linewidth}  % 0.5 cannot fit on this row, so it goes to the next row
          \includegraphics[width=\linewidth]{support/coffee.jpg}
          \caption{Too much coffee.}
        \end{subfigure}
        \caption{The same cup of coffee. Multiple times.}
        \label{f3}
      \end{figure}

  % ------------------------------------ 4 -------------------------------------
  \section{Bibliography}
    For simplicity, better compatibility and maintainability, it is recommended that we use \textit{bibtex} and \textit{biblatex} to create the bibliography. Briefly speaking, \textit{bibtex} is an external program that processes bibliography information in your .bib file, while \textit{biblatex} is a LaTeX package that formats citations and bibliographies. In other words, \textit{bibtex} reads input from our database (i.e. the .bib file) and transforms that .bib file into a .tex understandable one, and then, the LaTeX package \textit{biblatex} gives us access to use citing commands and display our bibliography in the final output .pdf file, this is how the pipeline works in general, despite that the real workflow is much more complicated.\\

    Alternatively, we also have some other choices such as \textit{biber} and \textit{natlib}, which are not in the scope of this notebook. For those who are interested, \href{https://tex.stackexchange.com/questions/25701/bibtex-vs-biber-and-biblatex-vs-natbib}{this post} contains a detailed introduction and comparison between all these tools.

    % --------------------------------- 4.1 ---------------------------------
    \subsection{Creating a .bib file}
      First we have to create a .bib file (bibliography database), which contains our bibliographic information. Here we have some examples.

      \lstinputlisting{latex.bib}

      Now let's closely look at the reference blocks in our .bib file and explain each field. There are three mandatory fields for all document classes. Be it an article, a book or an incollection, we must have the \textbf{author, year, title} fields. The string on the first line after \{ is a label that we use to refer to the item when we cite it. Inside the \textbf{author = \{\}} braces is the list of authors connected by "and", not by commas. Here commas are used to separate different parts of an author's name, where we should write in the form of "last name, first name". Inside the \textbf{title = \{\}} braces is the title of the reference, without quotation marks. For the \textbf{year} field, it must consist of only digits, and the braces around it can be omitted. All other fields are somewhat self-explanatory so we won't bother to cover them.\\

      For an article, we must also specify the \textbf{journal} field. For a book, the \textbf{publisher} field is also mandatory. Besides, the \textbf{author} field can also be replaced by an \textbf{editor} field, either of the two must be specified. For an incollection document class, fields \textbf{booktitle} and \textbf{publisher} are both mandatory. Likewise, \textbf{booktitle} is mandatory for inproceedings, \textbf{institution} is mandatory for techreport, and \textbf{note} is mandatory for unpublished document class.\\

      Inside each reference block structure, the order of the fields is unimportant. Our .bib file can contain references we don't cite. \textit{bibtex} will put in the list of references at the end of our paper only the ones that we cite.

    % --------------------------------- 4.2 ---------------------------------
    \subsection{Reading database and formatting references}
      Next, in the preamble we have to include the \textit{biblatex} package, specify \textit{bibtex} as the backend engine, choose a bibliographic formatting style, and then use the command \textit{\textbackslash bibliography} to tell LaTeX the location of our .bib file. Anywhere within the document, we can cite references using \textit{\textbackslash cite} and \textit{\textbackslash autocite}.\\

      For example, this is a citation \autocite{ab94} which is numbered and appears in the footnotes, and this is a citation whose full text description is directly embedded in the paragraph but does not appear in the footnotes: \cite{ahu61}.\\

      Here's another citation \autocite[32-35]{fk1988}  % we can specify page numbers in brackets as an option
      for which we have also specified the page numbers.\\

      Then, at the end of the document, we can use \textit{\textbackslash printbibliography} to create a separate reference page which will list all citations that have been cited.\\

      Finally, it's worth mentioning that there are many bibliography styles that we can use when we include the package \textit{biblatex}. \href{https://www.overleaf.com/learn/latex/Biblatex_bibliography_styles}{This post} has listed some of the most commonly used styles, with sample snapshots of how they look like. It is noteworthy that for different styles, the behaviors of the citing commands we mentioned above are also different. For some styles, the reference page could be empty, or the citation full text cannot be embedded. This is just a tutorial notebook, but when we write a formal paper, we should always stick to the style that is required by the university department.

  % ------------------------------------ 5 -------------------------------------
  \section{Footnotes}
    Footnotes are numbered automatically. For example, we can create a footnote of what coursera\footnote{\label{coursera}An American online learning platform founded by Stanford professors Andrew Ng and Daphne Koller that offers massive open online courses (MOOC), specializations, and degrees.} is, and later refer to it as footnote \ref{coursera}.

  % ------------------------------------ 6 -------------------------------------
  \section{Tables}
    Tables in LaTeX can be created through a combination of the \textit{table} environment and the \textit{tabular} environment. The \textit{table} environment part contains the caption and defines the float for our table, i.e. where in our document the table should be positioned and whether we want it to be displayed centered. The \textit{\textbackslash caption} and \textit{\textbackslash label} commands can be used in the same way as for pictures. The actual content of the table is contained within the \textit{tabular} environment.\\

    The \textit{tabular} environment uses ampersands \& to separate columns and newline symbol \textit{\textbackslash \textbackslash} to separate rows. A horizontal line can be added with the \textit{\textbackslash hline} command. Within a column, if we want to have numbers aligned at the decimal point, we can include the \textit{siunitx} package for this purpose, and setup the alignment using \textit{\textbackslash sisetup}.

    % --------------------------------- 6.1 ---------------------------------
    \subsection{A simple table}
      This is a simple table that works but is not very readable.

      \begin{table}[h!]
        \begin{center}
          \caption{A simple table.}
          \label{t1}
          \begin{tabular}{l|c|r}  % 1st column left-aligned, 2nd centered, 3rd right-aligned, with vertical lines in between
            \textbf{Value 1} & \textbf{Value 2} & \textbf{Value 3} \\  % 1st row
            $\alpha$         & $\beta$          & $\gamma$ \\          % 2nd row
            \hline  % row separator --------------------------------------------
            1                & 110.1            & a\\                  % 3rd row
            2                & 10.1             & b\\                  % 4th row
            3                & 23.113231        & c\\                  % 5th row
          \end{tabular}
        \end{center}
      \end{table}

      \begin{table}[h!]
        \begin{center}
          \caption{A simple table - numbers aligned.}
          \label{t2}
          \begin{tabular}{l|S|r}  % here "S" means: align the 2nd column as specified by \sisetup
            \textbf{Value 1} & \textbf{Value 2} & \textbf{Value 3} \\
            $\alpha$         & $\beta$          & $\gamma$ \\
            \hline
            1                & 110.1            & a\\
            2                & 10.1             & b\\
            3                & 23.113231        & c\\
          \end{tabular}
        \end{center}
      \end{table}

    % --------------------------------- 6.2 ---------------------------------
    \subsection{Cells spanning multiple rows or multiple columns}
      Sometimes it's necessary to make a row or column span several cells. For this purpose we can use the \textit{multirow} package. This package allows us to use the \textit{multirow} and \textit{multicolumn} environments, which make it easy to create a cell spanning multiple rows or columns.\\

      \begin{table}[h!]
        \begin{center}
          \caption{Multirow table.}
          \label{t3}
          \begin{tabular}{l|S|r}
            \textbf{Value 1}    & \textbf{Value 2} & \textbf{Value 3} \\
            $\alpha$            & $\beta$          & $\gamma$ \\
            \hline
            \multirow{2}{*}{12} & 1110.1           & a\\   % \multirow{number_of_rows}{width}{content}, "*" means automatic
                                & 10.1             & b\\   % the first column is omitted due to multirow
            \hline
            3                   & 23.113231        & c\\
            4                   & 25.113231        & d\\
          \end{tabular}
        \end{center}
      \end{table}

      If we want a cell to span multiple columns, we have to use the \textit{multicolumn} command. The usage differs a bit from \textit{multirow} command, since we also have to specify the alignment for our column. For example, in the row where we have a cell that spans two columns, there's only one column separator \& (instead of two for all other rows).\\

      \begin{table}[h!]
        \begin{center}
          \caption{Multicolumn table.}
          \label{t4}
          \begin{tabular}{l|S|r}
            \textbf{Value 1} & \textbf{Value 2} & \textbf{Value 3} \\
            $\alpha$         & $\beta$          & $\gamma$ \\
            \hline
            \multicolumn{2}{c|}{12}             & a\\  % combine two cells with alignment {c|} and content 12.
            \hline
            2                & 10.1             & b\\
            3                & 23.113231        & c\\
            4                & 25.113231        & d\\
          \end{tabular}
        \end{center}
      \end{table}

      Of course it's also possible to combine the two features, to make a cell spanning multiple rows and columns. To do this, we simply nest the \textit{multirow} command inside the \textit{multicolumn} command. The trick here is that, we have to add another \textit{multicolumn} statement for as many rows as we're combining.

      \begin{table}[h!]
        \begin{center}
          \caption{Multirow and -column table.}
          \label{t5}
          \begin{tabular}{l|S|r}
            \textbf{Value 1} & \textbf{Value 2}        & \textbf{Value 3} \\
            $\alpha$         & $\beta$                 & $\gamma$ \\
            \hline
            \multicolumn{2}{c|}{\multirow{2}{*}{1234}} & a\\  % \multirow serves as the content of \multicolumn
            \multicolumn{2}{c|}{}                      & b\\  % * empty \multicolumn statement serves as a placeholder
            \hline
            3                & 23.113231               & c\\
            4                & 25.113231               & d\\
          \end{tabular}
        \end{center}
      \end{table}

    % --------------------------------- 6.3 ---------------------------------
    \subsection{Prettier tables with booktabs}
      The \textit{booktabs} package provides much prettier horizontal separators. We can replace \textit{\textbackslash hline} with \textit{\textbackslash toprule}, \textit{\textbackslash midrule} and \textit{\textbackslash bottomrule}.

      \begin{table}[H]
        \begin{center}
          \caption{Table using booktabs.}
          \label{t6}
          \begin{tabular}{c|S|c}
            \toprule  % -----------------------------------------------
            \textbf{Value 1} & \textbf{Value 2} & \textbf{Value 3} \\
            $\alpha$         & $\beta$          & $\gamma$ \\
            \midrule  % -----------------------------------------------
            1                & 110.1            & a\\
            2                & 10.1             & b\\
            3                & 23.113231        & c\\
            \bottomrule  % --------------------------------------------
          \end{tabular}
        \end{center}
      \end{table}

    % --------------------------------- 6.4 ---------------------------------
    \subsection{Multipage tables}
      If you have a lot of rows in your table, you will notice that by default, the table will be cropped at the bottom of the page, which is certainly not what you want. The package \textit{longtable} provides a convenient way, to make tables span multiple pages. It's actually easier to use this package since the \textit{longtable} environment combines the previous \textit{table} and \textit{tabular} environment into a single environment. Using this environment, we create a table, that is automatically split between pages, if it has too many rows.

      \begin{longtable}[c]{c|S|c|c|c}  % \begin{longtable}[position_on_page]{alignment}
        \caption{Multipage table.}
        \label{t7}\\
        \toprule
        \textbf{Value 1} & \textbf{Value 2} & \textbf{Value 3} & \textbf{Value 4} & \textbf{Value 5} \\
        $\alpha$         & $\beta$          & $\gamma$         & $\epsilon$       & $\eta$           \\
        \midrule
        \endfirsthead    % end of the first header, which will be shown on the first page only

        % in between \endfirsthead and \endhead is the subsequent header
        \toprule
        \textbf{Value 6} & \textbf{Value 7} & \textbf{Value 8} & \textbf{Value 9} & \textbf{Value 0} \\
        $\delta$         & $\theta$         & $\lambda$        & $\kappa$         & $\psi$           \\
        \midrule

        \endhead         % end of the subsequent header, which will be shown on every page except the first page
        10               & 110.1            & a63              & apple            & orange \\
        29               & 10.1             & b73              & apple            & orange \\
        38               & 23.113231        & c65              & apple            & orange \\
        47               & 523.1            & a98              & apple            & orange \\
        56               & 120.12           & b15              & apple            & orange \\
        65               & 3.72             & c35              & apple            & orange \\
        74               & 46.18            & a90              & apple            & orange \\
        83               & 14.0             & b34              & apple            & orange \\
        92               & 9.135            & c72              & apple            & orange \\
        01               & 532.24           & a84              & apple            & orange \\
        10               & 110.1            & a56              & apple            & orange \\
        29               & 10.1             & b38              & apple            & orange \\
        38               & 23.113231        & c93              & apple            & orange \\
        47               & 523.1            & a54              & apple            & orange \\
        56               & 120.12           & b66              & apple            & orange \\
        65               & 3.72             & c86              & apple            & orange \\
        74               & 46.18            & a33              & apple            & orange \\
        83               & 14.0             & b26              & apple            & orange \\
        92               & 9.135            & c18              & apple            & orange \\
        01               & 532.24           & a27              & apple            & orange \\
        10               & 110.1            & a58              & apple            & orange \\
        29               & 10.1             & b88              & apple            & orange \\
        38               & 23.113231        & c94              & apple            & orange \\
        47               & 523.1            & a56              & apple            & orange \\
        56               & 120.12           & b00              & apple            & orange \\
        \bottomrule
      \end{longtable}

    % --------------------------------- 6.5 ---------------------------------
    \subsection{Generating tables from .csv files}
      When writing papers, it is sometimes necessary to present a large amount of data in tables. Writing such tables by hand is very time-consuming and error-prone. To avoid this, we can simply import the data directly from .csv (comma-separated value) files. For this purpose, we can use the \textit{pgfplotstable} package. Similarly, there's also a package called \textit{pgfplots} for automatic plot generation from .csv files. However, this notebook will not cover them here because such cases are rare. It's not useful to learn about the redundant features since we already have better tools such as Python for tackling with these tasks. The point is, for whatever task we have, wisely choose the most appropriate toolbox.

  % ------------------------------------ 7 -------------------------------------
  \section{Source code}
    The required packages and settings have already been setup in the preamble part, and the comments should be self-explanatory. To actually insert source code in the document, there are mainly two ways. One way is to directly copy and paste source code into the \textit{lstlisting} environment, but indentation could be troublesome since it will not ignore the indentation and spaces in the .tex file. As an alternative, it's preferable to use the \textit{\textbackslash lstinputlisting} command, which is able to read in a source code script file and outputs it to the .pdf, without messing up with our .tex file.\\

    \begin{lstlisting}[language=python]
      # indentation from the .tex file not ignored
      # when we directly copy and paste code
      @functools.singledispatch
      def show(obj):
          print(obj, type(obj), "obj")
    \end{lstlisting}

    \lstinputlisting{support/HelloWorld.cpp}  % \lstlinputlisting{filename}

  % ------------------------------------ 8 -------------------------------------
  \section{Hyperlinks}
    We can use the \textit{hyperref} package which allows us to set links with a description as well as add bare urls to the document. After the hyperlink is inserted, if there's a colored box shown around the word. Don't worry, this box is not going to show up in our printed document, but only if we view it on the computer.\\

    This is my homepage: \href{https://github.com/neo-mashiro}{neo-mashiro}.\\

    A bare URL without an description: \url{https://github.com/neo-mashiro}.\\

    My email address is: \href{mailto:neo-mashiro@hotmail.com}{neo-mashiro@hotmail.com}.

  % ------------------------------------ 9 -------------------------------------
  \section{Lists}
    Unordered lists use the \textit{itemize} environment.

    \begin{itemize}
      \item One
      \item Two
      \item Three
    \end{itemize}

    \noindent Ordered lists use the \textit{enumerate} environment.

    \begin{enumerate}
      \item One
      \item Two
      \item Three
    \end{enumerate}

    \noindent Nested lists are the products of nested list environments.

    \begin{enumerate}
      \item One
      \begin{enumerate}
      	\item Two
        \item Three
      \end{enumerate}
      \item Four
    \end{enumerate}

    \noindent It's easy to change the numbering scheme or the bullets of a list.

    \begin{itemize}
      \item[--] Dash
      \item[$-$] Dash
      \item[$\ast$] Asterisk
    \end{itemize}

  % ------------------------------------ appendix ------------------------------------
  \newpage
  \begin{appendix}  % after all sections, before references, is the appendix
    \listoffigures  % compile twice to generate the lists, same as TOC
    \listoftables   % compile twice to generate the lists, same as TOC
  \end{appendix}

  % ----------------------------------- references -----------------------------------
  \newpage
  \printbibliography

\end{document}


% !TEX options=--shell-escape
\documentclass [12pt]{article}

\usepackage {amsmath}
\usepackage {amsthm}
\usepackage {amssymb}
\usepackage {graphicx}
\usepackage {float}
\usepackage {multirow}
\usepackage {xcolor}
\usepackage {algorithmic}
\usepackage [ruled,vlined,commentsnumbered,titlenotnumbered]{algorithm2e} \usepackage {array}
\usepackage {booktabs}
\usepackage {url}
\usepackage {parskip}
\usepackage [margin=1in]{geometry}
\usepackage [T1]{fontenc}
\usepackage {cmbright}
\usepackage [many]{tcolorbox}
\usepackage [colorlinks = true,
            linkcolor = blue,
            urlcolor  = blue,
            citecolor = blue,
            anchorcolor = blue]{hyperref}
\usepackage {enumitem}
\usepackage {xparse}
\usepackage {verbatim}
\usepackage{listings}
\usepackage{xcolor}
\usepackage{csquotes}
\usepackage[cache=false]{minted}
\usepackage{mdframed}
\usepackage{tikz}
\usetikzlibrary{shapes.symbols}
\newtheorem{theorem}{Theorem}

\BeforeBeginEnvironment{minted}{\begin{mdframed}}
\AfterEndEnvironment{minted}{\end{mdframed}}

\DeclareTColorBox {Solution}{}{breakable, title={Solution}}
\DeclareTColorBox {Solution*}{}{breakable, title={Solution (provided)}}
\DeclareTColorBox {Instruction}{}{boxrule=0pt, boxsep=0pt, left=0.5em, right=0.5em, top=0.5em, bottom=0.5em, arc=0pt, toprule=1pt, bottomrule=1pt}
\DeclareDocumentCommand {\Expecting }{+m}{\textbf {[We are expecting:} #1\textbf {]}}
\DeclareDocumentCommand {\Points }{m}{\textbf {(#1 pt.)}}
\newcommand {\hint }[1]{\noindent {[\textbf {HINT:} \em #1 \em ]}} \newcommand {\pts }[1]{\textbf {(#1 pt.)}}

\begin{document}

{\LARGE \textbf {COMP 285 (NC A\&T, Spr `22)}\hfill \textbf {Homework 5} }
\vspace {1em}
\begin{Instruction}

\paragraph {Due.} Friday, February 25th, 2022 @ 11:59 PM!
\end{Instruction}

\vspace {1em}
\begin{Instruction} \paragraph {Homework Expectations:} Please see \href{https://www.comp285.ml/homework/#general-homework-information}{Homework}.
\end{Instruction}

\vspace {1em}
\begin{Instruction}

\paragraph {Exercises} The following questions are exercises. We encourage you to work with a group and discuss solutions to make sure you understand the material.

\paragraph {Points} This assignment is graded out of 100 points. However, you can get up to 120 points if you complete everything. These are not bonus points, but rather points to help make-up any parts you miss.

\end{Instruction}

\begin{centering}
\section*{Fun with Data Structures and Hashing}
\end{centering}

\begin{Instruction}

\paragraph{Written Problems} The following questions are to be submitted in written/typed form to gradescope.

\end{Instruction}

\section{Interview Practice: Moose Tree \Points {20}}

A moose comes to you with the following claim. They say that they have come up with a new kind of binary search tree, called \texttt{mooseTree}, even better than red-black trees!

More precisely, \texttt{mooseTree} is a data structure that stores comparable elements in a binary search tree. It might also store other auxiliary information, but the moose won't tell you how it works. The moose claims that \texttt{mooseTree} supports the following operations:

\begin{itemize}
    \item \texttt{mooseInsert(k)} inserts an item with key $k$ into the \texttt{mooseTree}, maintaining the BST property. It does not return anything. It runs in time $O(1)$.
    \item \texttt{mooseSearch(k)} finds and returns a pointer to node with key $k$, if it exists in the tree. It runs in time $O(\log (n))$.
    \item \texttt{mooseDelete(k)} removes and returns a pointer to an item with key $k$, if it exists in the tree, maintaining the BST property. It runs in time $O(\log (n))$.
\end{itemize}

Above, $n$ is the number of items stored in the \texttt{mooseTree}. The moose says that all these operations are deterministic, and that \texttt{mooseTree} can handle arbitrary comparable objects.

\subsection{Making Moose Trees \Points{8}}

You want to get a better understanding of the \texttt{mooseTree}. To do so, you think it'd be helpful to write an algorithm that takes as input a vector of unsorted elements and creates a mooseTree using the methods above.

We'll get you started.
\begin{verbatim}
algorithm makeMooseTree(A):
    // Input: A is a vector of n comparable elements.
    T = mooseTree() // creates an empty mooseTree.
    // FILL THIS IN.
    return T
\end{verbatim}

\Expecting{Completed pseudocode for the algorithm, the running time in $O(\cdots)$, and a short explanation justifying the running time.}

\subsection{From Moose Trees to Sorted Vectors \Points{8}}

Now that you understand how to make \texttt{mooseTree}s, you consider the opposite. How can you go from a \texttt{mooseTree} to an \textbf{sorted} vector?\footnote{If you're having trouble, take a look at Lecture 12, Slides 15-27}

We'll get you started \footnote{Since the \texttt{mooseTree} is still a kind of binary search tree, you can access the root of \texttt{mooseTree} by calling \texttt{mooseTree.root()}.}.
\begin{verbatim}
algorithm getElements(T, A):
    // Input: T is a mooseTree with n elements.
    // Input: A is the vectors where we should add elements into.

    // FILL THIS IN.
\end{verbatim}

\Expecting{Completed pseudocode for the algorithm, the running time in $O(\cdots)$, and a short explanation justifying the running time.}

\subsection{Wait a second... \Points{4}}
You think the moose's logic is a bit loosey-moosey. How do you know the moose is wrong?

\textbf{Notes:}
\begin{itemize}
    \item You may use results or algorithms that we have seen in class without further justification.
    \item Proofs that just say "since it's impossible to do these operations that fast in BST, this data structure can't exist" is not sufficient.
\end{itemize}

\Expecting {Use the results from the sections above (as well as results from class) to write a short explanation as to why the Moose is wrong.}

\pagebreak
\section{Interview Practice: Wise Duck \Points{20}}

A wise duck has knowledge of an array $A$ of length $n$, so that $A[i] \in \{1,\ldots ,k\}$ for all $i$ (note that the elements of $A$ are not necessarily distinct). You don't have direct access to the list, but you can ask the wise duck \em any \em yes/no questions about it. For example, you could ask ``If I remove $A[5]$ and swap $A[7]$ with $A[8]$, would the array be sorted?'' or ``are ducks related to grebes?''

This time you did bring a paper and pencil, and your job is to write down all of the elements of $A$ in sorted order.\footnote {Note that you don't have any ability to change the array $A$ itself, you can only ask the wise duck about it.} You are allowed to take all the time you need to do any computations on paper with the wise duck's answers, but the wise duck charges one bandito burrito per question.
\vspace {-.2cm}
\begin{center}
\begin{tikzpicture}
    \node (a) {
        \includegraphics [width=2cm]{alice}
    };
    \node (b) at (8,.5) {
        \includegraphics [width=2cm]{wiseduck}
    };
    \node [draw, cloud, cloud puffs=20.5, cloud ignores aspect,fill=white] at (11,2.5) {
        $A = [6,2,4,3,3,5,2,1,2,6]$
    };
    \node (c) at (3,2.8) {Is $7$ in the array?};
    \node (d) at (5,2) {\textbf {No.}};
    \node (e) at (3.5,1) {
        \begin{minipage}{3.5cm}
            \begin{center}
            Do duck quacks echo?
            \end{center}
        \end{minipage}
    };
    \node (f) at (4.5,-.2) {\textbf {Yes.}};
    \draw (c) -- (a);
    \draw (e) -- (a);
    \draw (d) -- (b);
    \draw (f) -- (b);
\end{tikzpicture}
\end{center}
\vspace {-.7cm}

Design an algorithm which outputs a sorted version of $A$ which uses $O(k\log n)$ badito burritos. You may assume that you know $n$ and $k$, although this is not necessary.

\Expecting{Pseudocode and a clear English explanation of what it is doing. An explanation of why the algorithm uses $O(k \log n)$ ice cream cones. You do not need to prove that your algorithm is correct.}

\hint{One approach is to think first about what you would do for $k=2$: that is, when $A$ contains only the numbers $1$ and $2$. What information do you need to write down a sorted version of $A$ in this case?}

\pagebreak
\section{Exercise: Hash Functions \Points{20}}
With 217 students currently enrolled in computer science\footnote{See \href{https://www.ncat.edu/coe/departments/cs/undergrad-programs/index.php}{here} if you'd like to see other years!} at North Carolina A\&T University, we would like to keep track of student records.

The key for each person will be their 9-digit Banner ID.

\subsection{Our own hash functions! \Points{10}}
Consider using a hash table of size $80$ and the hash function $h(N) =$ sum of each digits of $N$. For example, $h(012345678) = 0 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 = 36$.

Is this a good hash function to use? List two reasons supporting your decision.

\Expecting{The answer to whether this is a good hash function or not, and two reasons explaining why.}

\subsection{Good hash families \Points{10}}
Consider a hash table of $99$ buckets. For $m \in \{1, \cdots , 1000\}$, let $h_m(x) =$ last two digits of $mx$.  For example, $h_4(01234567)=$ last two digits of $4\times01234567=4938268 = 68$. Define $\mathcal{H} = \{h_i: i \in \{1, \cdots, 1000\}\}$.

Is $H$ a good family of hash functions? Justify your decision.

\Expecting{The answer to whether $\mathcal{H}$ is a good family of hash functions or not, and a brief justification.}

\section{Feedback: Homework Thoughts \Points{10}}

In order to improve the homework in future iterations, complete this \href{https://forms.gle/h3mZjdF4e1y4tXiZ8}{form}.

\Expecting{You should submit the form with your @aggies.ncat.edu email to track your submission.}

\pagebreak
\begin{Instruction}

\paragraph{Coding Problems} The following questions are to be submitted as a ".zip" file on Gradescope.

\end{Instruction}

\section{Coding \Points{50}}
After completing the written portion of the assignment, you should submit it to \href{https://www.gradescope.com/courses/350304}{Gradescope}.

For the coding portion, you can get your starter code for \href{https://replit.com/team/COMP285/HW5-Code}{C++} and \href{https://replit.com/team/COMP285/HW5-Code-Python}{Python}. You are welcomed to implement the solution in whichever language you prefer.

Note that the starter code also include a few test cases you can run on repl.it. However, the full test suite is the one run on Gradescope.

Please reference the \texttt{README.md} included in your starter code for detailed instructions.

\section*{Submitting the Assignment}

This assignment is a combination of written and programming questions. Both portions of the assignment should be submitted through \href{https://www.gradescope.com/courses/350304}{Gradescope}.

The "Homework 5: Fun with Data Structures and Hashing" assignment is the written portion, for which you should submit a \textbf{typed} response to the non-coding questions (questions 1-\ref{sec:last}). Each response should clearly be marked with its corresponding number. You are free to use the provided templates, print the questions and write your answers, or to simply type your responses on a blank document (whatever works for you).

The "Homework 5: Coding" is the programming portion of the assignment. For this portion, download the ".zip" file from replit and upload this ".zip" file as your answer to \href{https://www.gradescope.com/courses/350304}{Gradescope}. You can upload the assignment as many times as you want.

\end{document}


\section{CurryCheck: A Tool for Testing Properties of Curry Programs}
\label{sec-currycheck}

CurryCheck\index{CurryCheck}\index{testing programs}\index{program!testing}
is a tool that supports the automation of
testing Curry programs.
The tests to be executed can be unit tests as well as
property tests parameterized over some arguments.
The tests can be part of any Curry source program
and, thus, they are also useful to document the code.
CurryCheck is based on EasyCheck \cite{ChristiansenFischer08FLOPS}.
Actually, the properties to be tested are written
by combinators proposed for EasyCheck, which are actually
influenced by QuickCheck \cite{ClaessenHughes00}
but extended to the demands of functional logic programming.

\subsection{Installation}

The current implementation of CurryCheck is a package
managed by the Curry Package Manager CPM.
Thus, to install the newest version of CurryCheck, use the following commands:
%
\begin{curry}
> cypm update
> cypm install currycheck
\end{curry}
%
This downloads the newest package, compiles it, and places
the executable \code{curry-check} into the directory \code{\$HOME/.cpm/bin}.
Hence it is recommended to add this directory to your path
in order to execute CurryCheck as described below.

\subsection{Testing Properties}

To start with a concrete example, consider the following naive definition of
reversing a list:
\begin{curry}
rev :: [a] -> [a]
rev []     = []
rev (x:xs) = rev xs ++ [x]
\end{curry}
To get some confidence in the code, we add some unit tests,
i.e., test with concrete test data:
\begin{curry}
revNull = rev []      -=- []
rev123  = rev [1,2,3] -=- [3,2,1]
\end{curry}
The operator \ccode{-=-} specifies a test where both sides must
have a single identical value. Since this operator (as many more, see below)
are defined in the library \code{Test.Prop}\pindex{Test.Prop},\footnote{%
The library \code{Test.Prop} is a clone of the library
\code{Test.EasyCheck}\pindex{Test.EasyCheck} (see package \code{easycheck})
which defines only the interface but not the actual test implementations.
Thus, the library \code{Test.Prop} has less import dependencies.
When CurryCheck generates programs to execute the tests,
it automatically replaces references to \code{Test.Prop}
by references to \code{Test.EasyCheck} in the generated programs.}
we also have to import this library.
Apart from unit tests, which are often tedious to write,
we can also write a property, i.e., a test parameterized over
some arguments. For instance, an interesting property of reversing a list
is the fact that reversing a list two times provides the input list:
\begin{curry}
revRevIsId xs = rev (rev xs) -=- xs
\end{curry}
Note that each property is defined as a Curry operation
where the arguments are the parameters of the property.
Altogether, our program is as follows:
\begin{curry}
module Rev(rev) where

import Test.Prop

rev :: [a] -> [a]
rev []     = []
rev (x:xs) = rev xs ++ [x]

revNull = rev []      -=- []
rev123  = rev [1,2,3] -=- [3,2,1]

revRevIsId xs = rev (rev xs) -=- xs
\end{curry}
Now we can run all tests by invoking the CurryCheck tool.
If our program is stored in the file \code{Rev.curry},
we can execute the tests as follows:
\begin{curry}
> curry-check Rev
...
Executing all tests...
revNull (module Rev, line 7):
 Passed 1 test.
rev123 (module Rev, line 8):
 Passed 1 test.
revRevIsId_ON_BASETYPE (module Rev, line 10):
 OK, passed 100 tests.
\end{curry}
Since the operation \code{rev} is polymorphic,
the property \code{revRevIsId} is also polymorphic in its argument.
In order to select concrete values to test this property,
CurryCheck replaces such polymorphic tests by defaulting the type
variable to prelude type \code{Ordering}
(the actual default type can also be set by a command-line flag).
If we want to test this property on integers numbers,
we can explicitly provide a type signature,
where \code{Prop} denotes the type of a test:
\begin{curry}
revRevIsId :: [Int] -> Prop
revRevIsId xs = rev (rev xs) -=- xs
\end{curry}
The command \code{curry-check} has some options to influence
the output, like \ccode{-q} for a quiet execution
(only errors and failed tests are reported) or
\ccode{-v} for a verbose execution where all generated test cases
are shown.
Moreover, the return code of \code{curry-check} is \code{0}
in case of successful tests, otherwise, it is \code{1}.
Hence, CurryCheck can be easily integrated in tool chains
for automatic testing.

In order to support the inclusion of properties in the source code,
the operations defined the properties do not have to be exported,
as show in the module \code{Rev} above.
Hence, one can add properties to any library and export only
library-relevant operations. To test these properties,
CurryCheck creates a copy of the library where all operations
are public, i.e., CurryCheck requires write permission on the
directory where the source code is stored.

The library \code{Test.Prop} defines many combinators
to construct properties. In particular, there are a couple of
combinators for dealing with non-deterministic operations
(note that this list is incomplete):
\begin{itemize}
\item
The combinator \ccode{<\char126>} is satisfied if the set of values
of both sides are equal.
\item
The property \code{$x$ \char126> $y$} is satisfied if $x$
evaluates to every value of $y$.
Thus, the set of values of $y$ must be a subset of the set of values of $x$.
\item
The property \code{$x$ <\char126 $y$} is satisfied if $y$
evaluates to every value of $x$, i.e.,
the set of values of $x$ must be a subset of the set of values of $y$.
\item
The combinator \ccode{<\char126\char126>} is satisfied
if the multi-set of values of both sides are equal.
Hence, this operator can be used to compare the number
of computed solutions of two expressions.
\item
The property \code{always $x$} is satisfied if all values of $x$ are true.
\item
The property \code{eventually $x$} is satisfied if some value
of $x$ is true.
\item
The property \code{failing $x$} is satisfied if $x$ has no value,
i.e., its evaluation fails.
\item
The property \code{$x$ \# $n$} is satisfied if $x$ has $n$
different values.
\end{itemize}
%
For instance, consider the insertion of an element at an arbitrary
position in a list:
\begin{curry}
insert :: a -> [a] -> [a]
insert x xs     = x : xs
insert x (y:ys) = y : insert x ys
\end{curry}
The following property states that the element is inserted
(at least) at the beginning or the end of the list:
\begin{curry}
insertAsFirstOrLast :: Int -> [Int] -> Prop
insertAsFirstOrLast x xs = insert x xs ~> (x:xs ? xs++[x])
\end{curry}
%
A well-known application of \code{insert} is to use it to define
a permutation of a list:
\begin{curry}
perm :: [a] -> [a]
perm []     = []
perm (x:xs) = insert x (perm xs)
\end{curry}
We can check whether the length of a permuted lists is unchanged:
\begin{curry}
permLength :: [Int] -> Prop
permLength xs = length (perm xs) <~> length xs
\end{curry}
Note that the use of \ccode{<\char126>} is relevant since
we compare non-deterministic values. Actually, the left argument
evaluates to many (identical) values.

One might also want to check whether \code{perm} computes the
correct number of solutions. Since we know that a list of length $n$
has $n!$ permutations, we write the following property:
\begin{curry}
permCount :: [Int] -> Prop
permCount xs = perm xs # fac (length xs)
\end{curry}
where \code{fac} is the factorial function.
However, this test will be falsified with the argument \code{[1,1]}.
Actually, this list has only one permuted value since the two
possible permutations are identical and the combinator \ccode{\#}
counts the number of \emph{different} values.
The property would be correct if all elements in the input list \code{xs}
are different.
This can be expressed by a conditional property:
the property \code{$b$ ==> $p$} is satisfied if $p$
is satisfied for all values where $b$ evaluates to \code{True}.
Therefore, if we define a predicate \code{allDifferent} by
\begin{curry}
allDifferent []     = True
allDifferent (x:xs) = x `notElem` xs && allDifferent xs
\end{curry}
then we can reformulate our property as follows:
\begin{curry}
permCount xs = allDifferent xs ==> perm xs # fac (length xs)
\end{curry}
%
Now consider a predicate to check whether a list is sorted:
\begin{curry}
sorted :: [Int] -> Bool
sorted []       = True
sorted [_]      = True
sorted (x:y:zs) = x<=y && sorted (y:zs)
\end{curry}
This predicate is useful to test whether there are also sorted permutations:
\begin{curry}
permIsEventuallySorted :: [Int] -> Prop
permIsEventuallySorted xs = eventually $\code{\$}$ sorted (perm xs)
\end{curry}
%
The previous operations can be exploited to provide
a high-level specification of sorting a list:
\begin{curry}
psort :: [Int] -> [Int]
psort xs | sorted ys = ys
 where ys = perm xs
\end{curry}
Again, we can write some properties:
\begin{curry}
psortIsAlwaysSorted xs = always $\code{\$}$ sorted (psort xs)$\listline$
psortKeepsLength xs = length (psort xs) <~> length xs
\end{curry}
Of course, the sort specification via permutations is not useful
in practice. However, it can be used as an oracle to test
more efficient sorting algorithms like quicksort:
\begin{curry}
qsort :: [Int] -> [Int]
qsort []     = []
qsort (x:l)  = qsort (filter (<x) l) ++ x : qsort (filter (>x) l)
\end{curry}
The following property specifies the correctness of quicksort:
\begin{curry}
qsortIsSorting xs = qsort xs <~> psort xs
\end{curry}
Actually, if we test this property, we obtain a failure:
%
\begin{curry}
> curry-check ExampleTests
...
qsortIsSorting (module ExampleTests, line 53) failed
Falsified by third test.
Arguments:
[1,1]
Results:
[1]
\end{curry}
%
The result shows that, for the given argument \code{[1,1]},
an element has been dropped in the result.
Hence, we correct our implementation, e.g., by replacing
\code{(>x)} with \code{(>=x)}, and obtain a successful test execution.

For I/O operations, it is difficult to execute them with random data.
Hence, CurryCheck only supports specific I/O unit tests:
\begin{itemize}
\item \code{$a$ `returns` $x$} is satisfied if the I/O action $a$
returns the value $x$.
\item \code{$a$ `sameReturns` $b$} is satisfied if the I/O actions
$a$ and $b$ return identical values.
\end{itemize}
%
Since CurryCheck executes the tests written in a source program
in their textual order, one can write several I/O tests that are
executed in a well-defined order.

\subsection{Generating Test Data}

CurryCheck test properties by enumerating test data and
checking a given property with these values.
Since these values are generated in a systematic way,
one can even prove a property if the number of test cases
is finite. For instance, consider the following property
from Boolean logic:
\begin{curry}
neg_or b1 b2 = not (b1 || b2) -=- not b1 && not b2
\end{curry}
This property is validated by checking it with all possible values:
%
\begin{curry}
> curry-check -v ExampleTests
...
0:
False
False
1:
False
True
2:
True
False
3:
True
True
neg_or (module ExampleTests, line 67):
 Passed 4 tests.
\end{curry}
%
However, if the test data is infinite, like lists of integers,
CurryCheck stops checking after a given limit for all tests.
As a default, the limit is 100 tests but it can be changed
by the command-line flag \ccode{-m}. For instance, to test
each property with 200 tests, CurryCheck can be invoked by
%
\begin{curry}
> curry-check -m 200 ExampleTests
\end{curry}
%
For a given type, CurryCheck automatically enumerates all values
of this type (except for function types).
In KiCS2, this is done by exploiting the functional logic features
of Curry, i.e., by simply collecting all values of a free variable.
For instance, the library \code{Test.EasyCheck}\pindex{Test.EasyCheck}
defines an operation
\begin{curry}
valuesOf :: a -> [a]
\end{curry}
which computes the list of all values of the given argument
according to a fixed strategy (in the current implementation:
randomized level diagonalization \cite{ChristiansenFischer08FLOPS}).
For instance, we can get 20 values for a list of integers by
%
\begin{curry}
Test.EasyCheck> take 20 (valuesOf (_::[Int]))
[[],[-1],[-3],[0],[1],[-1,0],[-2],[0,0],[3],[-1,1],[-3,0],[0,1],[2],
[-1,-1],[-5],[0,-1],[5],[-1,2],[-9],[0,2]]
\end{curry}
%
Since the features of PAKCS for search space exploration are more limited,
PAKCS uses in CurryCheck explicit generators for search tree structures
which are defined in the module \code{SearchTreeGenerators}.
For instance, the operations
%
\begin{curry}
genInt :: SearchTree Int$\listline$
genList :: SearchTree a -> SearchTree [a]
\end{curry}
generates (infinite) trees of integer and lists values.
To extract all values in a search tree, the library \code{Test.EasyCheck}
also defines an operation
\begin{curry}
valuesOfSearchTree :: SearchTree a -> [a]
\end{curry}
so that we obtain 20 values for a list of integers in PAKCS by
%
\begin{curry}
...> take 20 (valuesOfSearchTree (genList genInt))
[[],[1],[1,1],[1,-1],[2],[6],[3],[5],[0],[0,1],[0,0],[-1],[-1,0],[-2],
[-3],[1,5],[1,0],[2,-1],[4],[3,-1]]
\end{curry}
%
Apart from the different implementations,
CurryCheck can test properties on predefined types, as already shown,
as well as on user-defined types.
For instance, we can define our own Peano representation of
natural numbers with an addition operation and two properties as follows:
%
\begin{curry}
data Nat = Z | S Nat$\listline$
add :: Nat -> Nat -> Nat
add Z     n = n
add (S m) n = S(add m n)$\listline$
addIsCommutative x y = add x y -=- add y x$\listline$
addIsAssociative x y z = add (add x y) z -=- add x (add y z)
\end{curry}
%
Properties can also be defined for polymorphic types.
For instance, we can define general polymorphic trees,
operations to compute the leaves of a tree and mirroring a tree
as follows:
\begin{curry}
data Tree a = Leaf a | Node [Tree a]$\listline$
leaves (Leaf x) = [x]
leaves (Node ts) = concatMap leaves ts$\listline$
mirror (Leaf x) = Leaf x
mirror (Node ts) = Node (reverse (map mirror ts))
\end{curry}
Then we can state and check two properties on mirroring:
\begin{curry}
doubleMirror t = mirror (mirror t) -=- t$\listline$
leavesOfMirrorAreReversed t = leaves t -=- reverse (leaves (mirror t))
\end{curry}
%
In some cases, it might be desirable to define own test data
since the generated structures are not appropriate for testing
(e.g., balanced trees to check algorithms that require work
on balanced trees).
Of course, one could drop undesired values by an explicit condition.
For instance, consider the following operation that adds all numbers
from 0 to a given limit:
%
\begin{curry}
sumUp n = if n==0 then 0 else n + sumUp (n-1)
\end{curry}
%
Since there is also a simple formula to compute this sum,
we can check it:
%
\begin{curry}
sumUpIsCorrect n = n>=0 ==> sumUp n -=- n * (n+1) `div` 2
\end{curry}
Note that the condition is important since \code{sumUp}
diverges on negative numbers.
CurryCheck tests this property by enumerating integers,
i.e., also many negative numbers which are dropped for the tests.
In order to generate only valid test data, we define
our own generator for a search tree containing only valid data:
%
\begin{curry}
genInt = genCons0 0 ||| genCons1 (+1) genInt
\end{curry}
%
The combinator \code{genCons0} constructs a search tree
containing only this value, whereas \code{genCons1}
constructs from a given search tree a new tree where the function
given in the first argument is applied to all values.
Similarly, there are also combinators \code{genCons2},
\code{genCons3} etc.\ for more than one argument.
The combinator \ccode{|||} combines two search trees.

If the Curry program containing properties defines a generator
operation with the name \code{gen$\tau$},
then CurryCheck uses this generator to test properties
with argument type $\tau$.
Hence, if we put the definition of \code{genInt}
in the Curry program where \code{sumUpIsCorrect} is defined,
the values to check this property are only non-negative integers.
Since these integers are slowly increasing, i.e., the search tree
is actually degenerated to a list, we can also use
the following definition to obtain a more balanced search tree:
%
\begin{curry}
genInt = genCons0 0 ||| genCons1 (\n -> 2*(n+1)) genInt
                    ||| genCons1 (\n -> 2*n+1)   genInt
\end{curry}
The library \code{SearchTree} defines the structure of search trees
as well as operations on search trees, like limiting the depth
of a search tree (\code{limitSearchTree}) or showing a search tree
(\code{showSearchTree}). For instance, to structure
of the generated search tree up to some depth
can be visualized as follows:
\begin{curry}
...SearchTree> putStr (showSearchTree (limitSearchTree 6 genInt))
\end{curry}
%
If we want to use our own generator only for specific properties,
we can do so by introducing a new data type and defining a generator
for this data type.
For instance, to test only the operation \code{sumUpIsCorrect} with non-negative
integers, we do not define a generator \code{genInt} as above,
but define a wrapper type for non-negative integers and
a generator for this type:
%
\begin{curry}
data NonNeg = NonNeg { nonNeg :: Int }$\listline$
genNonNeg = genCons1 NonNeg genNN
 where
   genNN = genCons0 0 ||| genCons1 (\n -> 2*(n+1)) genNN
                      ||| genCons1 (\n -> 2*n+1)   genNN
\end{curry}
Now we can either redefine \code{sumUpIsCorrect} on this type
\begin{curry}
sumUpIsCorrectOnNonNeg (NonNeg n) = sumUp n -=- n * (n+1) `div` 2
\end{curry}
or we simply reuse the old definition by
\begin{curry}
sumUpIsCorrectOnNonNeg = sumUpIsCorrect . nonNeg
\end{curry}

\subsection{Checking Equivalence of Operations}

CurryCheck supports also equivalence tests for operations.
Two operations are considered as \emph{equivalent} if they
can be replaced by each other in any possible context
without changing the computed values (this is also called
\emph{contextual equivalence} and precisely defined in
\cite{AntoyHanus12PADL} for functional logic programs).
For instance, the Boolean operations
\begin{curry}
f1 :: Bool -> Bool               f2 :: Bool -> Bool
f1 x = not (not x)                f2 x = x
\end{curry}
are equivalent, whereas
\begin{curry}
g1 :: Bool -> Bool               g2 :: Bool -> Bool
g1 False = True                   g2 x = True
g1 True  = True
\end{curry}
are not equivalent: \code{g1 failed} has no value but
\code{g2 failed} evaluates to \code{True}.

To check the equivalence of operations, one can use the
property combinator \code{<=>}:
\begin{curry}
f1_equiv_f2 = f1 <=> f2
g1_equiv_g2 = g1 <=> g2
\end{curry}
The left and right argument of this combinator must be a defined operation
or a defined operation with a type annotation in order to specify
the argument types used for checking this property.

CurryCheck transforms such properties into properties
where both operations are compared w.r.t.\ all partial
values and partial results.
The details are described in \cite{AntoyHanus18FLOPS}.

It should be noted that CurryCheck can test
the equivalence of non-terminating operations provided
that they are \emph{productive}, i.e., always generate
(outermost) constructors after a finite number of steps
(otherwise, the test of CurryCheck might not terminate).
For instance, CurryCheck reports a counter-example to
the equivalence of the following non-terminating operations:
\begin{curry}
ints1 n = n : ints1 (n+1)$\listline$
ints2 n = n : ints2 (n+2)

-- This property will be falsified by CurryCheck:
ints1_equiv_ints2 = ints1 <=> ints2
\end{curry}
This is done by iteratively guessing depth-bounds, computing both operations
up to these depth-bounds, and comparing the computed results.
Since this might be a long process, CurryCheck supports
a faster comparison of operations when it is known
that they are terminating.
If the name of a test contains the suffix \code{'TERMINATE},
CurryCheck assumes that the operations to be tested are terminating,
i.e., they always yields a result when applied to ground terms.
In this case, CurryCheck does not iterate over depth-bounds
but evaluates operations completely.
For instance, consider the following definition of
permutation sort (the operations \code{perm} and \code{sorted}
are defined above):
\begin{curry}
psort :: Ord a => [a] -> [a]
psort xs | sorted ys = ys
  where ys = perm xs
\end{curry}
A different definition can be obtained by defining
a partial identity on sorted lists:
\begin{curry}
isort :: Ord a => [a] -> [a]
isort xs = idSorted (perm xs)
 where idSorted []              = []
       idSorted [x]             = [x]
       idSorted (x:y:ys) | x<=y = x : idSorted (y:ys)
\end{curry}
We can test the equivalence of both operations by
specializing both operations on some ground type (otherwise,
the type checker reports an error due to an unspecified
type \code{Ord} context):
\begin{curry}
psort_equiv_isort = psort <=> (isort :: [Int] -> [Int])
\end{curry}
CurryCheck reports a counter example by the 274th test.
Since both operations are terminating, we can also check
the following property:
\begin{curry}
psort_equiv_isort'TERMINATE = psort <=> (isort :: [Int] -> [Int])
\end{curry}
Now a counter example is found by the 21th test.

Instead of annotating the property name to use more efficient equivalence
tests for terminating operations, one can also ask CurryCheck
to analyze the operations in order to safely approximate
termination or productivity properties.
For this purpose, one can call CurryCheck with the option
\ccode{--equivalence=$equiv$} or \ccode{-e$equiv$}.
The parameter $equiv$ determines the mode for equivalence checking
which must have one of the following values (or a prefix of them):
%
\begin{description}
\item[\code{manual}:]
This is the default mode. In this mode, all equivalence tests
are executed with first technique described above, unless
the name of the test has the suffix \code{'TERMINATE}.
\item[\code{autoselect}:]
This mode automatically selects the improved transformation
for terminating operations by a program analysis, i.e.,
if it can be proved that both operations are terminating, then
the equivalence test for terminating operations is used.
It is also used when the name of the test has the suffix \code{'TERMINATE}.
\item[\code{safe}:]
This mode analyzes the productivity behavior of operations.
If it can be proved that both operations are terminating
or the test name has the suffix \code{'TERMINATE}, then
the more efficient equivalence test for terminating operations is used.
If it can be proved that both operations are productive
or the test name has the suffix \code{'PRODUCTIVE}, then
the first general test technique is used.
Otherwise, the equivalence property is \emph{not} tested.
Thus, this mode is useful if one wants to ensure that all
equivalence tests always terminate (provided that the additional
user annotations are correct).
\item[\code{ground}:]
In this mode, only ground equivalence is tested, i.e.,
each equivalence property
\begin{curry}
g1_equiv_g2 = g1 <=> g2
\end{curry}
is transformed into a property which states that both
operations must deliver the same values on same input values, i.e.,
\begin{curry}
g1_equiv_g2 x1 ... xn = g1 x1 ... xn <~> g2 x1 ... xn
\end{curry}
Note this property is more restrictive than contextual equivalence.
For instance, the non-equivalence of \code{g1} and \code{g2}
as shown above cannot be detected by testing ground equivalence only.
\end{description}

\subsection{Checking Contracts and Specifications}
\label{sec:currycheck:contracts}

The expressive power of Curry supports
writing high-level specifications
as well as efficient implementations for a given problem
in the same programming language,
as discussed in \cite{AntoyHanus12PADL}.
If a specification or contract is provided for some function,
then CurryCheck automatically generates properties
to test this specification or contract.

Following the notation proposed in \cite{AntoyHanus12PADL},
a \emph{specification}\index{specification}
for an operation $f$ is an operation \code{$f$'spec}
of the same type as $f$.
A \emph{contract}\index{constract} consists
of a pre- and a postcondition, where the precondition could be omitted.
A \emph{precondition}\index{precondition} for an operation $f$
of type $\tau \to \tau'$ is an operation
\begin{curry}
$f$'pre :: $\tau$ ->$~$Bool
\end{curry}
whereas
a \emph{postcondition}\index{postcondition} for $f$
is an operation
\begin{curry}
$f$'post :: $\tau$ ->$~\tau'$ ->$~$Bool
\end{curry}
which relates input and output values
(the generalization to operations with more than one argument
is straightforward).

As a concrete example, consider again the problem of sorting a list.
We can write a postcondition and a specification for
a sort operation \code{sort} and an implementation via quicksort
as follows (where \code{sorted} and \code{perm}
are defined as above):

\begin{curry}
-- Postcondition: input and output lists should have the same length
sort'post xs ys = length xs == length ys

-- Specification:
-- A correct result is a permutation of the input which is sorted.
sort'spec :: [Int] -> [Int]
sort'spec xs | sorted ys = ys  where ys = perm xs

-- An implementation of sort with quicksort:
sort :: [Int] -> [Int]
sort []     = []
sort (x:xs) = sort (filter (<x) xs) ++ [x] ++ sort (filter (>=x) xs)
\end{curry}
%
If we process this program with CurryCheck,
properties to check the specification and postcondition
are automatically generated. For instance,
a specification is satisfied if it is equivalent to its
implementation, and a postcondition is satisfied
if each value computed for some input satisfies the postcondition
relation between input and output. For our example, CurryCheck generates
the following properties (if there are also
preconditions for some operation, these preconditions are used
to restrict the test cases via the condition operater \ccode{==>}):

\begin{curry}
sortSatisfiesPostCondition :: [Int] -> Prop
sortSatisfiesPostCondition x = always (sort'post x (sort x))

sortSatisfiesSpecification :: Prop
sortSatisfiesSpecification = sort <=> sort'spec
\end{curry}

\subsection{Combining Testing and Verification}

Usually, CurryCheck tests all user-defined properties as well as
postconditions or specifications,
as described in Section~\ref{sec:currycheck:contracts}.
If a programmer uses some other tool to verify such properties,
it is not necessary to check such properties with test data.
In order to advice CurryCheck to do so,
it is sufficient to store the proofs in specific files.
Since the proof might be constructed by some tool
unknown to CurryCheck or even manually,
CurryCheck does not check the proof file but trusts the programmer
and uses a naming convention for files containing proofs.
If there is a property \code{p} in a module \code{M}
for which a proof in file \code{proof-M-p.*}
(the name is case independent), then
CurryCheck assumes that this file contains
a valid proof for this property.
For instance, the following property states that
sorting a list does not change its length:
%
\begin{curry}
sortlength xs = length (sort xs) <~> length xs
\end{curry}
%
If this property is contained in module \code{Sort} and
there is a file \code{proof-Sort-sortlength.txt}
containing a proof for this property,
CurryCheck considers this property as valid and does not check it.
Moreover, it uses this information to simplify other properties to be tested.
For instance, consider the property \code{sortSatisfiesPostCondition}
of Section~\ref{sec:currycheck:contracts}.
This can be simplified to
\code{always$\;$True} so that it does not need to be tested.

One can also provide proofs for generated properties,
e.g., determinism, postconditions, specifications,
so that they are not tested:
\begin{itemize}
\item
If there is a proof file \code{proof-$M$-$f$-IsDeterministic.*},
a determinism annotation for operation $M.f$ is not tested.
\item
If there is a proof file \code{proof-$M$-$f$-SatisfiesPostCondition.*},
a postcondition for operation $M.f$ is not tested.
\item
If there is a proof file \code{proof-$M$-$f$-SatisfiesSpecification.*},
a specification for operation $M.f$ is not tested.
\end{itemize}
Note that the file suffix and all non-alpha-numberic characters
in the name of the proof file are ignored.
Furthermore, the name is case independent
This should provide enough flexibility when other verification tools
require specific naming conventions.
For instance, a proof for the property \code{Sort.sortlengh}
could be stored in the following files in order to be considered
by CurryCheck:
\begin{curry}
proof-Sort-sortlength.tex
PROOF_Sort_sortlength.agda
Proof-Sort_sortlength.smt
ProofSortSortlength.smt
\end{curry}

\subsection{Checking Usage of Specific Operations}

In addition to testing dynamic properties of programs,
CurryCheck also examines the source code of the given
program for unintended uses of specific operations
(these checks can be omitted via the option \ccode{--nosource}).
Currently, the following source code checks are performed:

\begin{itemize}
\item
The prelude operation \ccode{=:<=} is used to implement
functional patterns \cite{AntoyHanus05LOPSTR}. It should not be
used in source programs to avoid unintended uses.
Hence, CurryCheck reports such unintended uses.
\item
Set functions \cite{AntoyHanus09} are used to encapsulate
all non-deterministic results of some function in a set structure.
Hence, for each top-level function $f$ of arity $n$,
the corresponding set function can be expressed in Curry
(via operations defined in the library \code{SetFunctions})
by the application \ccode{set$n$ $f$} (this application is used
in order to extend the syntax of Curry with a specific notation
for set functions).
However, it is not intended to apply the operator \ccode{set$n$}
to lambda abstractions, locally defined operations
or operations with an arity different from $n$.
Hence, CurryCheck reports such unintended uses of set functions.
\end{itemize}

% LocalWords: CurryCheck

%%% Local Variables:
%%% mode: latex
%%% TeX-master: "main"
%%% End:


\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{indentfirst}
%\usepackage{mathptmx}%Times
\title{CS131 B1: HW 2}
\author{Duy Nguyen}
\date{24 September 2016}

\begin{document}

\maketitle

\section*{Question 1}

\subsection*{a. Pluto is called a planet if and only if Kuiper Belt objects are called planets.}

Pluto is called a planet \textbf{P}

Kuiper Belt objects are called planet \textbf{K}

$P \leftrightarrow K$

P is false, K is false so $P \leftrightarrow K$ is true.

\subsection*{b. If C++ is object-oriented language, then Java is also an object-oriented language.}

C++ is object-oriented language \textbf{C}

Java is an object-oriented language \textbf{J}

$C \rightarrow J$

C is true and J is true so $C \rightarrow J$ is true.

\subsection*{c. If C++ uses pointers, then Java also uses pointers.}

C++ uses pointers \textbf{C}

Java uses pointers \textbf{J}

$C \rightarrow J$

C is true and J is false so $C \rightarrow J$ is false.

\subsection*{d. Rain or shine, I am studying CS131.}

Rain \textbf{R}

Shine \textbf{S}

I am studying CS131 \textbf{I}

$(R \lor S) \rightarrow I$

Since it could either raining or shine right now, $R \lor S$ is always true. I is true. Thus $(R \lor S) \rightarrow I$ is true.

\subsection*{e. For every $x$: if $x^4>10,000$, then $x>10$.}

$x^4>10,000$ \textbf{A}

$x>10$ \textbf{B}

$A \rightarrow B$

When A is true, B could be false (for $\sqrt[4]{10,000} = \pm 10$, $x <= -10$). Thus $A \rightarrow B$ is false.

\subsection*{f. For every $x$: $x>10$ implies $x^4 > 10,000$.}

$x>10$ \textbf{C}

$x^4>10,000$ \textbf{D}

$C \rightarrow D$

When C is true, D is also true. Thus $C \rightarrow D$ is true.

\subsection*{g. $log x>0$ iff $x>1$.}

$log x>0$ \textbf{L}

$x>1$ \textbf{M}

$L \leftrightarrow M$

When M is true, L is true. When M is false, L is false. There is no way only either M or L is true/false. Thus $L \leftrightarrow M$ is true.

\section*{Question 2}
\subsection*{a. The fact A implies the fact B.}
$A \rightarrow B$
\subsection*{b. The conclusion C follows from the three premises: P, Q, and R.}
$(P \land Q \land R) \rightarrow C$
\subsection*{c. A is sufficient for B.}
$A \rightarrow B$
\subsection*{d. A is necessary for B.}
$B \rightarrow A$
\subsection*{e. A is necessary and sufficient for B.}
$(B \rightarrow A) \land (A \rightarrow B) \equiv A \leftrightarrow B$
\subsection*{f. If I study hard I get good grades.}
I study hard \textbf{S}

I get good grades \textbf{G}

$S \rightarrow G$

\subsection*{g. I get good grades only if I study hard.}
I get good grade \textbf{G}

I study hard \textbf{S}

$G \rightarrow S$.

\subsection*{h. I get good grades if and only if I study hard.}
I get good grade \textbf{G}

I study hard \textbf{S}

$G \leftrightarrow S$.

\section*{Question 3}
\subsection*{2a. The fact A implies the fact B.}
\begin{tabular}{r|l}
    Statement & $A \rightarrow B$ \\
    Contrapositive & $\neg B \rightarrow \neg A$ \\
    & Not B implies not A \\
    Negation & $A \land \neg B$ \\
    & A and not B
\end{tabular}
\subsection*{2f. If I study hard I get good grades.}
I study hard \textbf{S}

I get good grades \textbf{G}

\begin{tabular}{r|l}
    Statement & $S \rightarrow G$ \\
    Contrapositive & $\neg G \rightarrow \neg S$ \\
    & If I don't get good grade, then I didn't study hard. \\
    Negation & $S \land \neg G$ \\
    & I study hard and (still) I don't get good grade
\end{tabular}
\section*{Question 4}
\subsection*{a.}
\begin{tabular}{l|l}
    If Pedro Martinez pitches, the Red Sox win. & $P \rightarrow R$\\
    The Red Sox do not win. & $\neg R$\\ \hline
    Pedro Martinez does not pitch. & $\neg P$
\end{tabular}

This argument is valid as it fit the known valid form of \textit{modus tollens}.

\subsection*{b.}
\begin{tabular}{l|l}
    If you got a good grade for the course,& \\
    then you did well on the final exam. & $G \rightarrow F$\\
    You did well on the final exam. & $F$\\ \hline
    You got a good grade for the course. & $G$
\end{tabular}

This argument is valid as it fit the known valid form of \textit{modus ponens}.

\subsection*{c.}
\begin{tabular}{l|l}
    If there is a snow storm, there is no electricity in my house. & $S \rightarrow \neg E$ \\
    The snow is not falling. & $\neg S$ \\ \hline
    My house has electricity. & $E$
\end{tabular}

This argument is invalid as it is the invalid form knows as \textit{fallacy of the inverse}.

\subsection*{d.}
\begin{tabular}{l|l}
    My friend wants to major in CS or biology or chemistry.& $S \lor B \lor C$\\
    She decided that biology and chemistry are not for her. & $\neg B \land \neg C$\\ \hline
    My friend wants to major in CS. & $S$
\end{tabular}

We notice that if we reverse De Morgan's law on the second premise, we have $\neg B \land \neg C \equiv \neg (B \lor C)$. We also notice that we apply associative law and commutative law to have $S \lor B \lor C \equiv (B \lor C) \lor S$.

We have the following argument:

\begin{tabular}{l}
    $(B \lor C) \lor S$\\
    $\neg (B \lor C)$\\ \hline
    $S$
\end{tabular}

This argument is true due to \textit{disjunctive syllogism}.

\subsection*{e.}
\begin{tabular}{l|l}
    If parents go to town, then nanny supervises kids. & $P \rightarrow N$ \\
    If nanny does not supervise kids, then nanny will cook. & $\neg N \rightarrow C$ \\
    Nanny cooked today. & $C$\\ \hline
    Therefore, parents did not go to town today.&$\neg P$.
\end{tabular}

We have the following truth table:

\begin{tabular}{ccc|ccc|c}
	$P$&$N$&$C$&$P \rightarrow N$&$\neg N \rightarrow C$&$C$&$\neg P$ \\ \hline
	\textbf{T}&\textbf{T}&\textbf{T}&\textbf{T}&\textbf{T}&\textbf{T}&\textbf{F}\\
	F&F&F&T&F&F& \\
	T&F&F&F&F&F& \\
	F&T&F&T&T&F& \\
	F&F&T&T&T&T& \\
	T&T&F&T&T&F& \\
	T&F&T&F&T&T& \\
	F&T&T&T&T&T&
\end{tabular}

The first line has true premises but false conclusion. Thus the argument is invalid.

\subsection*{f.}
\begin{tabular}{l|l}
    If I tell you the time, then we'll start chatting & $T \rightarrow C$  \\
    If we start chatting, & \\
    then I'll have to invite you to my house. & $C \rightarrow H$ \\
    If I invite you to my house, & \\
    then you'll meet my daughter & \\
    and you both will fall in love. & $H \rightarrow (D \land L)$ \\
    If you both fall in love, you'll marry my daughter.&$L \rightarrow M$\\ \hline
    Since I don't want a poor son-in-law without a watch, & \\
    I won't tell you the time. & $\neg M \rightarrow \neg T$
\end{tabular}

First we note that "not having a poor son-in-law without a watch" means that he did not marry the daughter ($\neg M$). Now we need to check if $(H \rightarrow (D \land L)) \land (L \rightarrow M) \equiv H \rightarrow M$. For this, we check if $H \rightarrow (D \land L) \equiv H \rightarrow L$. This only happen if D is always true.

If D is true, then using transitivity, we can conclude $T \rightarrow M$. Contrapositive of this argument is $\neg M \rightarrow \neg T$. Therefore, the statement is valid (if D is true). Meeting a person doesn't mean that you will fell in love right?

\end{document}


\documentclass[12]{scrartcl}
\usepackage{amssymb,amsmath,gensymb,dsfont,calc,multicol,fullpage}
\makeatletter
\newcommand\Aboxed[1]{
   \@Aboxed#1\ENDDNE}
\def\@Aboxed#1&#2\ENDDNE{%
   &
   \settowidth\@tempdima{$\displaystyle#1{}$}
   \setlength\@tempdima{\@tempdima+\fboxsep+\fboxrule}
   \kern-\@tempdima
   \boxed{#1#2}
}
\makeatother

\begin{document}

\title{Homework 1, Section 1.2, 5, 16, 18, 19, 23–25, 28–31 }
\author{Alex Gordon}
\date{\today}
\maketitle
\section*{Homework}
\subsection*{5.}
$ \begin{bmatrix} \blacksquare & * \\ 0&\blacksquare \end{bmatrix} $,
$ \begin{bmatrix} \blacksquare & * \\ 0&0 \end{bmatrix} $,
$ \begin{bmatrix} 0 &\blacksquare \\ 0&0 \end{bmatrix} $

\subsection*{16. A)}
This system is inconsistent because $x_1 = 0 and x_2 = 0$
\subsection*{16. B)}
This system is consistent and has infinitely many solutions

\subsection*{18.}
The matrix in REF (Reduced Echelon Form)
$ \begin{bmatrix} 1 &-3 & 1 \\ 0&1 & -\frac{1}{3} \end{bmatrix} $
The system is consistent and the REF does not depend on h. H can then take any value.
\subsection*{19. A)}
The system is unique when $h = 2 $ and $k \neq 8$
\subsection*{19. B)}
The system is inconsistent when $h \neq 2 $
\subsection*{19. C)}
The system is inconsistent when $h = 2 $ and $k = 8$
\subsection*{23.}
$ \begin{bmatrix} 1 &0 & 0&0&a \\ 0 &1 & 0&0&b \\ 0 &0 & 1&0&c \\ 0 &0 & 0&1&d \end{bmatrix} $
thus $x_1$ through $x_4$ equals a unique $a$ through $b$
\subsection*{24.}
The augmented matrix has a pivot in the rightmost column, thus the system is not consistent.
\subsection*{25.}
If the augmented matrix has a pivot in every row, then the matrix is in echelon form by definition and if a matrix is in echelon form by definition it is consistent.
\subsection*{28.}
Every column in the matrix except the rightmost column is a pivot column and the rightmost column is not a pivot column.
\subsection*{29.}
A system of linear equations with fewer equations that unknowns is sometimes called and undetermined system.
The undetermined system is consistent if it has infinitely many solutions. Since an undetermined system always has more variables than equations, there cannot be more basic variables than equations, meaning there is at least one free variable. Therefore, because of the free variable the system is consistent.
\subsection*{30.}
Since $0 \neq 7$, the system is inconsistent.
\subsection*{31.}
Yes it can be consistent.

\end{document}