开发者

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

开发者 https://www.devze.com 2023-03-14 08:56 出处:网络
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 ord

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.


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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号