\documentclass[12pt,a4paper]{article}
\setlength{\topmargin}{-5mm}
\setlength{\textheight}{244mm}
\setlength{\oddsidemargin}{0mm}
\setlength{\textwidth}{165mm}

\usepackage{fancyvrb}
\DefineVerbatimEnvironment{verbatim}{Verbatim}{xleftmargin=4mm}

\usepackage{lmodern}
\usepackage[T1]{fontenc}
\usepackage{pxfonts}
\usepackage{textcomp}
\usepackage{tabu}

\title{Dijkstra Maps in Roguelikes}
\author{Jeremy Mates}
\date{March 13, 2020}

\usepackage{hyperref}
\hypersetup{pdfauthor={Jeremy Mates},pdftitle={Dijkstra Maps in Roguelikes}}

\begin{document}
\bibliographystyle{plainnat}
\maketitle

\setlength{\parindent}{0pt}

\section*{Simple Pathfinding}

Consider the following map, wherein there are three velociraptors
\texttt{R} surrounding the player \texttt{@} on an open
field\cite{xkcd135}. How can the raptors reach the player?

\begin{verbatim}
......R
.R.....
.......
...@...
.......
.......
..R....
\end{verbatim}

One solution to this problem is the so-called Dijkstra Map\cite{tipodm}.
A map this small can easily be worked out on graph paper; set the
location of the player to the value \texttt{0}. Then in the squares
adjacent to that point write the next highest number, \texttt{1}.

\begin{verbatim}
.......
.......
...1...
..101..
...1...
.......
.......
\end{verbatim}

And so forth until the map is filled. This is a Dijkstra Map (with
Manhattan distances).

\begin{verbatim}
6543456
5432345
4321234
3210123
4321234
5432345
6543456
\end{verbatim}

Note that diagonal moves were not considered\textendash only those
points North South East or West of the given square. This has
ramifications on more complicated maps that contain obstacles.
Meanwhile, each velociraptor can use this map to find the player by
walking ``downhill'' to \texttt{0}, or can flee by picking a cell with a
higher value.

\section*{Obstacles}

Many maps will be more complicated than the above and will contain
obstacles, typically walls, or lava, or there may be monsters that can
pass through walls but not across holy water\textendash specters
perhaps\textendash or anything else you can imagine. Let us for now
only consider physical walls, represented using \texttt{\symbol{35}} as
is typical for roguelikes.

\begin{verbatim}
R....
.###.
.#@..
.#.##
.#.#.
...#.
\end{verbatim}

A Dijkstra Map for this might look like

\vskip 1em%
\begin{tabu} spread 0pt{|X|X|X|X|X|} \hline
8 & 7 & 6 & 5 & 4\\\hline
9 & -1 & -1 & -1 & 3\\\hline
8 & -1 & 0 & 1 & 2\\\hline
7 & -1 & 1 & -1 & -1\\\hline
6 & -1 & 2 & -1 & ?\\\hline
5 & 4 & 3 & -1 & ?\\\hline
\end{tabu}
\vskip 1em%

where the impassable walls are represented by \texttt{-1}. One may use
\texttt{Inf} or an object for such cells, but I assume here an integer
or fixnum array. Another option would be to leave walls at the maximum
integer or \texttt{MOST-POSITIVE-FIXNUM} value and to ignore them while
calculating the costs. Note the two squares lower right that have no
path to the player; these after calculation will typically remain at the
maximum integer value the field was filled with before the pathfinding
pass. This map by the way was made with my \texttt{Game::DijkstraMap}
module\cite{gdm}.

\begin{verbatim}
#!/usr/bin/env perl
use strict;
use warnings;
use Game::DijkstraMap;
my $dm = Game::DijkstraMap->new( str2map => <<'EOM' );
.....
.###.
.#x..
.#.##
.#.#.
...#.
EOM
print $dm->to_tsv;
\end{verbatim}

Pathfinding on this map must ignore \texttt{-1} and look for values
equal to or greater than \texttt{0} when routing to a goal. Here, the
raptor should move horizontally to reach the player in as few moves
as possible.

\section*{Multiple Goals}

A Dijkstra Map may contain multiple goals; pathfinding will find the (or
a) nearest goal. Crabs \texttt{c} for example may wish to retreat to
water \texttt{\symbol{126}} when threatened by the player.

\begin{verbatim}
..~~......~.....
.~~~~......~~...
...~~..c..~~....
..........c.....
...~~...........
..~~...c........
...~~...........
.....~.........@
\end{verbatim}

\vskip 1em%
\begin{tabu} spread 0pt{|X|X|X|X|X|X|X|X|X|X|X|X|X|X|X|X|} \hline
2 & 1 & 0 & 0 & 1 & 2 & 3 & 4 & 2 & 1 & 0 & 1 & 1 & 2 & 3 & 4\\\hline
1 & 0 & 0 & 0 & 0 & 1 & 2 & 3 & 4 & 2 & 1 & 0 & 0 & 1 & 2 & 3\\\hline
2 & 1 & 1 & 0 & 0 & 1 & 2 & 3 & 2 & 1 & 0 & 0 & 1 & 2 & 3 & 4\\\hline
3 & 2 & 2 & 1 & 1 & 2 & 3 & 4 & 3 & 2 & 1 & 1 & 2 & 3 & 4 & 5\\\hline
4 & 3 & 1 & 0 & 0 & 1 & 2 & 3 & 4 & 3 & 2 & 2 & 3 & 4 & 5 & 6\\\hline
2 & 1 & 0 & 0 & 1 & 2 & 3 & 4 & 5 & 4 & 3 & 3 & 4 & 5 & 6 & 7\\\hline
3 & 2 & 1 & 0 & 0 & 1 & 2 & 3 & 4 & 5 & 4 & 4 & 5 & 6 & 7 & 8\\\hline
4 & 3 & 2 & 1 & 1 & 0 & 1 & 2 & 3 & 4 & 5 & 5 & 6 & 7 & 8 & 9\\\hline
\end{tabu}
\vskip 1em%

This map however does not consider other crabs\textendash can two occupy
the same square, or will one need to find a longer route to a free water
cell?\textendash nor the influence of the player; a monster may
realistically have multiple desires: get to water while also avoiding
the player. This can be solved in various ways; moves could be ranked by
utility value--corners might be scored poorly for a fleeing monster (see
e.g. ``Behavioral Mathematics for Game AI''\cite{gameai} for ideas)--or
by using a combination of maps.

\section*{Combining Dijkstra Maps}

Multiple maps may be added together and the combined score used to move
an entity towards or away from goals. Suppose that some
Knight\cite{donq} seeks to make justice upon a fleeing goblin. The
monster, however, has been cornered in a room so simple ``move to the
highest cost cell'' code will leave the monster trapped in a corner.
There should be, in this condition, some means for the monster to slip
past the player.

\begin{verbatim}
######
#....#
#.g.@.
#....#
######
\end{verbatim}

A monster whose state is fleeing needs to be anywhere else; this can be
represented by a map with the monster as the goal, higher values thus
being more desirable. This map can be combined with the map centered on
the player--and also any of their allies, if necessary. Since the
player map will have undesirably low values close to the player, the
resulting map should give a path of higher values for a monster to flee
along step by step.

\begin{verbatim}
######   ######   ######
#2123#   #4321#   #6444#
#1g123 + #321@1 = #42224
#2123#   #4321#   #6444#
######   ######   ######
\end{verbatim}

The best single move in this case would be for the goblin to move to
one of the corners (combined cost 6) and for the player to step
towards them, so

\begin{verbatim}
######   ######
#g...#   #....#
#.....   #..@..
#....#   #....#
######   ######
 g123     3212     3335
 11345 +  21@12 =  33357
 2345     3212     5557
\end{verbatim}

The goblin is now stuck on an island (cost 3), so the player
advances again,

\begin{verbatim}
######   ######
#g...#   #....#
#.....   #.@...
#....#   #....#
######   ######
 g123     2123     2246
 12345 +  1@123 =  22468
 2345     2123     4468
\end{verbatim}

This is not productive as even with combined maps the goblin still gets
stuck. Perhaps if we give more weight to the values of one map or the
other, say multiplying the goblin costs by 2?

\begin{verbatim}
######   ######
#g...#   #....#
#.....   #.@...
#....#   #....#
######   ######
 g123     2123     2369
 11234 +  1@123 =  347AD
 2223     2123     67AD
  * 2
\end{verbatim}

This looks promising, though the best move is to move into the player,
which might be bad. The easiest solution would be to treat the player
(and any allies) as impassable squares on the goblin's flee map

\begin{verbatim}
######   ######
#g...#   #....#
#.#...   #.@...
#....#   #....#
######   ######
 g123     2123     2369
 1#234 +  1@123 =  3#7AD
 2223     2123     67AD
  * 2
\end{verbatim}

Better. The goblin might here roll unlucky and move down instead of
right towards the exit, but that should create conditions that will
cause them to try to move past the player:

\begin{verbatim}
######   ######
#....#   #....#
#g#...   #.@...
#....#   #....#
######   ######
 1234     2123     458B
 1#456 +  1@123 =  1#9CF
 1234     2123     458B
  * 2
\end{verbatim}

However the monster may move back and forth between the back wall and an
edge of the room instead of only moving towards the door if the RNG
dictates that, but at least it is not always stuck, and it may roll well
and escape. \\

Another method would be to construct a line or path to the highest value
on the monster's map instead of only looking for the single best move in
any given turn; this would avoid the possibility of the monster getting
stuck over multiple turns though may be more expensive to calculate and
store. The monster's map also need not comprise the entire field; it may
only need to be slightly larger than the player's field of vision. \\

Different or non-integer weights can be used, or the maps could be
subtracted instead of being added, though experimentation shows that
adding the maps and applying a small positive integer weight to the
monster flee map better avoids problems such as the monster islanding
itself in a corner. \\

Play testing with different approaches and map weights will likely be
necessary. Level design may also be a factor, 3x3 rooms give an obvious
path for the player to try to box a monster in with; larger rooms or
rooms with multiple exits or rooms with rounded corners should create
different weights for the monsters to flee along.

\section*{The Diagonal}

Costs in the above maps have been done without consideration for
diagonal moves. Consider the following map, where \texttt{x} is the
goal.

\begin{verbatim}
@#..
#...
...x
\end{verbatim}

\vskip 1em%
\begin{tabu} spread 0pt{|X|X|X|X|} \hline
? & -1 & 3 & 2\\\hline
-1 & 3 & 2 & 1\\\hline
3 & 2 & 1 & 0\\\hline
\end{tabu}
\vskip 1em%

The player here cannot pathfind to the goal as the diagonal move was not
considered by the 4-way algorithm that only consults cells North South
East and West. Various roguelikes (Angband, Dungeon Crawl Stone Soup)
permit such diagonal moves, so will need to use an 8-way algorithm when
constructing a Dijkstra Map. Other roguelikes (Brogue, POWDER) may deny
such diagonal moves so can use the 4-way algorithm. This choice also
influences level design. 4-way and 8-way roguelikes require rather
different diagonal corridors:

\begin{verbatim}
8-way    @####   4-way    @.###
corridor #.###   corridor #..##
         ##x##            ##x##
\end{verbatim}

Brogue (like rogue) is complicated in that it allows some diagonal
moves. A 4-way Dijkstra Map algorithm can be used with 8-way motion
provided 4-way moves are possible to everywhere that must be reached.
Diagonal moves in such a case exist as shortcuts\textendash moving
diagonally along the above 4-way corridor (which Brogue does not permit,
nor POWDER unless one is ploymorphed into a grid bug).

\section*{Diagonal Maps}

8-way maps typically assign equal costs to all adjacent squares. The
original raptor map instead with Chebyshev distances:

\begin{verbatim}
......R  3333333
.R.....  3222223
.......  3211123
...@...  3210123
.......  3211123
.......  3222223
..R....  3333333
\end{verbatim}

This while traditional for roguelikes is not actually correct; diagonals
under euclidean geometry should instead use $\sqrt{x^2 + y^2}$ or
$\sqrt{2}$ instead of \texttt{1} for the closest diagonal. Various
roguelikes are actually non-euclidean: Brogue and Dungeon Crawl Stone
Soup apply the same cost to a move in any direction, diagonal or
otherwise. Anyways! Our original diagonal map that stumped the 4-way map
under (non-euclidean) 8-way is:

\begin{verbatim}
@#..
#...
...x
\end{verbatim}

\vskip 1em%
\begin{tabu} spread 0pt{|X|X|X|X|} \hline
3 & -1 & 2 & 2\\\hline
-1 & 2 & 1 & 1\\\hline
3 & 2 & 1 & 0\\\hline
\end{tabu}
\vskip 1em%

And the player can path to the goal.

\section*{Not Just for Animates}

Dijkstra Map can be used for other purposes. Given a map with two rooms
in it, how to connect them?

\begin{verbatim}
####################
###########XXXXXX###
###########X....X###
###########X....X###
#XXXXXX####XXXXXX###
#X....X#############
#X....X#############
#X....X#############
#XXXXXX#############
####################
\end{verbatim}

Place a goal anywhere in the wall space, and then considering only walls
\texttt{\symbol{35}} as passable construct a Dijkstra Map with the goal
as the destination, here shown partially complete.

\begin{verbatim}
           XXXXXX
           X....X8
     DCBA98X....X7
 XXXXXXA987XXXXXX6
 X....X98765432345
 X....X87654321234
 X....X76543210123
 XXXXXX 765432123
\end{verbatim}

Then pick a random door location in each room, and pathfind from each
door to the goal, drawing a corridor along the way.

