How to get a random value from 1~N but excluding several specific values in PHP?

前端 未结 7 2046
不知归路
不知归路 2020-12-10 06:56

rand(1,N) but excluding array(a,b,c,..),

is there already a built-in function that I don\'t know or do I have to implement it myself(how?)

7条回答
  •  悲&欢浪女
    2020-12-10 07:08

    What you need to do is calculate an array of skipped locations so you can pick a random position in a continuous array of length M = N - #of exceptions and easily map it back to the original array with holes. This will require time and space equal to the skipped array. I don't know php from a hole in the ground so forgive the textual semi-psudo code example.

    1. Make a new array Offset[] the same length as the Exceptions array.
    2. in Offset[i] store the first index in the imagined non-holey array that would have skipped i elements in the original array.
    3. Now to pick a random element. Select a random number, r, in 0..M the number of remaining elements.
    4. Find i such that Offset[i] <= r < Offest[i+i] this is easy with a binary search
    5. Return r + i

    Now, that is just a sketch you will need to deal with the ends of the arrays and if things are indexed form 0 or 1 and all that jazz. If you are clever you can actually compute the Offset array on the fly from the original, it is a bit less clear that way though.

提交回复
热议问题