Calculate the sequence mode of numbers without using arrays / vectors

I am TA for introducing MATLAB, and the class has not yet studied the use of arrays (or in MATLAB, vectors). There is an exam, and one of the questions in the study guide is as follows:

[Hard problem] A mode is a number in the sequence that appears most often. The user is prompted to enter a sequence of non-negative numbers in non-decreasing order one after another. The user indicates the end of the sequence by entering a negative number. Write a script to get this user input and determine the sequence mode. If there are several modes, you can report any of them as a mode. Do not use arrays. The following is an example of execution:

Determine mode of a set of nonnegative integers.
Use a negative number to quit.
Give me a number:  70
Another number not smaller than the previous: 71
Another number not smaller than the previous: 80
Another number not smaller than the previous: 80
Another number not smaller than the previous: 80
Another number not smaller than the previous: 91
Another number not smaller than the previous: 93
Another number not smaller than the previous: -1
  Mode is 80.

, . - , ?

, , , , .

+3
4

" , , :". , , , . , 1 , , current_mode_so_far, frequency_of_current_mode, input frequency_of_input.

+7

Clue: , , ( ), 80, 80. , , 80 .

, , .

+5

(.. ).

Since the elements are monotonous, you just keep the mode visible so far (and how many times it has appeared). If a new element overtakes the current mode, just replace it and the counter.

+1
source

Something like this might work:

num = input('Give me a number: ');
mode = num;
prev = num;
n = 1;
bestn = -1;

while num > 0
    num = input('Another number not smaller than the previous: ');
    if num > prev
        %New number
        if n > bestn
            %New mode
            bestn = n;
            mode = prev;
        end
        n = 1;
    else
        n = n +1;
    end
    prev = num;
end

fprintf('Mode is %d',mode);
+1
source

Source: https://habr.com/ru/post/1733928/


All Articles