Try the fastest way to create flashcards
Question

# Devise an algorithm that finds the first term of a sequence of integers that equals some previous term in the sequence.

Solution

Verified
Step 1
1 of 3

We call the algorithm "firstrepeated" and the input is a list of integers $a_1,a_2,...,a_n$

$\textbf{procedure}$ firstrepeated($a_1,a_2,...a_n$: integers with $n\geq 1$)

We will first define a value "location", which we set to 0 and will be set to the position of the repeated number (if there is one). $i$ will be the position in the list that we are comparing to the previous positions $j$.

location:=0

$i$:=2

The algorithm should stop when the a location of a repeated number was found (and thus if location is no longer zero). The algorithm should also stop if we checked every element in the list.

$\textbf{while }i\leq n$ and location=0

We compare every element in position $i$ to the elements in previous positions $j$. If the elements are equal, then we set the variable "location" to the location of the repeated number.

$\:\:\:\:\:$ $j$:=1

$\:\:\:\:\:$$\textbf{while }j and location=0

$\:\:\:\:\:\:\:\:\:\:$$\textbf{if }a_i=a_j$$\textbf{ then }$location:=$i$

$\:\:\:\:\:\:\:\:\:\:$$\textbf{else}$ $j$:=$j+1$

$\:\:\:\:\:$ $i$:=$i+1$

Finally we return the value "location" which is the position of the first repeated value.

$\textbf{return}$ location

## Recommended textbook solutions #### Discrete Mathematics and Its Applications

7th EditionISBN: 9780073383095 (8 more)Kenneth Rosen
4,283 solutions #### Discrete Mathematics

8th EditionISBN: 9780321964687Richard Johnsonbaugh
4,246 solutions #### Discrete Mathematics and Its Applications

8th EditionISBN: 9781259676512 (3 more)Kenneth Rosen
4,397 solutions #### Discrete Mathematics with Applications

5th EditionISBN: 9781337694193Susanna S. Epp
2,641 solutions