## Related questions with answers

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

Solution

VerifiedWe 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<i$ 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

## Create a free account to view solutions

## Create a free account to view solutions

## Recommended textbook solutions

#### Discrete Mathematics and Its Applications

7th Edition•ISBN: 9780073383095 (8 more)Kenneth Rosen#### Discrete Mathematics and Its Applications

8th Edition•ISBN: 9781259676512 (3 more)Kenneth Rosen## More related questions

1/4

1/7