测试一系列数字以确保它们符合序列 1,2,3...n [英] Test a series of numbers to ensure they fit the sequence 1,2,3...n

查看:58
本文介绍了测试一系列数字以确保它们符合序列 1,2,3...n的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找到一个稍微更优雅的解决方案来确定一个数字序列是否有序.这是一个网络表单,我让用户有机会对项目进行编号,这将设置订单.我知道项目的最大数量,它应该总是从一个开始.

I am trying to find a slightly more elegant solution to find if a sequence of numbers is in order. This is for a web form, and I am giving the user a chance to number items and that will set up the order. I know the maximum number of items, and it should always start at one.

现在(我知道这是不正确的)我测试以确保所有数字都不同并加起来应该是什么(例如,对于我测试的三个项目,它加起来为 6).有没有人有更好/更准确的(因为有可能打破我的)解决方案?我正在使用 php,但我真正想要的是逻辑,因此您的示例可以是伪代码或任何相对容易阅读的语言.

Right now (I know it is not correct) I test to make sure all the numbers are different and add up to what it should (e.g. for three items I test it adds to 6). Does anyone have a better/more accurate (since it is possible to go break mine) solution? I am using php, but what I really want is logic so your example could be in pseudo-code or any relatively easy to read language.

推荐答案

只需对用户输入的数字进行排序,看看它们是否与您递增 1 的索引匹配.

Just sort the user-input numbers, and see if they match an index that you increment by 1.

nMax = 10
sortedUserArray = Sort(UserArray)

For i = 1 To nMax
    If Not sortedUserArray(i) = i Then
        ' Input not valid. 
        ' Throw an error or something. 
    End If
Next i

对于Sort部分,存在多种排序算法:Quicksort直接插入Heapsort 等.只需选择一个适合您的需求并进行搜索即可在网络上找到现成的程序.你选择的语言甚至可能有一些内置的排序算法,所以你甚至可能不需要看那么远.

For the Sort part, there exists a variety of sorting algorithms: Quicksort, Straight insertion, Heapsort, etc. Just pick one that fits your needs and do a search to find a ready-made procedure on the web. Your language of choice may even have some built-in sorting algorithms, so you might not even need to look that far.

这篇关于测试一系列数字以确保它们符合序列 1,2,3...n的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