Joseph Ring

When I was learning Scala recently, my teacher left me a question to write down the following ideas

Topic message:

There are 100 people in a circle, numbered in order. Count off from the first person (counting from 1 to 3). If the person reporting for 3 leaves the circle, ask who was left last.

Answer:

You start by simply saying 100 is an array, and then you delete multiples of 3, and then you iterate, and then you’re left with exactly what they want

The following code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
list = []
index = []
for i in range (0,100):
list.append(i)

print(list)
for i in range(0,len(list)):
if i %3 == 2:
#print(i)
index.append(i)
onelist = [i for i in list if i not in index]
index = []
print(onelist)

while len(onelist) > 2:
for i in range(0,len(onelist)):
if i %3 == 2:
#print(i)
index.append(onelist[i])
#print(index)
onelist = [i for i in onelist if i not in index]
print(onelist)

Such results is the remaining two, respectively, for the first and second, the problem must be wrong, if according to this algorithm, no matter what happens, the first person and second person always can’t count to three, so back to the topic, turned out to be forgotten city circle, a circle represents the last man after the number, the first people to continue to the last man to count off.

So to adjust our thinking, we set a zero for 100 people, and then the people who count to three will be marked as one, and then the people who are left with a zero will be the people left. Thinking that how to realize the specific algorithm, first of all set a total length of 100 0 array as a marker of 100 people, at the same time, set the number off the starting position to 0, when the number off position 0, began to count off 1, until the number off for 3, tag into 1, then the starting position in time becomes zero, the total number of minus one, start the second number off 1 at the same time, Then loop through the above process, when the starting position reaches the length of the array, it represents the beginning of a new loop.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
index = [0,0,0,0,0,0,0,0,0,0]*10
print(index)

long = 100
person = 0
location = 0

while long > 1:

if index[location] == 0:
person += 1
if person == 3:
person = 0
index[location] = 1
long -= 1

location += 1
if (location == len(index)):
location = 0

else:
location += 1
if location == len(index):
location = 0

print(index)
for i in range(0,len(index)):
if index[i] == 0:
print(i+1)

Then the code is written in Python, not in Scala, and will be written in Scala again after you are familiar with Scala.


Joseph Ring
http://example.com/2022/03/21/Joseph-Ring/
Author
feeling-cold
Posted on
March 21, 2022
Licensed under