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 a1,a2,...,ana_1,a_2,...,a_n

procedure\textbf{procedure} firstrepeated(a1,a2,...ana_1,a_2,...a_n: integers with n1n\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). ii will be the position in the list that we are comparing to the previous positions jj.

location:=0

ii:=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.

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

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

\:\:\:\:\: jj:=1

\:\:\:\:\:while j<i\textbf{while }j<i and location=0

\:\:\:\:\:\:\:\:\:\:if ai=aj\textbf{if }a_i=a_j then \textbf{ then }location:=ii

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

\:\:\:\:\: ii:=i+1i+1

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

return\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 by Kenneth Rosen

Discrete Mathematics and Its Applications

7th EditionISBN: 9780073383095 (8 more)Kenneth Rosen
4,283 solutions
Discrete Mathematics 8th Edition by Richard Johnsonbaugh

Discrete Mathematics

8th EditionISBN: 9780321964687Richard Johnsonbaugh
4,246 solutions
Discrete Mathematics and Its Applications 8th Edition by Kenneth Rosen

Discrete Mathematics and Its Applications

8th EditionISBN: 9781259676512 (3 more)Kenneth Rosen
4,397 solutions
Discrete Mathematics with Applications 5th Edition by Susanna S. Epp

Discrete Mathematics with Applications

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

More related questions

1/4

1/7