Test a series of numbers to ensure they fit the sequence 1,2,3…n

孤街浪徒 提交于 2019-12-13 04:05:35

问题


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.

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

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.




回答2:


Since you know the maximum number of items, you can avoid a sort by simply allocating a boolean array and populating it. In pseudocode:

define numsInOneThruN (int xarr[], int sz):
    # Declare the boolean array and initialise to all false.

    declare isSet[1..sz]
    for all i in 1..sz:
        isSet[i] = false

    # For every number in list, if within range, set boolean value to true.

    for all i in xarr:
        if i >= 1 and i <= sz:
            isSet[i] = true

    # Check that all boolean values are true.

    for all i in 1..sz:
        if not isSet[i]:
            return false

    return true

This has the advantage of being O(n) time complexity rather than a best-case sort of O(n log n) - that probably won't matter for small data sets but it may become important for larger one.

You should also take into account the fact that this has a higher space complexity than an in-place sort since it uses an array equalt to the input size. That makes it O(n) space instead of the O(1) for the sort option.

As always, you can generally trade off space for time depending on your needs.




回答3:


If you already established that the numbers are all different, just check the minimum and the maximum values. There are only n different numbers which satisfy 1 <= x <= n.



来源:https://stackoverflow.com/questions/6435255/test-a-series-of-numbers-to-ensure-they-fit-the-sequence-1-2-3-n

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!