\begin{verbatim}
####################
###########XXXXXX###
###########X....+.##
#####...###X....X.##
#XXXX+X.###XXXXXX.##
#X....X...#######.##
#X....X##.........##
#X....X#######..####
#XXXXXX#############
####################
\end{verbatim}

This will run into complications if rooms are adjacent or worse two
rooms block a third from reaching a goal (there should likely be one
goal per unconnected wall space in a map) though there are various
solutions to these challenges, such as pathfinding through rooms or
using additional code to find and link up adjacent rooms.

\section*{Super Dimensional Dijkstra Maps}

We need not confine ourselves to two, or even three dimensions;
Dijkstra Maps can be built in arbitrary numbers of dimensions
(memory requirements, implementation demands, and sanity
permitting). The following is a four-dimensional map with an
implementation\cite{crazylisp} that does not consider diagonal
moves legal.

\begin{verbatim}
% sbcl --noinform --load dijkstramap.lisp
* (setf *dimap-cost-max* 99)

99
* (defparameter level
    (make-array '(3 3 3 3)
                 :initial-contents
                 '((((99 -1 99) (-1 99 -1) (99 -1 99))
                    ((-1 99 99) (99 99 99) (99 99 -1))
                    ((99 99 99) (99 99 99) (99 99 99)))
                   (((-1 99 99) (99 99 99) (99 99 -1))
                    ((99 99 99) (99  0 99) (99 99 99))
                    ((99 99 99) (99 99 99) (99 99 99)))
                   (((99 99 99) (99 99 99) (99 99 99))
                    ((99 99 99) (99 99 99) (99 99 99))
                    ((99 99 99) (99 99 99) (99 99 99))))))

LEVEL
* (dimap-calc level)

4
* level

#4A((((99 -1 4) (-1 2 -1) (4 -1 99))
     ((-1 2 3) (2 1 2) (3 2 -1))
     ((4 3 4) (3 2 3) (4 3 4)))
    (((-1 2 3) (2 1 2) (3 2 -1))
     ((2 1 2) (1 0 1) (2 1 2))
     ((3 2 3) (2 1 2) (3 2 3)))
    (((4 3 4) (3 2 3) (4 3 4))
     ((3 2 3) (2 1 2) (3 2 3))
     ((4 3 4) (3 2 3) (4 3 4))))
*
\end{verbatim}

Productive uses for such maps are left as an exercise to the reader.

\clearpage
\bibliography{references}
\end{document}


\documentclass{article}

\usepackage{fancyhdr}
\usepackage{extramarks}
\usepackage{amsmath}
\usepackage{amsthm}
\usepackage{amssymb}
\usepackage{amsfonts}
\usepackage{tikz}
\usepackage{physics}
\usepackage[plain]{algorithm}
\usepackage{algpseudocode}

\usetikzlibrary{automata,positioning}

%
% Basic Document Settings
%

\topmargin=-0.45in
\evensidemargin=0in
\oddsidemargin=0in
\textwidth=6.5in
\textheight=9.0in
\headsep=0.25in

\linespread{1.1}

\pagestyle{fancy}
\lhead{\hmwkAuthorName}
\chead{\hmwkClass\ : \hmwkTitle}
\rhead{\firstxmark}
\lfoot{\lastxmark}
\cfoot{\thepage}

\renewcommand\headrulewidth{0.4pt}
\renewcommand\footrulewidth{0.4pt}

\setlength\parindent{0pt}

%
% Create Problem Sections
%
\newcommand{\be}{\begin{equation}}
\newcommand{\ee}{\end{equation}}
\newcommand{\bes}{\begin{equation*}}
\newcommand{\ees}{\end{equation*}}
\newcommand{\bea}{\begin{flalign*}}
\newcommand{\eea}{\end{flalign*}}

