Split a random value into four that sum up to it

后端 未结 6 887
被撕碎了的回忆
被撕碎了的回忆 2020-12-20 05:50

I have one value like 24, and I have four textboxes. How can I dynamically generate four values that add up to 24?

All the values must be integers and can\'t be nega

6条回答
  •  醉酒成梦
    2020-12-20 06:29

    For your stated problem, it is possible to generate an array of all possible solutions and then pick one randomly. There are in fact 1,770 possible solutions.

    var solutions = [[Int]]()
    
    for i in 1...21 {
        for j in 1...21 {
            for k in 1...21 {
                let l = 24 - (i + j + k)
                if l > 0 && !(i == 6 && j == 6 && k == 6) {
                    solutions.append([i, j, k, l])
                }
            }
        }
    }
    
    // Now generate 20 solutions
    for _ in 1...20 {
        let rval = Int(arc4random_uniform(UInt32(solutions.count)))
        println(solutions[rval])
    }
    

    This avoids any bias at the cost of initial setup time and storage.


    This could be improved by:

    • Reducing storage space by only storing the first 3 numbers. The 4th one is always 24 - (sum of first 3)
    • Reducing storage space by storing each solution as a single integer: (i * 10000 + j * 100 + k)
    • Speeding up the generation of solutions by realizing that each loop doesn't need to go to 21.

    Here is the solution that stores each solution as a single integer and optimizes the loops:

    var solutions = [Int]()
    
    for i in 1...21 {
        for j in 1...22-i {
            for k in 1...23-i-j {
                if !(i == 6 && j == 6 && k == 6) {
                    solutions.append(i * 10000 + j * 100 + k)
                }
            }
        }
    }
    
    // Now generate 20 solutions
    for _ in 1...20 {
        let rval = Int(arc4random_uniform(UInt32(solutions.count)))
        let solution = solutions[rval]
    
        // unpack the values
        let i = solution / 10000
        let j = (solution % 10000) / 100
        let k = solution % 100
        let l = 24 - (i + j + k)
    
        // print the solution
        println("\([i, j, k, l])")
    }
    

提交回复
热议问题