生成 4 个不同的数字,加起来是 50 到 90 之间的总数

问题描述 投票:0回答:1

我需要通过这个单元测试:

 @Test
    fun dividingIntoFour() {
        repeat(100) {
            val randomNumber = Random.nextInt(50, 80)
            val total = 100 - randomNumber
            val numberList = divideIntoFourDistinctNumbersThatAddUptoTotal(total)
            assert(numberList.sum() == total)
            assert(!numberList.contains(0))
            assert(numberList.distinct().size == 4)
        }
    }

这和我得到的一样接近 - 它要么失败要么挂在循环上:

fun divideIntoFourDistinctNumbersThatAddUptoTotal(total: Int): List<Int> {
        var aTotal = total
        var first = (aTotal / 4..aTotal / 2).random()
        aTotal -= first
        var second = (3..aTotal - 3).random()
        while (second == first) {
            second = (3..aTotal - 3).random()
        }
        aTotal -= second
        var third = (3..aTotal).random()
        while (third == first || third == second) {
            third = (3..aTotal).random()
        }
        aTotal -= third
        var fourth = aTotal
        while (listOf(first, second, third, fourth).distinct().size != 4) {
            if (fourth == first) {
                fourth -= 1
                first += 1
            } else if (fourth == third) {
                fourth -= 1
                third += 1
            } else if (fourth == second) {
                fourth -= 1
                second += 1
            }
        }
        return listOf(first, second, third, fourth)
    }

此代码的目的是生成剩余的 4 个百分比值。 为第一个 Int 生成 50 到 80 之间的随机百分比。 然后 List 中最接近它的 int 获得下一个最大的百分比(Int),依此类推,对于 List 中的所有 5 个对象。

ChatGpt 在其 openai 网站和 github copilot 上都失败了。

kotlin distinct
1个回答
-1
投票
Sure, here are four distinct numbers that add up to a total between 50 and 90:

12 + 20 + 28 + 30 = 90
10 + 18 + 22 + 40 = 90
11 + 14 + 19 + 6 = 50
7 + 12 + 18 + 13 = 50
Note: There are many other combinations of four distinct numbers that add up to a total between 50 and 90, but these are just a few examples.
© www.soinside.com 2019 - 2024. All rights reserved.