import kotlin.test.* class T2Test { @Test fun evenSplitRemainderToFirst() = assertEquals(listOf(34L, 33L, 33L), allocate(100, listOf(1, 1, 1))) @Test fun exactSplit() = assertEquals(listOf(300L, 0L, 400L), allocate(700, listOf(3, 0, 4))) @Test fun largestRemainderNotFirstIndex() = assertEquals(listOf(3L, 7L), allocate(10, listOf(1, 2))) @Test fun tieGoesToLowerIndex() = assertEquals(listOf(1L, 0L), allocate(1, listOf(1, 1))) @Test fun tieAmongSeveral() = assertEquals(listOf(1L, 1L, 0L, 0L), allocate(2, listOf(1, 1, 1, 1))) @Test fun zeroWeightGetsNothing() = assertEquals(listOf(0L, 3L, 2L), allocate(5, listOf(0, 1, 1))) @Test fun zeroTotal() = assertEquals(listOf(0L, 0L), allocate(0, listOf(5, 7))) @Test fun negativeMirrors() { assertEquals(listOf(-34L, -33L, -33L), allocate(-100, listOf(1, 1, 1))) assertEquals(listOf(-3L, -7L), allocate(-10, listOf(1, 2))) } @Test fun singleParty() = assertEquals(listOf(-12345L), allocate(-12345, listOf(9))) @Test fun rejectsInvalidWeights() { assertFailsWith { allocate(100, emptyList()) } assertFailsWith { allocate(100, listOf(1, -1)) } assertFailsWith { allocate(100, listOf(0, 0)) } } @Test fun noOverflowLargeTotalAndWeights() { val r = allocate(Long.MAX_VALUE, listOf(Int.MAX_VALUE, Int.MAX_VALUE)) assertEquals(listOf(Long.MAX_VALUE / 2 + 1, Long.MAX_VALUE / 2), r) } @Test fun noOverflowManyLargeWeights() { val w = List(10) { Int.MAX_VALUE } val r = allocate(Long.MAX_VALUE, w) assertEquals(Long.MAX_VALUE, r.fold(0L) { a, b -> Math.addExact(a, b) }) assertTrue(r.all { it == Long.MAX_VALUE / 10 || it == Long.MAX_VALUE / 10 + 1 }) } @Test fun minPlusOneMirrors() { val r = allocate(Long.MIN_VALUE + 1, listOf(1, 1)) assertEquals(listOf(-(Long.MAX_VALUE / 2 + 1), -(Long.MAX_VALUE / 2)), r) } @Test fun sumAlwaysExactRandomized() { val rnd = java.util.Random(42) repeat(2000) { val n = 1 + rnd.nextInt(6) val w = List(n) { rnd.nextInt(1000) }.let { if (it.all { x -> x == 0 }) it.mapIndexed { i, x -> if (i == 0) 1 else x } else it } val total = rnd.nextLong() / (1 + rnd.nextInt(1000)) val r = allocate(total, w) assertEquals(total, r.sum(), "total=$total w=$w") val sw = w.sumOf { it.toLong() }.toBigDecimal() r.zip(w).forEach { (s, wi) -> val exact = (total.toBigDecimal().setScale(40) * wi.toBigDecimal()).divide(sw, java.math.RoundingMode.HALF_EVEN) assertTrue((s.toBigDecimal() - exact).abs() < java.math.BigDecimal.ONE, "share $s exact $exact") } } } }