\newcommand{\enterProblemHeader}[1]{
    \nobreak\extramarks{}{Problem \arabic{#1} continued on next page\ldots}\nobreak{}
    \nobreak\extramarks{Problem \arabic{#1} (continued)}{Problem \arabic{#1} continued on next page\ldots}\nobreak{}
}

\newcommand{\exitProblemHeader}[1]{
    \nobreak\extramarks{Problem \arabic{#1} (continued)}{Problem \arabic{#1} continued on next page\ldots}\nobreak{}
    \stepcounter{#1}
    \nobreak\extramarks{Problem \arabic{#1}}{}\nobreak{}
}

\setcounter{secnumdepth}{0}
\newcounter{partCounter}
\newcounter{homeworkProblemCounter}
\setcounter{homeworkProblemCounter}{1}
\nobreak\extramarks{Problem \arabic{homeworkProblemCounter}}{}\nobreak{}

%
% Homework Problem Environment
%
% This environment takes an optional argument. When given, it will adjust the
% problem counter. This is useful for when the problems given for your
% assignment aren't sequential. See the last 3 problems of this template for an
% example.
%
\newenvironment{homeworkProblem}[1][-1]{
    \ifnum#1>0
        \setcounter{homeworkProblemCounter}{#1}
    \fi
    \section{Problem \arabic{homeworkProblemCounter}}
    \setcounter{partCounter}{1}
    \enterProblemHeader{homeworkProblemCounter}
}{
    \exitProblemHeader{homeworkProblemCounter}
}

%
% Homework Details
%   - Title
%   - Due date
%   - Class
%   - Section/Time
%   - Instructor
%   - Author
%

\newcommand{\hmwkTitle}{Assignment\ \#1}
\newcommand{\hmwkDueDate}{September 23, 2020}
\newcommand{\hmwkClass}{Introduction to General Relativity}
\newcommand{\hmwkClassTime}{}
\newcommand{\hmwkClassInstructor}{Prof. Bala Iyer}
\newcommand{\hmwkAuthorName}{\textbf{Aditya Vijaykumar}}

%
% Title Page
%

\title{
    %\vspace{2in}
    \textmd{\textbf{\hmwkClass:\ \hmwkTitle}}\\
    \normalsize\vspace{0.1in}\small{\hmwkDueDate\ }\\
%    \vspace{3in}
}

\author{\hmwkAuthorName}
\date{}

\renewcommand{\part}[1]{\textbf{\large Part \Alph{partCounter}}\stepcounter{partCounter}\\}

%
% Various Helper Commands
%

% Useful for algorithms
\newcommand{\alg}[1]{\textsc{\bfseries \footnotesize #1}}

% For derivatives
\newcommand{\deriv}[1]{\frac{\mathrm{d}}{\mathrm{d}x} (#1)}

% For partial derivatives
\newcommand{\pderiv}[2]{\frac{\partial}{\partial #1} (#2)}

% Integral dx
\newcommand{\dx}{\mathrm{d}x}

% Alias for the Solution section header
\newcommand{\solution}{\textbf{\large Solution}}

% Probability commands: Expectation, Variance, Covariance, Bias
\newcommand{\E}{\mathrm{E}}
\newcommand{\Var}{\mathrm{Var}}
\newcommand{\Cov}{\mathrm{Cov}}
\newcommand{\Bias}{\mathrm{Bias}}

\begin{document}

\maketitle
\textit{\textbf{Note} --- All problem numbers refer to the exercises numbers in d'Inverno}.
\begin{homeworkProblem}
	\textit{\textbf{Exercise 5.2}}\\
	Given: $ x^a = (x,y,z) $ and $ x'^a  = \qty(r, \theta, \phi)$. The relation between the coordinates is the following:
	\begin{align}\label{key}
	x = r \cos \phi \sin \theta \qq{,}y = r \sin \phi \sin \theta \qq{,} z = r \cos \theta \\
	r = \sqrt{x^2 + y^2 + z^2} \qq{,} \cos \theta = \dfrac{z}{ \sqrt{x^2 + y^2 + z^2}} = \dfrac{z}{r} \qq{,} \tan \phi = \dfrac{y}{x}
	\end{align}
	The transformation matrix is given by:
	\begin{align}\label{key}
		\mqty[\pdv{x^a}{x'^b}] = \mqty[\pdv{x}{r} & \pdv{y}{r} & \pdv{z}{r} \\
		\pdv{x}{\theta} & \pdv{y}{\theta} & \pdv{z}{\theta} \\
		\pdv{x}{\phi} & \pdv{y}{\phi} & \pdv{z}{\phi} \\]^T &= \mqty[\cos \phi \sin \theta  &  \sin \phi \sin \theta & \cos \theta \\
		r \cos \phi \cos \theta &  r \sin \phi \cos \theta & - r \sin \theta \\
		-r \sin \phi \sin \theta & r \cos \phi \sin \theta & 0]^T \\
		J &= \abs{\mqty[\pdv{x^a}{x'^b}]} = r^2 \sin \theta
	\end{align}

	\begin{align}\label{key}
	\mqty[\pdv{x'^a}{x^b}] = \mqty[\pdv{r}{x} & \pdv{r}{y} & \pdv{r}{z} \\
	\pdv{\theta}{x} & \pdv{\theta}{y} & \pdv{\theta}{z} \\
	\pdv{\phi}{x} & \pdv{\phi}{y} & \pdv{\phi}{z} \\]
	&= \mqty[\dfrac{x}{\sqrt{x^2 + y^2 + z^2}} & \dfrac{y}{\sqrt{x^2 + y^2 + z^2}}& \dfrac{z}{\sqrt{x^2 + y^2 + z^2}} \\
	\dfrac{xz}{\sqrt{x^2+ y^2} (x^2 + y^2 + z^2)} & \dfrac{yz}{\sqrt{x^2+ y^2} (x^2 + y^2 + z^2)} & - \dfrac{\sqrt{x^2 + y^2}}{x^2 + y^2 + z^2 }\\
	 \dfrac{-y}{{x^2 + y^2}}& \dfrac{x}{{x^2 + y^2}} &0\\]  \\
	 J' = 1/J &= \dfrac{1}{\sqrt{(x^2 + y^2 + z^2 )(x^2 + y^2)}}
	\end{align}

    For finite $ x, y ,z $, $ J' $ is never zero. It is infinite for $ (x,y,z) = (0,0,a) $, where $ a $ is any real number.

\end{homeworkProblem}

\begin{homeworkProblem}
	\textit{\textbf{Exercise 5.5}}\\
	Given: $ Y^a  $ and $ Z^a $ are contravariant vectors, meaning they obey the contravariant transformation laws.
	\begin{equation}\label{key}
	\implies Y'^a = \pdv{x'^a}{x^b } Y^b \qq{and }  Z'^a = \pdv{x'^a}{x^b } Z^b
	\end{equation}
	Let $T^{ab} =  Y^a Z^b $. Note that we haven't yet proved that $ T^{ab} $ is a tensor --- to prove this, it would suffice to show $ T'^{ab} =  Y'^a Z'^b $, where the primed quantities denote objects transformed as per the contravariant transformation laws. Now consider $ Y'^a Z'^b $
	\begin{align}\label{key}
		Y'^a Z'^b &= \pdv{x'^a}{x^c } Y^c \pdv{x'^b}{x^d } Z^d \\
		& = \pdv{x'^a}{x^c }\pdv{x'^b}{x^d }  Y^c  Z^d  \\
		& = \pdv{x'^a}{x^c }\pdv{x'^b}{x^d }  T^{cd} \\
		Y'^a Z'^b  &= T'^{ab}
	\end{align}
	Hence proved.
\end{homeworkProblem}

\begin{homeworkProblem}
	\textit{\textbf{Exercise 5.8}}\\
	Consider applying the transformation laws to $ \delta^a_b $ and using properties of the Kronecker delta,
	\begin{align}\label{key}
	\pdv{x'^a}{x^c }  \pdv{x^d}{x'^b } \delta^c_d &= \pdv{x'^a}{x^c }  \pdv{x^c}{x'^b } \\
	&= \pdv{x'^a}{x'^b } \\
	&= \delta'^a_b
	\end{align}
	This proves that the Kronecker delta does indeed have tensor character.
	\\

	Also, as the Kronecker delta is given by $ \pdv{x^a}{x^b} $ in a given frame, it has components $ \text{diag}(1,1,1,1) $ in all frames. This means it is a \textit{constant tensor}.
\end{homeworkProblem}

\begin{homeworkProblem}
	\textit{\textbf{Exercise 5.9}}\\
	Consider differentiating $ \pdv{\phi}{x'^a} $ wrt $ x'^c $,
	\begin{align}
		\pdv{}{x'^c} \qty{\pdv{\phi}{x'^a}} &= \pdv{x^d}{x'^c} \pdv{}{x^d} \qty{ \pdv{x^b}{x'^a}\pdv{\phi}{x^b}} \\
		&= \pdv{x^d}{x'^c} \pdv{x^b}{x'^a}\pdv{\phi}{x^b}{x^d} + \pdv{x^d}{x'^c} \pdv{x^b}{x'^a}{x^d}\pdv{\phi}{x^b} \\
		&= \pdv{x^d}{x'^c} \pdv{x^b}{x'^a}\pdv{\phi}{x^b}{x^d} +  \pdv{x^b}{x'^a}{x'^c}\pdv{\phi}{x^b}
	\end{align}
	If $ \pdv{\phi}{x'^c}{x'^a } $ is to transform as a tensor, the second term on the RHS of the last equation should be zero. One can see that though one can construct specific cases in which this term is zero, it is not possible to do so in general. Hence proved that $ \pdv{\phi}{x^a}{x^b} $ is not a tensor.
\end{homeworkProblem}

\begin{homeworkProblem}
	\textit{\textbf{Exercise 5.13}}\\
	Consider $ Y_c = \delta^b_a X^a_{bc} $,
	\begin{align}\label{key}
		Y'_c &= \delta'^b_a X'^a_{bc} \\
		&= \delta^b_a \times \pdv{x'^a}{x^v}  \pdv{x^w}{x'^b}\pdv{x^y}{x'^c} X^v_{wy} \\
		&=  \pdv{x'^a}{x^v}  \pdv{x^w}{x'^a}\pdv{x^y}{x'^c} X^v_{wy} \\
		&=  \pdv{x^w}{x^v}\pdv{x^y}{x'^c} X^v_{wy} \\
		&=  \delta^w_v \pdv{x^y}{x'^c} X^v_{wy} \\
		Y'^c  &= 	\pdv{x^y}{x'^c} X^v_{vy} =	\pdv{x^y}{x'^c} Y_y
	\end{align}
	Hence, we have seen that $ Y_c $ transforms as a covariant vector.
\end{homeworkProblem}

\begin{homeworkProblem}
	\textit{\textbf{Exercise 5.14}}\\
	\begin{align}\label{key}
		\delta^a_a =  \delta^1_1 + \delta^2_2 + \ldots + \delta^n_n = 1 + 1 + \ldots  (n \text{ times}) =  n  \\
		\delta^a_b \delta^b_a = \delta^a_a = n
	\end{align}
\end{homeworkProblem}

\begin{homeworkProblem}
	\textit{\textbf{Exercise 5.16}}\\

	\textit{Part (i)}\\
	Given: In $ \mathbb{R}^2 $, $ x^a = (x,y) $ and $ x'^a = (R, \phi) $.
	\begin{equation}\label{key}
	R = \sqrt{x^2 + y^2} \qq{and} \tan \phi = \dfrac{y}{x}
	\end{equation}
	\begin{equation}\label{key}
	\mqty[\pdv{x'^a}{x^b}] = \mqty[\dfrac{x}{\sqrt{x^2 + y^2}} & \dfrac{y}{\sqrt{x^2 + y^2}} \\
	-\dfrac{y}{x^2 + y^2} & \dfrac{x}{x^2 + y^2}]
	\end{equation}
	\begin{equation}\label{key}
	\boxed{\qq{if}  X^a = (1,0) \qq{then} X'^a = (1, 0)}
	\end{equation}
	\\

	\textit{Part (ii)}\\
	We have,
	\begin{equation}\label{key}
	\grad f \vdot \vb{i} = \pdv{f}{x} \qq{,}\grad f \vdot \vb{j} = \pdv{f}{y} \qq{,}\grad f \vdot \vb{\vu{R}} = \pdv{f}{R} \qq{,}\grad f \vdot \vu{\phi} =\dfrac{1}{R} \pdv{f}{\phi}
	\end{equation}

	But, by using expressions of $ \vu{R} $ and $ \vu{\phi} $ in the $ \vb{i}, \vb{j} $ coordinates, we have,
	\begin{equation}\label{key}
	\grad{f } \vdot \vu{R} = \cos \phi \pdv{f}{x} + \sin \phi \pdv{f}{y} \qq{and} \grad{f } \vdot \vu{\phi} = - \sin \phi \pdv{f}{x} + \cos \phi \pdv{f}{y}
	\end{equation}
	Using these equations, we have,
	\begin{equation}\label{key}
	\pdv{}{R} = \cos \phi \pdv{}{x} + \sin \phi \pdv{}{y} \qq{and} \dfrac{1}{R} \pdv{}{\phi }  = - \sin \phi \pdv{}{x} + \cos \phi \pdv{}{y}
	\end{equation}
	\\

	\textit{Part (iii)}\\
	In the cartesian coordinate system,
	\begin{equation}\label{key}
	X = x \pdv{}{x} + y \pdv{}{y}
	\end{equation}
	In the polar coordinate system,
	\begin{align}\label{key}
	X' &= \qty(\pdv{R}{x} x  + \pdv{R}{y} y)\pdv{}{R} +   \qty(\pdv{\phi}{x} x   + \pdv{\phi}{y} y)\pdv{}{\phi} \\
	&= \qty(\dfrac{x}{R}x  + \dfrac{y}{R} y)\pdv{}{R} +   \qty(\dfrac{-y}{R^2} x   + \dfrac{x}{R^2} y)\pdv{}{\phi} \\
	&= \qty(\dfrac{x^2 + y^2}{R})\pdv{}{R}  \\
	&= R\pdv{}{R} = x \pdv{}{x} + y \pdv{}{y} = X \\
	\end{align}

	Substituting $ X^a = (1,0) $,
	\begin{equation}\label{key}
	X = \pdv{}{x}
	\end{equation}\\

	\textit{Part (iv)}\\
	If $ Y^a = (0,1) $, then using the result from \textit{part (i)}, $ Y'^a = (1,0) $ and $ Y = \pdv{}{y} $

	If $ Z^a = (-y,x ) $, then $ Z'^a = (0,1) $ and $ Z = -y \pdv{}{x} + x\pdv{}{y} $
	\\

	\textit{Part (v)}\\
	\begin{align}\label{key}
	\comm{X}{Y} &= \pdv{}{x} \pdv{}{y} -  \pdv{}{y} \pdv{}{x} = 0
	\end{align}
	\begin{align}
	\comm{Y}{Z} &= \pdv{}{y} \qty{-y \pdv{}{x} + x\pdv{}{y}} - \qty{-y \pdv{}{x} + x\pdv{}{y}} \qty{\pdv{}{y}} \\
	&= - \pdv{}{x} -y \pdv{y} \pdv{}{x} + x\pdv[2]{y} + y \pdv{x} \pdv{y} - x \pdv[2]{y}\\
	&= - \pdv{}{x}  = - X
	\end{align}

	\begin{align}
		\comm{X}{Z} &=  \pdv{}{x} \qty{-y \pdv{}{x} + x\pdv{}{y}} - \qty{-y \pdv{}{x} + x\pdv{}{y}} \qty{\pdv{}{x}}\\
		&= -y \pdv[2]{x} + \pdv{y} + x \pdv{x}\pdv{y} + y \pdv[2]{x} -  x \pdv{x}\pdv{y}\\
		&= \pdv{y} = Y
	\end{align}
\end{homeworkProblem}
\end{document}


\documentclass[9pt, a4paper, oneside, reqno]{amsart}

\usepackage[final]{pdfpages}
\usepackage{wrapfig}

\usepackage{enumitem}
\usepackage{parskip}
\usepackage{fancyhdr}
\usepackage{color}
\usepackage{multicol}
\renewcommand{\thefootnote}{\fnsymbol{footnote}}

\newcommand{\hint}[1]{\footnote{\raggedleft\rotatebox{180}{Hint: #1\hfill}}}

\pagestyle{fancy}

\newlist{questions}{enumerate}{1}
\setlist[questions, 1]{label = \bf Q.\arabic*., itemsep=1em}

\lhead{\scshape Apurva Nakade}
\rhead{\scshape Honors Single Variable Calculus}
\renewcommand*{\thepage}{\small\arabic{page}}
\title{Problem Set 09}

\begin{document}

\maketitle
\thispagestyle{fancy}

\section*{Part 1 - Trigonometric functions}
You should probably make a table of trig identities before you start this problem sheet.
\begin{questions}
	% \item Using the addition formulae for $ \sin$ and $ \cos$ prove that
	% \begin{enumerate}
	% 	\item $ \tan(x + y) = \dfrac{\tan x + \tan y}{1 - \tan x \tan y}$
	% 	\item $ \mathrm{arctan}x + \mathrm{arctan}y = \mathrm{arctan}\left(\dfrac{x + y}{1 - x y}\right)$
	% \end{enumerate}

	% \item If $ u = \tan (x/2)$ express $ \sin x$ and $ \cos x$ in terms of $ u$.

	\item
	\begin{enumerate}
		\item Using the angle sum formula for $ \sin$ and $ \cos$ prove that for $ m, n > 0$  integers
		      \begin{align*}
		      	\int \limits _ {-\pi}^\pi  \sin mx \sin nx \: dx
		      	=
		      	\int \limits _ {-\pi}^\pi  \cos mx \cos nx \:dx
		      	& =
		      	\begin{cases} 0 & m \neq n \\ \pi & m = n\end{cases} \\
		      	\int \limits _ {-\pi}^\pi  \sin mx \cos nx \:dx
		      	& = 0
		      \end{align*}
		\item Show that the minimum value of \begin{align*}
		      g(a) = \int \limits _ {-\pi}^\pi  (f(x) - a \cos nx)^2\: dx
		\end{align*}
		occurs when $ a = \dfrac{1}{\pi}\int \limits _ {-\pi}^\pi  f(x) \cos nx\: dx$.
		\item Repeat part (2) for $g(a) = \int \limits _ {-\pi}^\pi  (f(x) - a \sin mx)^2 \: dx$.
	\end{enumerate}

	\item
	\begin{enumerate}
		\item Prove the following identities\hint{Use the identity $ \sin(k + 1/2)x - \sin(k - 1/2)x = 2 sin(x/2)\cos(kx)$}
		      \begin{align*}
		      	1/2 + \cos x + \cos 2x + \cdots + \cos nx
		      	  & = \dfrac{\sin \left(n + \dfrac{1}{2}\right)x}{2 \sin {(x/2)}}
		      \end{align*}
		\item Use these to find $ \int \limits_{0}^{a} \cos x \: dx$ (for $ a \in [0,\pi / 2]$) directly from the definition of integral.

	\end{enumerate}
	\item
	\begin{enumerate}
		\item Show that $ \lim \limits_{\lambda \rightarrow \infty} \int \limits_a^b \sin \lambda x \: dx = 0$. What does this mean geometrically?
		\item Show that if $ s$ is a step function then $ \lim \limits_{\lambda \rightarrow \infty} \int \limits_a^b s(x) \sin \lambda x \: dx = 0$.
		\item Using Q.7 from Problem Set 07 show that if $ f$ is an integrable function then $$ \lim \limits_{\lambda \rightarrow \infty} \int \limits_a^b f(x) \sin \lambda x \: dx = 0$$ This theorem is called the \textbf{Riemann Lebesgue lemma}.
	\end{enumerate}

\end{questions}
These trig identities (and many more) naturally show up while studying Fourier series.

\newpage
\section*{Part 2 - Logarithms and exponentials}
\begin{questions}[resume]
	\item Use the identity $ (\log f)' = f' / f$ to find $ f'$ for the following functions. This trick is sometimes called \textbf{logarithmic differentiation}.
	\begin{multicols}{2}
		\begin{enumerate}
			\item $ f(x) = \dfrac{(3-x)^{1/3}x^2}{(1-x)(3+x)^{2/3}}$
			\item $ f(x) = (\sin x)^{\cos x} + (\cos x)^{\sin x}$
		\end{enumerate}
	\end{multicols}

	\item The \textbf{hyperbolic} functions are defined as
	\begin{align*}
		\sinh x := \dfrac{e^x - e^{-x}}{2} &   & \cosh x := \dfrac{e^x + e^{-x}}{2}
	\end{align*}
	\begin{enumerate}
		\item Simplify each of the following:
		      \begin{align*}
		      	  & \cosh^2 x - \sinh^2 x,                \\
		      	  & \sinh'x,
		      	\quad \cosh'x,                                     \\
		      	  & \sinh x .\cosh y +  \sinh y. \cosh x, \\
		      	  & \cosh x .\cosh y + \sinh x. \sinh y.
		      \end{align*}
		\item Determine $ (\sinh^{-1})'x$, $ (\cosh^{-1})'x$.
		\item Find an explicit formula for $ \sinh^{-1} x$ and $ \cosh^{-1} x$.\hint{Substitute $ y = e^{x}$ in the right hand side of $\sinh x = \dfrac{e^x - e^{-x}}{2}$.}
		\item Compute $ \int \limits_a^b \dfrac{1}{\sqrt{x^2+1}} \: dx$ and $ \int \limits_a^b \dfrac{1}{\sqrt{x^2-1}} \: dx$.
	\end{enumerate}
	\item
	\begin{enumerate}
		\item Prove that if $ r$ is a root of the polynomial equation
		      \begin{align}
		      	\label{eq:first}
		      	a_n x^n + a_{n-1} x^{n-1} + \cdots + a_1 x + a_0 = 0
		      \end{align}
		      then the function $ y(x) = e^{rx}$ satisfies the differential equation
		      \begin{align}
		      	\label{eq:second}
		      	a_n y^{(n)} + a_{n-1} y^{(n-1)} + \cdots + a_1 y' + a_0 y= 0
		      \end{align}
		\item Prove that if $ r$ is a double root of the polynomial equation \eqref{eq:first} then $ y=x.e^{rx}$ is also a solution of the differential equation \eqref{eq:second}.\hint{Recall that if $ r$ is a double root of a polynomial $f(x)$ then $ r$ is also a root of $ f'(x)$.}
		\item Prove that if $ y_1$ and $ y_2$ satisfy $ \eqref{eq:second}$ then so does $ c_1 y_1 + c_2 y_2$ where $ c_1, c_2$ are arbitrary real numbers.
		\item Find  solutions of the differential equation $ y''' - y' = 0$. (Be careful!)
	\end{enumerate}
	The differential equation \eqref{eq:second} is called a \textbf{constant coefficient linear differential equation} and this is the standard way to solve it.
	\item
	\begin{enumerate}
		\item Sketch the graph of $ \dfrac{\log x}{x}$ for $ x > 0$.
		\item Determine, with proof, which one is larger: $ e^ \pi$ or $ \pi^e$?
	\end{enumerate}
	\item  Find the following limits:
	\begin{multicols}{2}
		\begin{enumerate}
			\item $\lim \limits_{x \rightarrow 0}\dfrac{\log(1+ax)}{x}$
			\item $\lim \limits_{x \rightarrow \infty}x.{\log(1+a/x)} $
			\item $\lim \limits_{x \rightarrow \infty}(1+1/x)^x$
			\item $\lim \limits_{x \rightarrow \infty}(1+a/x)^x$
		\end{enumerate}
	\end{multicols}
\end{questions}

\newpage
\section*{Part 3 - Computations}
From now on the Friday HWs will be about computing integrals. I'll usually assign the problems from the book.
\begin{questions}[resume]
	\item For this week do Q.1 and Q.2 on Pg. 377-378 from Ch.19. \\
	These might look like a lot of problems but they all have very short solutions, usually one trick will give you the answer.
\end{questions}

\end{document}


\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage[usenames]{color}
\usepackage{graphicx}
\usepackage{natbib}
\usepackage{amsmath}
\usepackage{amsfonts}
%\pagenumbering{gobble}%

% CSCI 8331 %

% avoid counting on sections %
\setcounter{secnumdepth}{-1}
\title{Trying different functions for Pollard's rho integer factorization}
\author{Jos? Silveira \\
  George Washington University,\\
  \texttt{silveiraneto@gwu.edu}}

\date{\vspace{-5ex}}

\begin{document}

\maketitle

\begin{abstract}
This work measures empirically how the performance and accuracy changes with different functions for the Pollard's Rho integer factorization. It finds that $f(x) = x+\sqrt[]{n}$ is a better function than the original function proposed for this algorithm. This is the final work for the class CSCI 8331 Advanced Cryptography at George Washington University with professor Poorvi Vora.
\end{abstract}

\section{Introduction}

Pollard's rho algorithm is a integer factorization algorithm that uses concepts from Floyd's cycle-finding algorithm and the Birthday Paradox. In algorithm receives an integer $n$ and returns a non trivial divisor of $n$ (i.e. not $1$) or $False$, which means it may have found a prime. Pollards rho of $n$ execution time varies because the probability of founding a divisor is not the same every number, as shown in $Figure\ 1$.

\begin{figure}[h!]
\centering
\includegraphics[scale=0.35]{factors.png}
\caption{Number of non trivial factors from 1 to 1000}
\label{fig1}
\end{figure}

\section{Functions}

All the functions $f_i$ are $modulo\ n$. The function tested were:\\
\begin{itemize}
  \item $f_1(x) = x^2-1$
  \item $f_2(x) = x^2+1$
  \item $f_3(x) = x^3-1$
  \item $f_4(x) \xleftarrow{R} \mathbb{N}$
  \item $f_5(x) = 4x^2 - 2x +41$
  \item $f_6(x) = x+1$
  \item $f_7(x) = x+2$
  \item $f_8(x) = x+\sqrt[]{n}$
  \item $f_9(x) = 2**x$
  \item $f_{10}(x) = 2**x+1$
  \item $f_{11}(x) = 2x$
  \item $f_{12}(x) = 3x$
  \item $f_{13}(x) = x+3$
  \item $f_{14}(x) = 4x$
  \item $f_{15}(x) = x**2+3$
\end{itemize}

$f_1$ is the original function presented by Pollard \citep{pollard1975monte}. $f_2$ is a common variation. $f_4(x)$ test the hypothesis that $f_1$ was originally chosen because it behaves like a random function. $f_5$ uses the Euler's prime equation. $f_6$ is the consecutive function that guarantees that all numbers will be examined. $f_{15}$ is the function empirically chosen by Brent \citep{brent1980improved}.

\section{Methodology}

For each function, two parameters were analysed, the fail rate and the performance. The fail rate is how many times the pollard's rho fails, i.e. returns an incorrect divisor or returns \textit{False} when the input is not a prime. In the experiments, the pollard's rho method never returned a wrong divisor but depending on the chosen function it can return a false prime. In a practical implementation of this method a fail rate would not be acceptable, requiring to run the method more times using other functions until it returns a divisor or giving it up and assuming the input was a prime. This would imply a bad worst case scenario with prime numbers. In our implementation we accept the output of the method, but count the number of times it fails against a reliable prime verification. For this results, a fail rate higher than zero means that the performance in a practical implementation would be even worst.\\

The second parameter analysed was the performance for $100$ execution trials. The benchmark was done using the \textit{timeit} benchmark library for Python which avoids a number of common traps for measuring execution times. Each trial for a function was composed of the execution of pollard's rho method using the function for values between $2$ and $1000$.\\

Measurements were made using a Amazon Web Services EC2 instance of compute optimized type c3.2xlarge with High Frequency Intel Xeon E5-2670 v2 (Ivy Bridge) Processors, 8 vCPU, and 15Gb RAM. Due the serial nature of this algorithm and its insignificant memory requirements this setup was highly above the minimum necessary but it could run the benchmark 100 times faster than the development desktop.\\

\section{Implementation}

The \textit{Python} implementation used for this benchmark and raw results can be found at https://github.com/silveira/pollardsrho.

\section{Results}

The results for each function and their respective fail rate and performance:\\

\begin{tabular}{l*{2}{c}r}
Function              & Fail rate & Performance \\
\hline
$f_1(x)$ & 3.0\% & 0.756325960159 \\
$f_2(x)$ & 2.2\% & 0.771731138229 \\
$f_3(x)$ & 3.1\% & 3.81694221497 \\
$f_4(x)$ & 0.6\% & 44.762458086 \\
$f_5(x)$ & 1.9\% & 0.774783849716\\
$f_6(x)$ & 0\% & 11.6375050545 \\
$f_7(x)$ & 0\% & 11.491779089 \\
$f_8(x)$ & 0\% & 0.443336009979 \\
$f_9(x)$ & 5.5\% & 11.4220769405 \\
$f_{10}(x)$ & 4.4\% & 8.37259697914 \\
$f_{11}(x)$ & 0\% & 7.15102696419 \\
$f_{12}(x)$ & 0\% & 7.26384687424 \\
$f_{13}(x)$ & 0\% & 11.4748301506 \\
$f_{14}(x)$ & 0.4\% & 4.31600689888 \\
$f_{15}(x)$  & 2.1\% & 0.710178852081 \\
\end{tabular}

\section{Conclusion}

$f_8(x) = x+\sqrt[]{n}$ had the best result with lowest time execution and without any fails, which means that in a real application it would not be necessary to run the algorithm multiple times with different functions. With a simple optimization to memoize the value of $\sqrt[]{n}$ it would perform even better.

\begin{figure}[h!]
\centering
\includegraphics[scale=0.30]{f1_f8.png}
\caption{Execution times with inputs from 1 to 1000 for $f_1(x)$ (blue) and $f_8(x)$ (orange).}
\label{fig2}
\end{figure}

%------------------------------------------------------------------------------------------------------------------%

\bibliographystyle{plain}
\bibliography{references}

\end{document}


\documentclass[11pt,a4paper]{article}

\usepackage[utf8]{inputenc}
\usepackage{graphicx}
\usepackage{mathtools}

\author{Madhur Singhal\\2015CS10235 }
\date{February 2018}

\title{Parallel Programming Assignment 1}

\begin{document}

\maketitle
\section{Question 1}

\subsection{Part 1}
I assume that since only seven steps are given to us, they are the only ones that take measurable time. Thus one iteration of the loop will take $9\:ns$. Accordingly the whole loop will take \textbf{9000 ns} since there is no pipelining and everything executes serially.
\subsection{Part 2}
I assume that we mean a 7 stage pipelined processor which is superscalar (ie can execute two instructions at once). I also assume that the "fetch operands" fetches both operands at once , "add" adds both of them and "store result" stores the result of this. This is assumed since the first two operand names have an s at the end which signifies that they want plural number of operands.\\
With these assumptions the processor will take 506 cycles to go through the loop since 500 cycles will be taken to accept the whole input into the processor and the last 6 will be taken to process the 12 unfinished inputs present in the pipeline. Since we have a pipeline thus the cycle time will be 2 ns (maximum of the individual operation time). Thus total time $= 506*2\: ns =$ \textbf{1012 ns}.\\
It is impractical to show the pipeline state graphically so I'll just describe it. For the first cycle we just take two iterations of the loop (maybe 0 and 1) as input and fetch the four values. For each of the next six cycles these inputs keep proceeding to a new stage and new inputs come to the back thus after seven cycles the pipeline is totally filled. For the next cycles two iterations of the loop come in as input and two iterations of the loop go out as having been processed.

\section{Question 2}

I assume that memory accesses for the result matrix are negligible since they are an order less than those for others. For the \textbf{Y} matrix we would require a memory access each time but for the \textbf{X} matrix, a memory access is required only oncer per four executions since the word size is 4. We cannot use the cache to store the \textbf{Y} matrix  since going once through the innermost loop will remove the stored elements by accessing more than the 32 KB of cache we have (since our cache can store 32 KB which is equal to two columns of the matrix).

$$ Mem\:Accesses =  n^{3} + \dfrac{n^{3}}{4} $$
$$ Num\:Operations = 2n^3$$

We are given than N = 4K (assuming to be equal to 4096).

$$Performace\:=\:\dfrac{Num\:Operations}{Time\:Taken}=\dfrac{Num\:Operations}{Mem\:Time+Comp\:Time}$$
$$ = \dfrac{2*(4096)^3}{(100\:ns)*(4096)^3*\dfrac{5}{4}+(1\:ns)*2*(4096)^3} $$
$$= \dfrac{2}{127}\:GFLOPS = 15.748 \:MFLOPS$$

\section{Question 3}

The second option is true.\\

Suppose two barriers are invoked one after the other. Look at the moment when two processes are waiting at the fifth line and the third one goes through second line and changes process\_arrived to 3 and unlocks S. One of the three processes will then go through lines 6 to 12  and change process\_left to 1. The key problem happens now, this process can go into it's second barrier invocation and acquire the lock on lines 2 to 4 changing proces\_arrived to 4. After this another process will go through lines 6 to 12 and 2 to 4 changing process arrived to 5. The last process will go through lines 6 to 12 and 2 to 4 changing process left to 0 and process arrived to 1. So we end up with a situation where all three proceeses are waiting on line 5 while process arrived is 1. This is a deadlock and will stop the program.\\

To rectify this we can add a "while (process\_left != 0);" line after line 12 in the code. This makes sure one barrier has been processed before we enter the next.
\section{Question 4}
The correct option is (2). We wait till either the other process is one with it's critical section and has set flag(j) to false or the other process has set turn to us and is waiting in his own while loop. This ensures that entering the critical section twice simultaneously is impossible since for one of the processes the above condition has to hold. This is an application of Peterson's algorithm and can be used for parallelism if there is no inbuilt lock in the system. The use of two variables prevents deadlock.
\section{Question 5}

\subsection{Part 1}

$$ Efficiency\:=\:\dfrac{T_s}{p*T_p}$$
$$Here,\:Eff\:=\:\dfrac{T_s}{T_s+p*T_{over}}$$
We can assume that for a fixed number of threads the overhead is constant with respect to the input size (as $T_{over} = T_s*p$ usually). Thus $T_{over} = c$ and serial time can be assumed to be $T_s = O(n^j)$ for some suitable k>=1.
$$ Eff = \dfrac{O(n^j)}{k+O(n^j)}$$
Thus it is clear that efficiency increases with increasing problem size.
\subsection{Part 2}
$$ Efficiency\:=\:\dfrac{T_s}{p*T_p}$$
$$Here,\:Eff\:=\:\dfrac{n}{n+p*log(p)}$$
Scalability refers to whether or not we can icrease n and p simultaneously in a way so as to keep efficiency constant.
Clearly from the above expression,  making $O(n) = p*log(p)$ keeps efficiency constant hence this problem is \textbf{scalable}.
\subsection{Part 3}
A cost optimal version proceeds as follows - divide the array into p segments of equal size, add each segment separately on different processors, use a tree structure to add the p numbers together. Since communication is only needed when the p processors are adding their final numbers so we only need to spend it $log(p)$ times.\\
$$Thus,\,T_p=\dfrac{n}{p}+ 21*log_2(p)$$
$$S = \dfrac{n*p}{n+21*p\:log_2(p)}$$
$$E = \dfrac{n}{n+21*p\:log_2(p)}$$
$$Cost = n + 21*p*log_2(p)$$
The Isoefficiency function is given as follows.
$$ n= c*21*p*log_2(p)$$
\end{document}


\section{Melee Attack}
\textbf{Melee Attacks} are attacks done with a melee weapon up close. If both combatants are fighting with bladed weapons \textit{(swords)}, both combatants roll for a succesful hit and are trying to attack the same body part, and neither parties indicated any desire to prioritize defense over offense, they parry each other's attacks, leading to no damage - if one character decides to prioritize defense over offense, then any succesful roll for hitting will translate into parrying, no matter the targetted body part. It is impossible to parry with or against any melee weapon other than bladed weapons.
\subsection{Attack Types}
Melee Attacks can be neatly divided into four categories:
\begin{itemize}
  \item \textbf{Regular Attack:} A regular targeted or untargeted strike with your melee weapon. It has no drawbacks or advantages. All involuntary counterattacks are also regular attacks. All characters know how to do regular attacks by default too.
  \item \textbf{Power Attack:} An untargeted strike done with a greater swing, from a large distance, with a stronger momentum - this results in a stronger, but more inaccurate attacks, this means a \MalusPS{30\%} increase to chance of miss, but also a \Bonus{25\%} to all damage done in melee. By default, characters cannot do Power Attacks, and must unlock them via a feat - in the archmodule, that feat is Overswing.
  \item \textbf{Quick Attack:} Two untargeted strikes per at a turn, but each with an extra \MalusPS{30\%} increase to chance of miss, and also a \Malus{30\%} to all damage done in melee in case of landing a hit. By default, characters cannot do Quick Attacks, and must unlock them via a feat - in the archmodule, that feat is Flurry.
  \item \textbf{Mounted Attack:} A specialized untargeted strike from atop a mount \textit{(usually a horse)}, it requires the attacker to be moving while doing the attack \textit{(otherwise it's just a Regular Attack done from horseback)} - by default, this kind of attack comes with a \Bonus{40\%} at the cost of an extra \MalusPS{15\%} chance to miss the target. Just like Power Attack and Quick Attack, this needs to be unlocked via a feat - in the archmodule, that feat is Chevauchée.
\end{itemize}
\subsection{Unarmed Attacks}
When doing unarmed attacks, the damage done is $\frac{1d8}{4}*Strength$, unless some feats modify that. It is always \textbf{Crushing} type damage.


\input{templates/lec_template.tex}

\begin{document}

\title[Introduction]{Week 3: Control Structures}
\subtitle{Basic Programming in Python}

\author[kgross, mpoemsl, sselbach]{Katharina Groß, Martin Pömsl, Sören Selbach}

% change to date of actual lecture
\date{\today}

\begin{frame}[plain]
    \titlepage
\end{frame}

\begin{frame}
    \tableofcontents
\end{frame}

\section{Recap}

\subsection{Booleans}

\begin{frame}{Recap: Booleans}

    \begin{itemize}
        \item Boolean variables are either \texttt{True} or \texttt{False}
        \item Booleans are the result of \textit{comparisons:}

        \begin{itemize}
            \item \texttt{41 > 42} results in \texttt{False}
            \item \texttt{"basicpython" == "basic" + "python"} results in \texttt{True}
        \end{itemize}

        \item There are also operators which act directly on Booleans:

        \begin{itemize}
            \item \textbf{\texttt{not x}} is \texttt{True} if \texttt{x} is \texttt{False} and vice versa
            \item \textbf{\texttt{x and y}} is \texttt{True} if both \texttt{x} and \texttt{y} are \texttt{True}
            \item \textbf{\texttt{x or y}} is \texttt{True} if at either \texttt{x} or \texttt{y} is \texttt{True}, \textbf{or both}
        \end{itemize}

    \end{itemize}

    \note{
        \begin{tabular}{| r | r |}
            \hline
            \textbf{\texttt{x}} & \textbf{\texttt{not x}} \\
            \hline
            \color{Red}{\texttt{False}} & \color{Green}{\texttt{True}} \\
            \color{Green}{\texttt{True}} & \color{Red}{\texttt{False}} \\
            \hline
        \end{tabular}

        \vspace{1em}

        \begin{tabular}{| r r | r |}
            \hline
            \textbf{\texttt{x}} & \textbf{\texttt{y}} & \textbf{\texttt{x and y}} \\
            \hline
            \color{Red}{\texttt{False}} & \color{Red}{\texttt{False}} & \color{Red}{\texttt{False}} \\
            \color{Red}{\texttt{False}} & \color{Green}{\texttt{True}} & \color{Red}{\texttt{False}} \\
            \color{Green}{\texttt{True}} & \color{Red}{\texttt{False}} & \color{Red}{\texttt{False}} \\
            \color{Green}{\texttt{True}} & \color{Green}{\texttt{True}} & \color{Green}{\texttt{True}} \\
            \hline
        \end{tabular}

        \vspace{1em}

        \begin{tabular}{| r r | r |}
            \hline
            \textbf{\texttt{x}} & \textbf{\texttt{y}} & \textbf{\texttt{x or y}} \\
            \hline
            \color{Red}{\texttt{False}} & \color{Red}{\texttt{False}} & \color{Red}{\texttt{False}} \\
            \color{Red}{\texttt{False}} & \color{Green}{\texttt{True}} & \color{Green}{\texttt{True}} \\
            \color{Green}{\texttt{True}} & \color{Red}{\texttt{False}} & \color{Green}{\texttt{True}} \\
            \color{Green}{\texttt{True}} & \color{Green}{\texttt{True}} & \color{Green}{\texttt{True}} \\
            \hline
        \end{tabular}
    }

\end{frame}

\subsection{If-Statements}

\begin{frame}[fragile]{Recap: \texttt{if}-statements}

    \begin{block}{}
        \texttt{if}-statements can be used to direct the \textbf{flow} of the program
    \end{block}

    \begin{pythoncode}
        if <condition>:
            <do this if condition is True>
        else:
            <do this otherwise>
     \end{pythoncode}

     \begin{itemize}
         \item \textbf{\texttt{<condition>}} must be some expression that results in a Boolean
         \item if it is \textbf{\texttt{True}}, the code in the block after the \texttt{if} line is executed
         \item a \textbf{code block} are multiple consecutive lines that have the same \textbf{indentation}
     \end{itemize}

     \note{
        \begin{itemize}
            \item ... and if \texttt{<condition>} is \texttt{False}, the code in the \texttt{else}-block is executed
            \item in other languages like C or Java, code blocks are designated by \texttt{\{\}}.
        \end{itemize}
     }

\end{frame}

\begin{frame}[fragile]{\texttt{elif}}

    \begin{block}{}
        \textbf{\texttt{elif}} statements (short for \texttt{else if}) allow to check for an additional condition if the first one was \texttt{False}
    \end{block}

    \begin{pythoncode}
        if <condition 1>:
            <do this if condition 1 is True>

        elif <condition 2>:
            <do this if condition 2 is True>

        else:
            <do this otherwise>
    \end{pythoncode}

\end{frame}

\begin{frame}[fragile]{\texttt{elif}: Examples}

    \begin{columns}[totalwidth = \textwidth, T]

    \begin{column}{0.5\textwidth}

        \begin{pythoncode}
n = 42

if n > 100:
    print("if")

elif n > 20:
    print("elif")

else:
    print("else")
        \end{pythoncode}

        \pause
        \vspace{1em}

        \textbf{Output:} \texttt{elif}

    \end{column}

    \pause

    \begin{column}{0.5\textwidth}

        \begin{pythoncode}
n = 42

if n > 10:
    print("if")

elif n > 20:
    print("elif")

else:
    print("else")
        \end{pythoncode}

        \pause
        \vspace{1em}

        \textbf{Output:} \texttt{if}

    \end{column}

    \end{columns}

\end{frame}

\section{Loops}

\begin{frame}[fragile]

    \begin{block}{Task}
        We want to know how often we can divide a number by 2 (integer division) until we get 0
    \end{block}

    \pause

    \begin{pythoncode}
        if n == 0:
            print("Can divide 0 times.")
        else:
            n = n // 2
            if n == 0:
                print("Can divide 1 time.")
            else:
                n = n // 2
                if n == 0:
                    print("Can divide 2 times.")
                else: # ...

    \end{pythoncode}

    \note{
        Counting how often we can divide a number is basically computing its \textit{logarithm}.

        \vspace{1em}

        \textbf{Approach using \texttt{if} statements:}

        First, we check if \texttt{n} is already \texttt{0}. If yes, we can safely say that we could divide 0 times until we got 0. If not, we divide \texttt{n} by 2 once, and check if it is \texttt{0} \textit{now}. If yes, we can safely say that we could divide 1 time until we got 0 - and so on.

        \vspace{1em}

        Obviously, that is a bad approach. What if we want to be able to deal with numbers that need to be divided, say, 100 times? Writing 100 nested \texttt{if} statements is definitely impractical.
    }

\end{frame}

\begin{frame}

    \centering\includegraphics[width=0.7\textwidth]{03_Control_Structures/da7.jpg}

\end{frame}

\subsection{While-Loop}

\begin{frame}[fragile]{While-Loop}

    \begin{pythoncode}
        while <condition>:
            <code to be executed>
    \end{pythoncode}

    \begin{block}{}
        Just as with the \texttt{if}-statement, the \texttt{while}-loop checks if the condition is \texttt{True} and executes the code block associated with it accordingly. However, when it reaches the end of the block it \textbf{jumps back to the condition}. If it is still true, the \texttt{while}-loop will run again!
    \end{block}

\end{frame}

\begin{frame}[fragile]{While-Loop: Example}

    \begin{pythoncode}
    n = input("Enter a number: ")
    counter = 0

    while n > 0:
        n = n // 2
        counter = counter + 1

    print("Can divide " + str(counter) + " times.")
    \end{pythoncode}

\end{frame}

\begin{frame}{While-Loop: Example}

    \begin{exampleblock}{}
        \textbf{Input: \texttt{42}}
    \end{exampleblock}
    \vspace{-1em}

    \begin{columns}[totalwidth=\textwidth, t]

    \begin{column}{0.5\textwidth}

        \begin{center}

        \begin{tabular}{r r r}
            \textbf{\texttt{n}} & \textbf{\texttt{counter}} & \textbf{\texttt{n > 0}} \\
            \hline \hline
            \texttt{\color{red}{42}} & \texttt{-} & \texttt{True} \\
            \texttt{42} & \texttt{\color{red}{0}} & \texttt{True} \\
            \hline \hline
            \texttt{\color{red}{21}} & \texttt{0} & \texttt{True} \\
            \texttt{21} & \texttt{\color{red}{1}} & \texttt{True} \\
            \hline
            \texttt{\color{red}{10}} & \texttt{1} & \texttt{True} \\
            \texttt{10} & \texttt{\color{red}{2}} & \texttt{True} \\
            \hline
            \texttt{\color{red}{5}} & \texttt{2} & \texttt{True} \\
            \texttt{5} & \texttt{\color{red}{3}} & \texttt{True} \\
        \end{tabular}

        \end{center}

    \end{column}

    \begin{column}{0.5\textwidth}

        \begin{center}

        \begin{tabular}{r r r}
            \textbf{\texttt{n}} & \textbf{\texttt{counter}} & \textbf{\texttt{n > 0}} \\
            \hline \hline
            \texttt{\color{red}{2}} & \texttt{3} & \texttt{True} \\
            \texttt{2} & \texttt{\color{red}{4}} & \texttt{True} \\
            \hline
            \texttt{\color{red}{1}} & \texttt{4} & \texttt{True} \\
            \texttt{1} & \texttt{\color{red}{5}} & \texttt{True} \\
            \hline
            \texttt{\color{red}{0}} & \texttt{5} & \texttt{\color{red}{False}} \\
            \texttt{0} & \texttt{\color{red}{6}} & \texttt{False} \\
            \hline \hline
            \multicolumn{3}{c}{\texttt{End of program.}}
        \end{tabular}

        \end{center}

    \end{column}

    \end{columns}

\end{frame}

\begin{frame}[fragile]{While-Loop: Another Example}

    \begin{block}{Task}
        We want to list all the number from 1 to 100
    \end{block}

    \pause

    \begin{pythoncode}
    counter = 1

    while counter <= 100:
        print(counter)

        # equivalent to counter = counter + 1
        counter += 1
    \end{pythoncode}

    \pause
    \vspace{1em}

    \textbf{This time we know in advance how often our loop will run!}

    \note{
        \begin{itemize}
            \item Expressions like \texttt{x += 3}, at least on numbers, are equivalent to \texttt{x = x + 3}. They \textit{increment} a variable by a certain value. Such shorthands exist for other operators as well: \texttt{-=}, \texttt{*=}, \texttt{/=}, \texttt{**=} and \texttt{\%=}. No, there is no \texttt{i++} in Python.
        \end{itemize}
    }

\end{frame}

\subsection{For-Loop}

\begin{frame}[fragile]{For-Loop}

    \texttt{for}-loops make tasks like this more elegant

    \vspace{1em}

    \begin{pythoncode}
    for i in range(100):
        print(i + 1)
    \end{pythoncode}

    \pause
    \vspace{1em}

    \begin{itemize}
        \item \texttt{i} is just another variable (replacing \texttt{counter})
        \item \texttt{range(100)} "includes" all the numbers from 0 to 99
        \item ... which is why we need the \texttt{+ 1}
    \end{itemize}

    \note{
        You can interpret such a \texttt{for}-loop like this:

        \begin{itemize}
            \item Define a variable \texttt{i} and assign the first value from \texttt{0} to \texttt{99} to it (which is \texttt{0})
            \item Execute whatever is in the \texttt{for}-loop's code block
            \item Assign the \textbf{next} value from \texttt{0} to \texttt{99} to \texttt{i} (if there is no more value, the loop is over) and execute the code block again
        \end{itemize}

        \vspace{1em}

        There is much more to the \texttt{for}-loop than meets the eye. We will see some more ways to use it in this course, and there are even more that we will not cover.

        \vspace{1em}

        Usually whenever you can use a \texttt{for}-loop, you could also use a \texttt{while}-loop and vice versa, but one is usually more elegant than the other.
    }

\end{frame}

\begin{frame}[fragile]{Ways to use \texttt{range}}

    \begin{pythoncode}
    # all integers from 0 - 99
    range(100)

    # all integers from 50 - 99
    range(50, 100)

    # all integers from 50 - 99 in increments of 2
    # note that this does not actually include 99
    range(50, 100, 2)
    \end{pythoncode}

\end{frame}

\begin{frame}[fragile]{For-Loop: Another Example}

    \begin{block}{Task}
        We want to draw a square spiral using the turtle
    \end{block}

    \pause

    \begin{columns}[totalwidth=\textwidth]

    \begin{column}{0.5\textwidth}

    \vspace{-2em}

        \begin{pythoncode}
    from turtle import *

    for i in range(20):
        forward(10 * i)
        left(90)
        \end{pythoncode}

    \end{column}

    \begin{column}{0.5\textwidth}
        \includegraphics[width=\textwidth]{03_Control_Structures/spiral1}
    \end{column}

    \end{columns}

\end{frame}

\section{Functions}

\subsection{Re-Using Code}

\begin{frame}{}

    \vspace{0.5em}

    \begin{block}{Task}
        Now we would like to draw a spiral, do some stuff (like moving the turtle somewhere) and \textit{draw another spiral}
    \end{block}

    \vspace{-1em}

    \includegraphics[width = \textwidth]{03_Control_Structures/spiral2}

\end{frame}

\begin{frame}[fragile]{Naive Approach}

    We could just copy and paste the code for the spiral:

    \begin{pythoncode}
        for i in range(20):
            forward(10 * i)
            left(90)

        # do some stuff here

        for i in range(20):
            forward(10 * i)
            left(90)
    \end{pythoncode}

    \pause

    \begin{alertblock}{\textbf{Problem}}
        This can get long and complicated before you know it!
    \end{alertblock}

    \note{
        Technically, a programming language with branches (i.e. \texttt{if}-statements) and repetitions (i.e. loops) is \textit{Turing complete}, meaning we can compute just about anything with it. Much of the stuff that we will learn next "only" makes Python more convenient to use, although that is probably the biggest understatement of this course.
    }

\end{frame}

\begin{frame}[fragile]{Functions}

    \vspace{-1em}

    \begin{block}{}
        Functions can be used to organize and re-use code
    \end{block}

    \vspace{1em}

    \begin{columns}[totalwidth=\textwidth]

    \begin{column}{0.5\textwidth}

        \vspace{-0.4em}

        \begin{pythoncode}
def draw_spiral():
    for i in range(20):
        forward(10 * i)
        left(90)

draw_spiral()
# do some stuff here
draw_spiral()
        \end{pythoncode}

    \end{column}

    \begin{column}{0.5\textwidth}

        \begin{alertblock}{}
            Here we \textbf{define} a function named \texttt{draw\_spiral} which contains our code for drawing a spiral
        \end{alertblock}

        \begin{alertblock}{}
            Here we \textbf{call} the function (twice) \textit{Only here is the function actually executed}
        \end{alertblock}

    \end{column}

    \end{columns}

\end{frame}

\subsection{Arguments}

\begin{frame}[fragile]{Passing Arguments}

    \begin{block}{Task}
        We want to let our \texttt{draw\_spiral} function have a variable number of loops
    \end{block}

    Arguments/parameters are a way of making a function \textbf{depend on a variable}

    \begin{pythoncode}
    def draw_spiral(loops):
        for i in range(4 * loops):
            forward(10 * i)
            left(90)

    draw_spiral(3)  # will draw a spiral with 3 loops
    draw_spiral(5)  # will draw a spiral with 5 loops
    \end{pythoncode}

    \note{
        Although "argument" and "parameter" are often used synonymously, there is a difference:

        \begin{itemize}
            \item \textit{Arguments} are what is used inside a \textbf{function call}, e.g. the string in \texttt{print("derp")}
            \item \textit{Parameters} are the variables inside a \textbf{function definition}
        \end{itemize}
    }

\end{frame}

\begin{frame}{Passing Arguments}

    \vspace{-1em}

    \begin{columns}[totalwidth = \textwidth]

    \begin{column}{0.5\textwidth}

        \includegraphics[width = \textwidth]{03_Control_Structures/spiral3}
        \centering{\texttt{draw\_spiral(3)}}

    \end{column}

    \begin{column}{0.5\textwidth}

        \includegraphics[width = \textwidth]{03_Control_Structures/spiral4}
        \centering{\texttt{draw\_spiral(5)}}

    \end{column}

    \end{columns}

\end{frame}

\begin{frame}[fragile]{Default Parameter Values}

    \begin{block}{}
        We can give parameters a \textbf{default value} which is assumed if no argument is given
    \end{block}

    \begin{pythoncode}
    def draw_spiral(loops = 5):
        for i in range(4 * loops):
            forward(10 * i)
            left(90)

    draw_spiral()   # will draw a spiral with 5 loops
    draw_spiral(3)  # this still works
    draw_spiral(loops = 42) # this works as well
    \end{pythoncode}

\end{frame}

\begin{frame}[fragile]{Another Example: Factorial}

    \begin{alertblock}{\textbf{Reminder: Factorial}}
        $$ n! = \prod_{i=1}^n i = 1 \cdot 2 \cdot 3 \cdot ... \cdot (n - 1) \cdot n $$
    \end{alertblock}

    \begin{pythoncode}
    def print_factorial(n):
        product = 1

        for i in range(1, n + 1):
            product *= i
            # equivalent to product = product * i

        print(product)
    \end{pythoncode}

    \note{
        \begin{itemize}
            \item As a rule of thumb, you should only print in functions that have "\texttt{print}" in their name (or "\texttt{output}" etc.). The same goes for drawing with the turtle.
        \end{itemize}
    }

\end{frame}

\subsection{Return Values}

\begin{frame}{Return Values}

    \begin{block}{}
        What if we need the result of a function later on in our program?
    \end{block}

    Simply printing it does not work as we have no (easy) way of recovering what was printed

    \pause
    \vspace{1em}

    \begin{alertblock}{\textbf{\texttt{return} statements}}
        \texttt{return} statements return a value from inside a function to the caller of the function. They make functions behave more like mathematical functions in that they "map" the arguments to a value.
    \end{alertblock}

    \note{
        \begin{itemize}
            \item We also cannot access the variable \texttt{product} from outside the function because it was \textit{defined inside} of it. This is called a \textbf{local} variable.
        \end{itemize}
    }

\end{frame}

\begin{frame}[fragile]{Return Values: Example}

    \vspace{-1em}

    \begin{pythoncode}
    def factorial(n):
        product = 1
        for i in range(1, n + 1):
            product *= i

        return product

    fac_result = factorial(4)
    print("The resut is " + str(fac_result) + ".")
    \end{pythoncode}

    \vspace{1em}

    \begin{exampleblock}{\textbf{Output}}
        \texttt{The result is 24.}
    \end{exampleblock}

\end{frame}

\subsection{Docstrings}

\begin{frame}[fragile]{Docstrings}

    Functions can have a \textbf{documentation} directly in the code!

    \vspace{1em}

    \begin{pythoncode}
def factorial(n):
    """Computes the factorial of its only parameter

    Arguments:
    n -- number to compute factorial of
    """

    # code for the function here
    \end{pythoncode}

    \note{
        \texttt{"""} (triple quotation marks) are used to enclose \textbf{multiline strings} - i.e. strings, that span multiple lines of code.

        \vspace{1em}

        If a string appears on its own as the first line in a function definition, it is a \textbf{docstring}. For one, it acts like a comment that explains what your function does, what its parameters are and so on. However, it can also be accessed by commands like \texttt{help(function\_name)}.

        \vspace{1em}

        It is good practise to \textit{always} write docstrings. If it is relatively obvious, what a function does, a single short line can already be enough. Documenting your code is important, because other people (like your homework groupmates) need to understand what you wrote. Also, if you look at your code in a few weeks and it is not well documented, you yourself will have no idea what is going on.
    }

\end{frame}

\begin{frame}[fragile]{Docstrings}

    \begin{pythoncode}
        # live demo
    \end{pythoncode}

\end{frame}

\end{document}


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

\usepackage{amsmath, tikz, bm, tkz-euclide,pgfplots}
\pgfplotsset{compat = 1.16}
\usetkzobj{all}

\title{Absolute Value Equations and Inequalities}
\author{}
\date{}

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

\begin{document}

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

\section{Solve absolute value equations.}

\begin{frame}{Absolute Value Equations}
The \alert{absolute value} of a number, $b$, denoted $|b|$, is the distance $b$ is from 0 on a number line.	\newline\\	\pause

For $|x| = 2$, we get two possible values for $x$: \quad 2 and $-2$		\newline\\	\pause

\begin{center}
\begin{tikzpicture}
	\draw [<->, > = latex] (-2.5,0) -- (2.5,0);
	\foreach \x in {-2,-1,0,1,2}
	\draw (\x, -0.1) -- (\x, 0.1);
	\foreach \x in {-2,-1,0,1,2}
	\node at (\x, -0.1) [below] {\small $\x$};
	\draw[decoration={brace, raise=5pt},decorate] (-2,0) -- node[above=6pt] {\small $|-2|=2$} (0,0);
	\draw[decoration={brace, mirror, raise=0.2in},decorate] (0,0) -- node[below=0.22in] {\small $|2|=2$} (2,0);
\end{tikzpicture}
\end{center}
\end{frame}

\begin{frame}{Solving Absolute Value Equations}
When solving absolute value equations:

\[|x| = c \text{ means that } x=c \text{ or } x=-c\]
\pause

{\color{blue}\textbf{Make sure your absolute value bars are isolated on one side before separating your problem into 2 equations.}}
\end{frame}

\begin{frame}{Example 1}
Solve each.	\newline\\
(a) \quad $|2x-3| = 11$
\begin{align*}
\onslide<2->{2x-3 &= 11 & 2x-3 &= -11} \\[6pt]
\onslide<3->{2x &= 14 & 2x &=-8} \\[6pt]
\onslide<4->{x &= 7 & x &= -4}
\end{align*}
\onslide<5->{\[x =7 \text{ or } x = -4\]}
\end{frame}

\begin{frame}{Example 1}
(b) \quad $|3x-1| = 5$
\begin{align*}
\onslide<2->{3x-1 &= 5 & 3x-1 &= -5} \\[6pt]
\onslide<3->{3x &= 6 & 3x &=-4} \\[6pt]
\onslide<4->{x &= 2 & x &= -\frac{4}{3}}
\end{align*}
\onslide<5->{\[x =2 \text{ or } x = -\frac{4}{3}\]}
\end{frame}

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

\begin{frame}{Example 1}
(d) \quad $|-x+2|-4 = 10$
\begin{align*}
\onslide<2->{|-x+2| &= 14 &\text{add 4}}
\end{align*}
\begin{align*}
\onslide<3->{-x+2 &= 14 & -x+2 &= -14} \\[6pt]
\onslide<4->{-x &= 12 & -x &= -16} \\[6pt]
\onslide<5->{x &= -12 & x &= 16}
\end{align*}
\onslide<6->{\[x = -12 \text{ or } x = 16\]}
\end{frame}

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

\section{Solve and graph absolute value inequalities}

\begin{frame}{Absolute Value Inequalities: $<$ and $\leq$}
Absolute value inequalities are similar to absolute value equations.	\newline\\	\pause
For $|x| < 2$, we want all values of $x$ that are \alert{less than 2 units from 0} on a number line:	\newline\\	\pause
\begin{center}
\begin{tikzpicture}
	\draw [<->, > = latex] (-2.5,0) -- (2.5,0);
	\foreach \x in {-2,-1,0,1,2}
	\draw (\x, -0.1) -- (\x, 0.1);
	\foreach \x in {-2,-1,0,1,2}
	\node at (\x, -0.1) [below] {\small $\x$};
	\draw (-2,0) [color = blue!120, fill=white] circle (2.5pt);
	\draw (2,0) [color = blue!120, fill=white] circle (2.5pt);
	\draw [line width = 2, color = blue!120] (-1.92,0) -- (1.92,0);
\end{tikzpicture}
\end{center}
\pause
\[|x| < 2 \text{ means } -2 < x < 2\]
\end{frame}

\begin{frame}{Example 2}
Solve and graph each.	\newline\\
(a) \quad $|2x-2| < 5$
\begin{align*}
\onslide<2->{-5 &< 2x-2 & 2x-2 &< 5} \\[6pt]
\onslide<3->{2x-2 &>-5 & 2x-2 &< 5} \\[6pt]
\onslide<4->{2x &> -3 & 2x &< 7} \\[6pt]
\onslide<5->{x &> -\frac{3}{2} & x &< \frac{7}{2}}
\end{align*}
\begin{center}
\onslide<6->{
\begin{tikzpicture}
\draw[<->] (-2.5,0) -- (2.5,0);
\draw (-1.5,0.15) -- (-1.5,-0.15) node [below] {$-\frac{3}{2}$};
\draw (1.5,0.15) -- (1.5,-0.15) node [below] {$\frac{7}{2}$};
\draw[violet, line width=2] (-1.5,0) -- (1.5,0);
\draw[color=red,fill=white] (-1.5,0) circle [radius=2.5pt];
\draw[color=blue,fill=white] (1.5,0) circle [radius=2.5pt];
\end{tikzpicture}
}
\end{center}
\end{frame}

\begin{frame}{Alternate Solution Method for Example 2a}
(a) \quad $|2x-2| < 5$		\newline\\
\onslide<2->{Treat like an absolute value equation: $|2x-2|=5$ and then use \textbf{test values} in the \emph{original inequality}.}	\newline\\
\onslide<3->{$x = -\frac{3}{2} \text{ or } x = \frac{7}{2}$} \newline\\
\begin{center}
\onslide<4->{
\begin{tikzpicture}
\draw[<->] (-2.5,0) -- (2.5,0);
\draw (-1.5,0.15) -- (-1.5,-0.15) node [below] {$-\frac{3}{2}$};
\draw (1.5,0.15) -- (1.5,-0.15) node [below] {$\frac{7}{2}$};
\onslide<5->{\draw[violet, line width=2] (-1.5,0) -- (1.5,0);}
\draw[color=red,fill=white] (-1.5,0) circle [radius=2.5pt];
\draw[color=blue,fill=white] (1.5,0) circle [radius=2.5pt];
\end{tikzpicture}
}
\end{center}
\end{frame}

\begin{frame}{Example 2}
(b) \quad $|x-9| \leq 2.9$
\begin{align*}
\onslide<2->{-2.9 &\leq x-9 & x-9 &\leq2.9} \\[6pt]
\onslide<3->{x-9 &\geq -2.9 & x-9 &\leq2.9} \\[6pt]
\onslide<4->{x &\geq 6.1 & x &\leq 11.9}
\end{align*}
\begin{center}
\onslide<5->{
\begin{tikzpicture}
\draw[<->] (-2.5,0) -- (2.5,0);
\draw (-1.5,0.15) -- (-1.5,-0.15) node [below] {$6.1$};
\draw (1.5,0.15) -- (1.5,-0.15) node [below] {$11.9$};
\draw[violet, line width=2] (-1.5,0) -- (1.5,0);
\draw[color=red,fill=red] (-1.5,0) circle [radius=2.5pt];
\draw[color=blue,fill=blue] (1.5,0) circle [radius=2.5pt];
\end{tikzpicture}
}
\end{center}
\end{frame}

\begin{frame}{Example 2}
(c) \quad $|x+2| \leq -1$	\newline\\	\pause

No solution, $\varnothing$, since $|x+2|$ is guaranteed to always be non-negative.
\end{frame}

\begin{frame}{Alternate Approach to Example 2c}
(c) \quad $|x+2| \leq -1$	\qquad Treat as $|x+2|=-1$
\begin{align*}
\onslide<2->{x+2 &= -1 & x+2 &= 1} \\[6pt]
\onslide<3->{x &= -3 & x &= -1}
\end{align*}
\begin{center}
\onslide<4->{
	\begin{tikzpicture}
	\draw[<->] (-2.5,0) -- (2.5,0);
	\draw (-1.5,0.15) -- (-1.5,-0.15) node [below] {$-3$};
	\draw (1.5,0.15) -- (1.5,-0.15) node [below] {$-1$};
	\draw [color=red,fill=white] (-1.5,0) circle [radius = 2.5pt];
	\draw [color=blue,fill=white] (1.5,0) circle [radius = 2.5pt];
	\end{tikzpicture}
}
\end{center}
\onslide<5->{No test values work. \quad} \onslide<6->{$\varnothing$}
\end{frame}

\begin{frame}{Absolute Value Inequalities: $>$ and $\geq$}
For $|x| > 2$, we want all the values of $x$ that are \alert{greater than 2 units from 0} on a number line.	\newline\\	\pause
\begin{center}
\begin{tikzpicture}
	\draw [<->, > = latex] (-3,0) -- (3,0);
	\foreach \x in {-2,-1,0,1,2}
	\draw (\x, -0.1) -- (\x, 0.1);
	\foreach \x in {-2,-1,0,1,2}
	\node at (\x, -0.1) [below] {\small $\x$};
	\draw (-2,0) [color = blue!120, fill=white] circle (2.5pt);
	\draw (2,0) [color = blue!120, fill=white] circle (2.5pt);
	\draw [->, line width = 2, color = blue!120] (-2.08,0) -- (-2.75,0);
	\draw [->, line width = 2, color = blue!120] (2.08,0) -- (2.75,0);
\end{tikzpicture}
\end{center}
\pause
\[|x| > 2 \text{ means that } x < -2 \text{ or } x > 2 \]
\end{frame}

\begin{frame}{Example 3}
Solve and graph each.	\newline\\
(a) \quad $|2x+3| \geq 5$
\begin{align*}
\onslide<2->{2x+3 &\leq -5 & 2x+3 &\geq 5} \\[6pt]
\onslide<3->{2x &\leq -8 & 2x &\geq 2} \\[6pt]
\onslide<4->{x &\leq -4 & x &\geq 1}
\end{align*}
\begin{center}
\onslide<5->{
	\begin{tikzpicture}
	\draw[<->] (-2.5,0) -- (2.5,0);
	\draw (-1.5,0.15) -- (-1.5,-0.15) node [below] {$-4$};
	\draw (1.5,0.15) -- (1.5,-0.15) node [below] {$1$};
	\onslide<6->{\draw [color=red,fill=red] (-1.5,0) circle [radius = 2.5pt];
							\draw[color=red,ultra thick,->] (-1.5,0) -- (-2.5,0);}
	\onslide<7->{\draw [color=blue,fill=blue] (1.5,0) circle [radius = 2.5pt];
							\draw[color=blue,ultra thick,->] (1.5,0) -- (2.5,0);}
	\end{tikzpicture}
}
\end{center}
\end{frame}

\begin{frame}{Alternate Solution Method for Example 3a}
(a) \quad $|2x+3| \geq5$		\newline\\
\onslide<2->{Treat like an absolute value equation: $|2x+3|=5$ and then use \textbf{test values} in the \emph{original inequality}.}	\newline\\
\onslide<3->{$x = -4 \text{ or } x = 1$} \newline\\
\begin{center}
\onslide<4->{
\begin{tikzpicture}
\draw[<->] (-2.5,0) -- (2.5,0);
\draw (-1.5,0.15) -- (-1.5,-0.15) node [below] {$-4$};
\draw (1.5,0.15) -- (1.5,-0.15) node [below] {$1$};
\onslide<5->{\draw[red,ultra thick, ->] (-1.5,0) -- (-2.5,0);}
\onslide<6->{\draw[blue,ultra thick, ->] (1.5,0) -- (2.5,0);}
\draw[color=red,fill=red] (-1.5,0) circle [radius=2.5pt];
\draw[color=blue,fill=blue] (1.5,0) circle [radius=2.5pt];
\end{tikzpicture}
}
\end{center}
\end{frame}

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

\begin{frame}{Example 3}
(c) \quad $|2x+2| > -2$	\newline\\	\pause

All real numbers, $\mathbb{R}$, since $|2x+2|$ is guaranteed to always be greater than a negative number.
\end{frame}

\begin{frame}{Alternate Approach to Example 3c}
(c) \quad $|2x+2| > -2$	\qquad Treat as $|2x+2|=-2$
\begin{align*}
\onslide<2->{2x+2 &= -2 & 2x+2 &= 2} \\[6pt]
\onslide<3->{2x &= -4 & 2x &=0}	\\[6pt]
\onslide<4->{x &= -2 & x &= 0}
\end{align*}
\begin{center}
\onslide<5->{
	\begin{tikzpicture}
	\draw[<->] (-2.5,0) -- (2.5,0);
	\draw (-1.5,0.15) -- (-1.5,-0.15) node [below] {$-2$};
	\draw (1.5,0.15) -- (1.5,-0.15) node [below] {$0$};
	\onslide<6->{\draw [color=red,fill=red] (-1.5,0) circle [radius = 2.5pt];}
	\onslide<7->{\draw [color=blue,fill=blue] (1.5,0) circle [radius = 2.5pt];}
	\onslide<8->{\draw[<->,ultra thick, violet] (-2.5,0) -- (2.5,0);}
	\end{tikzpicture}
}
\end{center}
\onslide<9->{All test values work. \quad} \onslide<10->{$\mathbb{R}$}
\end{frame}

\end{document}


% !Mode:: "TeX:UTF-8"
% !TEX program  = xelatex
\newgeometry{margin=1.6in, marginpar=1.5in}

\title{Geometric Progression and Sum}
\author{}
\date{}

\maketitle

\begin{abstract}
    We present a concise formula for the sum of the first $n$\footnote{$n$ is a natural integer.} terms in a geometric progression, which is easy to implement. And we put it forward to the infinite case. This new method is more efficient and well-performed.
\end{abstract}
\paragraph{Keywords:} geometric progression, summation

\section{Introduction}\label{S:introduction}
Historically, geometric series played an important role in the early development of calculus, and they continue to be central in the study of convergence of series. Geometric series are used throughout mathematics, and have important applications in physics, engineering, biology, economics, computer science, queueing theory, and finance. The intuitive method to calculate the sum of the first $n$ terms of a geometric progression is adding them one by one. It can be sophisticated when $n$ is very large. This is a right but clumsy method, so an easier one is needed.

We use the misalignment subtraction to develop the formula to solve this problem. And we apply our method to three examples. Comparing with the traditional one, the calculation is extremely simple. The ratio of any two successive terms in the geometric progression is a constant, we call it common ratio and denote it as $q$. A geometric series only depends on its first term $a$ and common ratio $q$. The formula for the sum of the first $n$ terms $S_n$ is:
\begin{equation*}
    S_n = \begin{cases}
        na & (q=1) \\
        \frac{{a\left(1-q^{{n}}\right)}}{{1-q}} & (q\neq 1)
        \end{cases}
\end{equation*}
This series is converge and equals to $\frac{{a}}{{1-q}}$ when $|q|<1$.

The present paper is built up as follows. In Section~\ref{S:introduction}, we  we introduce the background of the geometric progression. Section~\ref{S:geometric-series} is about the definition of the geometric progression and the common ratio. We devote Section~\ref{S:summation-formula} to the construction of the formula, the derivation is presented and its proposals are given. In Section~\ref{S:applications}, we apply our method to two numerical examples and one economic example. Conclusions and discussions are presented in Section~\ref{S:conclusions-and-discussions}.

\section{Geometric Series}\label{S:geometric-series}
\subsection{Definition}
\begin{figure}[h]
    \centering{
    \includegraphics[width=0.4\textwidth]{figures/geometric_progression-1}}
    \caption{Squares(source: wikipedia)}\label{F:geometric-progression}
\end{figure}

In mathematics, a geometric series is a series with a constant ratio between successive terms. For example, the series
\begin{equation*}
    \frac{1}{2}+\frac{1}{4}+\frac{1}{8}+\frac{1}{16}+\cdots
\end{equation*}
is geometric, because each successive term equals to the previous one multiply $\frac{{1}}{{2}}$. Geometric series are among the simplest examples of infinite series with finite sums, although not all of them have this property.
The following table shows several geometric series with different start terms and common ratios:
\begin{equation*}
    \begin{aligned}
        & 2, 20, 200, 2000, \cdots \\
        & 2, 4, 8, 16, \cdots \\
        & 3, 9, 27, 81, \cdots
    \end{aligned}
\end{equation*}

\section{Summation Formula}\label{S:summation-formula}
The sum of a geometric series is finite when $|q|<1$; as the numbers near zero, it becomes insignificantly small, allowing to be calculated despite the series contain infinitely terms. We can use the self-similarity of the series to compute the sum.
\subsection{Derivation of the Formula}
Let $a$ and $q$ be two constants. Consider an infinite sequence of numbers
\begin{equation}\label{E:sequence}
    a_1, a_2, a_3, \ldots
\end{equation}
where the $i$th term in this sequence is
\begin{equation}\label{E:ith-term}
    a_i = a_1 q^{(i-1)}, \quad (i=1,2,3,\ldots)
\end{equation}
for $i=1,2,3\cdots$. The sum of the first $n$ terms of the sequence in Equation~\eqref{E:sequence} is denoted by $S_n$ : that is,
\begin{equation*}
    S_n = a_1 + a_2 + \cdots + a_n.
\end{equation*}

We are interested in finding the value of $S_n$ for any given $n$.

A direct approach is to first compute the $n$ terms ${a_1,a_2,\cdots,a_n}$ through Equation~\eqref{E:ith-term}, and then add them up to obtain the value, but this is clearly time-consuming when $n$ is large. We show an efficient formula below, which expresses the $S_n$ as a simple function of $a$, $q$ and $n$. Since
\begin{equation}\label{E:summation-expression-1}
    S_n = a + aq^1 + \cdots + aq^{(n-1)},
\end{equation}
multiplying $q$ of the both sides of the Equation~\ref{E:summation-expression-1}, we obtain
\begin{equation}\label{E:summation-expression-2}
    \begin{aligned}
        qS_n &= q(a + aq^1 + \cdots + aq^{(n-1)}) \\
             &= aq^1 + aq^2 + \cdots + aq^n
    \end{aligned}
\end{equation}
Subtract $S_n$ from both sides of the Equation~\eqref{E:summation-expression-2}, we obtain
\begin{equation}\label{E:summation-expression-3}
    (q-1)S_n = aq^n - a.
\end{equation}
If $q\neq 1$, dividing both side of Equation~\eqref{E:summation-expression-3} by $(q-1)$, we obtain
\begin{equation*}
    S_n = \frac{a(1-q^n)}{1-q},
\end{equation*}
which holds for any integer $n$.

If $q = 1$,we can easily get that $S_n = na$.

Till now, we finish the derivation of the formula. We can find that the result is concise and can be easily employed.

\subsection{Extensions of the Formula}
We derivate the sum of the fist $n$ terms of a geometric sequence. What will happen when the $n$ is extended to infinite? Without loss of generality, we assume $a>0$.

If $q=1$, then
\begin{equation*}
    S = \lim_{n\to\infty} S_n = \lim_{n\to\infty} na = \infty;
\end{equation*}

If $-1<q<1$, then $\lim_{n\to\infty}q^n=0$, we obtain
\begin{equation*}
    S = \lim_{n\to\infty} S_n = \frac{a}{1-q};
\end{equation*}

If $q>1$ or $q<-1$, this series does not converge, $\left| S \right| = \mathop {\lim }\limits_{n \to \infty } \left| {{S_n}} \right| = \infty$.

Till now, we have finished the extended of the formula and we have found that the new method performs well even when $n$ tends to infinity.

\section{Applications}\label{S:applications}
\subsection{Numerical Examples}
Some numerical experiments have been carried out in this section.

\paragraph{Example 1:} Calculate $1/2+1/2^2+\cdots+1/2^{20}$.

Using the formula above, we can easily find that
\begin{equation*}
    S_{20} = \frac{\frac{1}{2}\left(1-\frac{1}{2^{20}}\right)}{1-\frac{1}{2}} = 1 - \frac{1}{2^{20}}.
\end{equation*}

But if we calculate it by the traditional method, we need to add 19 times one by one. You can easily find that the new method is more efficient.

\paragraph{Example 2:} Calculate $1/2+1/2^2+\cdots$.

Using the formula above, we can easily find that
\begin{equation*}
    \begin{aligned}
        S_{n} &= \frac{\frac{1}{2}\left(1-\frac{1}{2^{n}}\right)}{1-\frac{1}{2}} = 1 - \frac{1}{2^{n}}. \\
        S &= \lim_{n\to\infty} S_n = 1.
    \end{aligned}
\end{equation*}

But if we calculate it by the traditional method, we will find that may not be useful, because we can never finish this job to add up all terms.

\subsection{Economic Example}
In economics, geometric series are used to calculate the value of an annuity (a sum of money to be paid in regular intervals). We present an economic example which is from wikipedia.

Suppose $\$100$ will be paid to the owner of the annuity once per year (at the end of the year) in perpetuity. Receiving $\$100$ a year from now is worth less than an immediate $\$100$, because one cannot invest the money until he receives it. In particular, the present value of $\$100$ one year later is $\frac{{\$100}}{{1 + I}}$, where $I$ is the yearly interest rate. Similarly, two years later, the payment of $\$100$ has a present value of  $\frac{{\$100}}{{(1 + I)}^2}$ (squared because two years'worth of interest is lost by not receiving the money right now). Therefore, the present value of receiving $\$100$ per year in perpetuity is:
\[
    \sum_{n=1}^\infty  {\frac{{\$100}}{{{{\left( {1 + I} \right)}^{n }}}}}  = \frac{{\$100/\left( {1+I} \right)}}{{1 - 1/\left( {1 + I} \right)}} = \frac{{\$100}}{I}
\]

If the yearly interest rate is $10\%(I=0.10)$, then the entire annuity has present value of $\$100/0.10=\$1000$.

This sort of calculation is used to compute the APR of a loan (such as a mortgage loan). It can also be used to estimate the present value of expected stock dividends, or the terminal value of a security.

\section{Conclusions and Discussions}\label{S:conclusions-and-discussions}
In this paper, we present a formula to get the sum of the finite geometric progression and put it forward to the infinite cases. the formula is developed by misalignment subtraction. The examples evidently demonstrate that the formula is efficient for computing $S_n$, as it does not require to add the terms one by one.  It can be used for any geometric sequences even when $n$ is infinite, while the traditional method performs badly.

This formula is the foundation of many other jobs. It is efficient and basic to solve many problems in our lives.

\section*{Acknowledgement}
My deepest gratitude goes first to the Professor Wang and Dr Zhang, for their guidance and teaching about how to write a paper and use the \LaTeX. I owe my sincere gratitude to my parents because they support me for every decision. I thank my advisor Professor He, he gives a lot help to my study. Then, I thank my group members because they give me some suggestions about this paper.

\begin{thebibliography}{9}
    \bibitem{tang2013} 汤涛, 丁玖. 数学之英文写作[M]. 北京: 高等教育出版社, 2013.
    \bibitem{highham1998} HIGHAM N J. Handbook of writing for the mathematical sciences[M]. Philadelphia: Society for Industrial and Applied Mathematics, 1998.
\end{thebibliography}


\input{templates/ex_template.tex}

\title{BPP Exercise 11 -- Pythonic Programming}

% {YYYY}{MM}{DD}
\setdate{2019}{06}{23}

\begin{document}

\section*{About this Exercise Sheet}

Because this sheet is all about pythonic programming, we will not only take {\it code style} into account when grading, but also {\it elegance} and {\it efficiency}. For many tasks on this sheet (probably not all), the solution is quite short, but may nonetheless take some time and effort to find!

\section{Warm Up: Using Someone Else's Code (30 points)}

Very often, you will find that someone has already implemented some parts you need for you program for you - you just need to assemble the puzzle. Implement the pseudocode given below using functions that you can import from the file {\tt chaos\_game.py}. Take a look at their documentation to learn how to use them.

\vspace{1em}

\noindent {\bf Chaos Game}

\begin{enumerate}
    \item {\tt Initialize a blank canvas of size 800x800 pixels}
    \item {\tt Draw an equilateral triangle $\Delta$ onto the canvas}
    \item {\tt Draw a point $P$ at a random location on the canvas}
    \item {\tt Do 10,000 times:}
    \item \hspace{2em}{\tt Select a random corner $C$ of $\Delta$}
    \item \hspace{2em}{\tt Create a new point $P'$ that lies halfway between $C$ and $P$}
    \item \hspace{2em}{\tt Draw $P'$ onto the canvas}
    \item \hspace{2em}{\tt $P \leftarrow P'$}
\end{enumerate}

\begin{solution}
    \begin{pythoncode}
from chaos_game import *

def run_chaos_game():
    # initialize canvas with triangle
    canvas = initialize(800)
    triangle = draw_triangle(canvas)

    # compute first point
    p = random_point(canvas)
    draw_point(p, canvas)

    for i in range(10000):
        # choose random corner and draw halfway point
        corner = random_corner(triangle)
        p_new = get_halfway_point(p, corner)
        draw_point(p_new, canvas)

        # continue with the newly drawn point
        p = p_new

if __name__ == "__main__":
    run_chaos_game()

    # wait until user closes application
    mainloop()
    \end{pythoncode}
\end{solution}

\noindent {\bf Bonus Question:} Can you explain the result?

\section{Pythonification (20 points)}

The following code works, but has some less-than-ideal approaches to solving the given problem. Rewrite the program to be {\it pythonic} (w.r.t. the topics discussed in the lecture). As usual, be careful not to change the functionality of the program.

\begin{pythoncode}
import csv

# read in list of names, discard the header
with open("names.csv") as names_file:
    names = []
    reader = csv.reader(names_file)

    for i, name in enumerate(reader):
        if i != 0:
            names.append(name)

# convert to ages to int
for i in range(len(names)):
    names[i][2] = int(names[i][2])

# sort by age
def bubblesort_names(names):
    done = False

    while not done:
        done = True

        for i, name in enumerate(names[:-1]):
            if names[i][2] > names[i+1][2]:
                names[i], names[i+1] = names[i+1], names[i]
                done = False

bubblesort_names(names)

# print names in a nice way:
for name in names:
    first_name = name[1]
    last_name = name[0]
    age = name[2]

    print(first_name + " " + last_name + " is " + str(age) + " years old.")
\end{pythoncode}

\begin{solution}
    \begin{pythoncode}
import csv

# read in list of names, discard the header
with open("names.csv") as names_file:
    # we can use unpacking here
    _, names = csv.reader(names_file)

# convert to ages to int
# no need to take the detour of range(len(...))
for name in names:
    name[2] = int(name[2])

# sort by age
# we can use sorted with custom key function
names = sorted(names, key=lambda name: name[2])

# print names in a nice way:
for name in names:
    # unpacking again + str.format
    print("{} {} is {} years old".format(*name))
    \end{pythoncode}
\end{solution}

\section{Lazy Evaluation (30 points)}

\subsection{Theory}

\begin{enumerate}
    \item Explain what the term {\it lazy evaluation} refers to in Python.

    \vspace{1em}
    \begin{solution}
        {\it Lazy Evaluation} relates to the idea that when iterating over a sequence of values, it is often not necessary to create the entire sequence in advance. Instead, it can be generated on the fly.
    \end{solution}
    \item In which situations does lazy evaluation provide an advantage? Give an example where it does and one where it does not. Can you think of reasons why it might actually be less efficient sometimes?

    \vspace{1em}
    \begin{solution}
        Lazy evaluation provides an advante when iterating over a large sequence of values, of which we only ever need one at a time. Creating e.g. a list of these values in advance would consume memory, which can be avoided by a lazy generator. It is usually not a good idea to use lazy objects if we need to iterate over them multiple times. In that case, we would have to recompute each value many times and it might be more efficient to just store them in a list in advance.
    \end{solution}
    \item Provide two examples of objects that use lazy evaluation. Explain their purpose. Describe how you could implement them without using lazy evaluation (you do not actually need to write code here).

        \vspace{1em}

        {\bf Example:} A {\tt range(start, stop, step)} object could be implemented as a list of numbers ranging from {\tt start} to {\tt stop} in increments of {\tt step}, e.g. {\tt range(0, 5, 1)} could be {\tt [0, 1, 2, 3, 4]}.

        \vspace{1em}
        \begin{solution}
            {\bf Generators} are very flexible lazy objects, as you can define the sequence they will generate. They could also be implemented as a {\tt for} loop that populates a list with the values the generator would have produced.
        \end{solution}
\end{enumerate}

\subsection{Practice}

\begin{enumerate}
    \item Write a generator expression that generates the values $f(1)$, $f(4)$, $f(7)$, $f(10)$ and $f(13)$ according to the formula $f(x) = 2 * e^{-\sqrt x}$

    \vspace{1em}
    \begin{solution}
        \begin{pythoncode}
from math import exp, sqrt

sequence = (2 * exp(-sqrt(x)) for x in range(1, 14, 3))
        \end{pythoncode}
    \end{solution}

    \item Using generator expressions and the built-in function {\tt sum}, write a single line of code that adds up the prices of all the cars in the list (see below) and prints the result.

    \begin{pythoncode}
class Car:
    def __init__(self, brand, price):
        self.brand = brand
        self.price = price

all_cars = [Car("SuperCar3000", 10_000), Car("Speedmaster", 12_000),
            Car("SuperCar3000", 300), Car("SuperCar3000", 6_500),
            Car("Drivinator", 25_000)]

# YOUR LINE OF CODE HERE
    \end{pythoncode}

    \begin{solution}
        \begin{pythoncode}
print(sum(car.price for car in all_cars))
        \end{pythoncode}
    \end{solution}

    \item Adapt your solution from before to now only add up those cars that are of brand "SuperCar3000".

    \vspace{1em}
    \begin{solution}
        \begin{pythoncode}
print(sum(car.price for car in all_cars if car.brand == "SuperCar3000"))
        \end{pythoncode}
    \end{solution}

    \item Using {\tt zip} and the idea of unpacking in function calls, write a single line that {\it unzips} two lists that have been zipped together. Explain in a comment why your code works.

    \begin{pythoncode}
list_1 = [1, 2, 3, 4]
list_2 = ["a", "b", "c", "d"]

zipped = list(zip(list_1, list_2))
# [(1, "a"), (2, "b"), (3, "c"), (4, "d")]

# should be equal to list_1, list_2
unzipped_1, unzipped_2 = # YOUR CODE HERE
    \end{pythoncode}

    \begin{solution}
        \begin{pythoncode}
unzipped_1, unzipped_2 = zip(*zipped)
        \end{pythoncode}

        This works because the zipped list is itself a list of tuples. If we unpack this list with the {\tt *}, we supply {\tt zip} with (in this case) 4 individual lists that each contain 2 elements. Zipping these together, we receive 2 lists of 4 elements, which are the unzipped lists.
    \end{solution}
\end{enumerate}

\section{Thinking Outside the Box: {\tt map} and {\tt filter} (20 points)}

\subsection{{\tt map}}

{\tt map} takes as arguments a function (usually a {\tt lambda} function) and an iterable. It will return a generator that applies the function to all elements of the iterable.

\begin{enumerate}
    \item Write a short program using {\tt map} and {\tt lambda} functions that squares, multiplies by 4 and then adds 42 to each element in a list. Print the result.

    \vspace{1em}
    \begin{solution}
        \begin{pythoncode}
some_list = [1, 2, 3, 4]
result = list(map(lambda x: 4 * x**2 + 42, some_list))

print(result)
        \end{pythoncode}
    \end{solution}

    \item Write a short program using {\tt map} (and whatever else you need) that creates a tuple containing the sums of all the sublists of the following list.

    \begin{pythoncode}
some_list = [[42, 5, 2], [-1, 0, 0, 20, 100], [1], [], [42, 42]]
    \end{pythoncode}

    {\bf Intended output:}

    \begin{outputcode}
(49, 119, 1, 0, 84)
    \end{outputcode}

    \begin{solution}
        \begin{pythoncode}
sums = tuple(map(sum, some_list))
print(sums)
        \end{pythoncode}
    \end{solution}
\end{enumerate}

\subsection{{\tt filter}}

{\tt filter} takes as arguments a function and an iterable. It will return a generator that only contains those elements of the iterable for which the function returns {\tt True}.

\begin{enumerate}
    \item Write a short program using {\tt filter} that only keeps those values in a list of positive integers (you may assume that to be the case) that are {\bf not prime}. You may go back to the example solution of {\it exercise sheet 3} and use the given function for checking primality.

    \vspace{1em}
    \begin{solution}
        \begin{pythoncode}
# using is_prime from sheet 3
from prime_checker import is_prime

some_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

not_prime = list(filter(lambda x: not is_prime(x)), some_list)

print(not_prime)
        \end{pythoncode}
    \end{solution}

    \item Write a short program using both {\tt filter} {\bf and} {\tt map} that takes a list like this

    \begin{pythoncode}
some_list = ["not a list", [3, 4, 1], "also not a list", [42, "not a number"],
             [5, 7], [3, "not a number", 6]]
    \end{pythoncode}

    and filters out elements that are not a list {\bf and} entire sublists that contain the string {\tt "not a number"}. It then should compute the sums of the remaining sublists like in 4.1.2.

    \vspace{1em}

    {\bf Hint 1:} Remember that {\tt type} gives you the type of an object.

    \begin{solution}
        \begin{pythoncode}
filtered = filter(lambda x: type(x) == list, some_list)
filtered = filter(lambda x: "not a number" not in x, filtered)

print(list(map(sum, filtered)))
        \end{pythoncode}
    \end{solution}
\end{enumerate}

\end{document}