V
V
Ventus2020-03-03 20:06:18
Algorithms
Ventus, 2020-03-03 20:06:18

Are the answers correct in the framework of compiling the algorithm?

I want to check myself (whether I understood the questions correctly, and whether I answered correctly). The condition of the problem within the framework of the Pascal language: write an algorithm that counts the number of letters 'a' and 'b' in the text.

Questions:
1. What is the maximum value the number of counter increment operations can take?
2. Minimum number?
3. How many comparisons does the algorithm need?
You need to express the answers using the number N of characters in the input string.

Got the code:

Program n1;
var s:string;
    i,k:integer;

begin
 write('Введите строку ');
 readln(s);

 k:=0;
 for i:=1 to length(s) do begin
    if (s[i]='a') then k:=k+1;
    if (s[i]='b') then k:=k+1;
    end;
 writeln('Буквы встречаются = ', k,' раз');
end.


Flowchart:
5e5e8bde91557108950508.png

Answering questions:
Let's take the string "Hello, baby" (11 characters) as an example.

1. Max count: 11 * 1 = 11 (all characters match the comparison conditions).
2. Min count: 0 * 1 = 0 (not a single character matches the comparison conditions).
3. 11 * 2 = 22 (each character is compared 2 times).

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
Wataru, 2020-03-03
@Ventus

Depending on the level of the tasker, your answer is correct or not quite correct.
Yes, exactly if-s comparisons 2N. But inside the for loop, N comparisons are also buried. How does a cycle work? He has a counter variable and he compares it with the boundary condition. This is clearly seen in the block diagram - the block loop has 2 outputs. So it has branching and, consequently, comparisons.
So the more accurate answer is 3N. An even more accurate answer is 4 N. Because the readln function also needs to do some comparisons to stop input at the end of the line, but this is already a nitpick, which is almost certainly not expected of you.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question