提出
{var l=it
var n=0
while(l>0){n++
val r=mutableListOf(1)
var t=3
var i=3
while(t<=l){r.add(t)
t+=i
i++}
l-=r.lastOrNull{l==it|| r.contains(l-it)}?:r[0]}
n}
美化
{
// Make a mutable copy of the input
var l=it
// Keep track of the number of items removed
var n=0
// While we still need to remove pebbles
while (l > 0) {
// Increase removed count
n++
// BEGIN: Create a list of triangle numbers
val r= mutableListOf(1)
var t = 3
var i = 3
while (t<= l) {
// Add the number to the list and calculate the next one
r.add(t)
t+=i
i++
}
// END: Create a list of triangle numbers
// Get the fitting pebble, or the biggest one if none fit or make a perfect gap
l -= r.lastOrNull {l==it|| r.contains(l-it)} ?: r[0]
}
//Return the number of pebbles
n
}
テスト
var r:(Int)->Int =
{var l=it
var n=0
while(l>0){n++
val r=mutableListOf(1)
var t=3
var i=3
while(t<=l){r.add(t)
t+=i
i++}
l-=r.lastOrNull{l==it|| r.contains(l-it)}?:r[0]}
n}
data class TestData(val input:Int, val output:Int)
fun main(args: Array<String>) {
val tests = listOf(
TestData(1,1),
TestData(2,2),
TestData(3,1),
TestData(4,2),
TestData(5,3),
TestData(6,1),
TestData(7,2),
TestData(8,3),
TestData(9,2),
TestData(10,1),
TestData(11,2),
TestData(12,2),
TestData(13,2),
TestData(14,3),
TestData(15,1),
TestData(16,2),
TestData(17,3),
TestData(18,2),
TestData(19,3),
TestData(20,2),
TestData(100,2),
TestData(101,2),
TestData(5050,1)
)
tests.map { it to r(it.input) }.filter { it.first.output != it.second }.forEach { println("Failed for ${it.first}, output ${it.second} instead") }
}
TryItOnline