Quick actions

cmd+k|ctrl+k

Navigation

Languages

Random split number

Snippet info

Language

Nim

Visibility

public

Author

7sdream

Created

2018-06-22T07:39:15Z

Updated

2018-06-22T07:39:15Z

import random, strutils

randomize()

proc randomCut(num: Natural, count: Natural): seq[Natural] =
    result = newSeq[Natural](count)
    let numStr = $num
    let length = numStr.len
    assert(count > 0 and count <= length)
    var j = 0
    for i in 0 ..< count:
        var resultStr = ""
        while j < length:
            resultStr.add(numStr[j])
            j += 1
            if (i == count - 1): continue
            if (length - j <= count - i - 1): break
            if rand(length - j - 1) < count - i - 1: break
        result[i] = resultStr.parseInt.Natural

let num = 123456789

for i in 0 ..< 100:
    echo num.randomCut(3)
INFO