MATLAB爱好者论坛-LabFans.com

MATLAB爱好者论坛-LabFans.com (https://www.labfans.com/bbs/index.php)
-   资料存档 (https://www.labfans.com/bbs/forumdisplay.php?f=72)
-   -   在不使用数组/向量的情况下计算数字序列的模式 (https://www.labfans.com/bbs/showthread.php?t=23146)

poster 2019-12-10 20:30

在不使用数组/向量的情况下计算数字序列的模式
 
我是MATLAB入门课程的助教,该课程尚未学习数组的使用(或在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. 我一直在考虑,但是我无法提出一个好的解决方案。有人知道是否有解决此问题的好方法吗?

我能提出的唯一解决方案是丑陋的hack,它们试图通过其他方式来模拟数组的使用,例如使用带有定界符的字符串来模拟类似字典的对象。



[B]回答:[/B]

这里的关键点是“另一个数字,不能小于前一个:”。这意味着输入序列将始终被排序,并且如果数量相等,它们必须彼此相邻出现。假设只需要一种模式,那么使用变量current_mode_so_far , frequency_of_current_mode , input和frequency_of_input推论它应该是微不足道的。



[url=https://stackoverflow.com/questions/2312630]更多&回答...[/url]


所有时间均为北京时间。现在的时间是 04:58

Powered by vBulletin
版权所有 ©2000 - 2025,Jelsoft Enterprises Ltd.