我是MATLAB课程入门级的TA,该课程尚未学习数组的使用(或在MATLAB,向量中).有一个考试即将开始,学习指南中的一个问题如下:
[难题]模式是序列中出现次数最多的数字.提示用户一个接一个地以非递减顺序输入一系列非负数.用户通过输入负数来指示序列的结束.编写脚本以获取此类用户输入并确定序列的模式.如果有多种模式,您可以将其中任何一种模式报告为模式.不要使用数组.下面是一个示例运行:
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.
Run Code Online (Sandbox Code Playgroud)
我一直在考虑它,但我无法想出一个好的解决方案.有谁知道是否有一个好方法来解决这个问题?
我能想出的唯一解决方案是丑陋的黑客攻击,试图通过其他方式模拟数组的使用,例如使用带分隔符的字符串来模拟类似字典的对象.
这里的关键点是"另一个不小于前一个的数字:".这意味着输入序列始终是有序的,如果有相同的数字,它们必须彼此相邻.假定仅需要1模式下,它应该是微不足道的使用变量来推断出这一点current_mode_so_far,frequency_of_current_mode,input和frequency_of_input.
线索:由于输入序列是非递减的顺序,你知道(在你的例子中)一旦你看到一个数字大于80,你永远不会再看到一个80.所以在这一点上,你确切知道80序列中有多少个.
也许你可以记住这个数字和线索在这里结束