为测验生成随机(正面和负面)数字

时间:2016-10-20 00:31:54

标签: ios swift xcode

我正在xcode / swift为我的女儿写一个数学测验应用。
具体来说,我想产生一个问题,其中至少包含一个负数,要对第二个随机生成的数字加上或减去。
不能是两个正数。

即。

  

什么是(-45)减去12?
  什么是23减(-34)?

我正在努力使语法正确生成数字,然后决定所述数字是负数还是正数。

然后第二个问题是随机化,如果问题是加法或减法。

2 个答案:

答案 0 :(得分:1)

这是我的尝试。尝试在游乐场中运行它,它应该有希望得到你想要的结果。我希望我已经做得够干净了......

//: Playground - noun: a place where people can play

import Cocoa


let range = Range(uncheckedBounds: (-50, 50))

func generateRandomCouple() -> (a: Int, b: Int) {
    // This function will generate a pair of random integers
    // (a, b) such that at least a or b is negative.

    var first, second: Int

    repeat {
        first   = Int(arc4random_uniform(UInt32(range.upperBound - range.lowerBound))) - range.upperBound
        second  = Int(arc4random_uniform(UInt32(range.upperBound - range.lowerBound))) - range.upperBound
    }
        while (first > 0 && second > 0);

    // Essentially this loops until at least one of the two is less than zero.

    return (first, second)
}


let couple = generateRandomCouple();
print("What is \(couple.a) + (\(couple.b))")
// at this point, either of the variables is negative


// I don't think you can do it in the playground, but here you would read
// her input and the expected answer would, naturally, be:

print(couple.a + couple.b)

无论如何,请随时要求澄清。祝你好运!

答案 1 :(得分:1)

可以在不重复数字绘制的情况下解决此问题。我的想法是:

  1. 绘制一个正数或负数的随机数
  2. 如果数字为负数:从同一范围中抽取另一个数字并返回该对。
  3. 如果数字为正数:从约束为负数的范围中绘制第二个数字。
  4. 以下是实施:

    extension CountableClosedRange where Bound : SignedInteger {
    
        /// A property that returns a random element from the range.
        var random: Bound {
            return Bound(arc4random_uniform(UInt32(count.toIntMax())).toIntMax()) + lowerBound
        }
    
        /// A pair of random elements where always one element is negative.
        var randomPair: (Bound, Bound) {
            let first = random
            if first >= 0 {
                return (first, (self.lowerBound ... -1).random)
            }
            return (first, random)
        }
    }
    

    现在你可以写......

    let pair = (-10 ... 100).randomPair
    

    ...并获得一个随机元组,其中一个元素保证为负数。