Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.lang.IllegalStateException
- fun main() {
- val elementsA = listOf(0, 1, 2, 3, 4)
- val elementsB = listOf(5, 6, 7)
- for (i in 0..1000) {
- val pairs: MutableSet<Pair<Int, Int>> = combineToPairs(elementsA, elementsB)
- check(pairs, elementsA.size)
- println("$pairs\n")
- }
- }
- fun combineToPairs(listA: List<Int>, listB: List<Int>, combinations: Int = 10): MutableSet<Pair<Int, Int>> {
- val result = mutableSetOf<Pair<Int, Int>>() // LinkedHashSet
- val listACopy = listA.shuffled().toMutableList()
- var i = 0
- var j = 0
- while (result.size < combinations) {
- val added = result.add(listACopy[i++] to listB[j])
- if (!added) {
- // Rollback previously added elements
- //println("${"-".repeat(20)}ROLLBACK${"-".repeat(20)}")
- val timesListAAdded = result.size / listA.size
- val uniquePairs = result.take(listA.size * timesListAAdded)
- result.replaceWith(uniquePairs)
- listACopy.replaceWith(uniquePairs.takeLast(listA.size).map { it.first })
- j = listB.indexOf(result.last().second)
- }
- if (i == listACopy.size || !added) {
- val listTemp = listACopy.toMutableList()
- while (listTemp == listACopy || listTemp.first() == listACopy.last()) {
- listTemp.shuffle()
- }
- listACopy.replaceWith(listTemp)
- i = 0
- }
- j = ++j % listB.size
- }
- return result
- }
- fun <T> MutableCollection<T>.replaceWith(newElements: Collection<T>) {
- clear()
- addAll(newElements)
- }
- fun check(pairs: MutableSet<Pair<Int, Int>>, size: Int) {
- val halves = pairs.chunked(size)
- val firstNumbers = halves.map { half ->
- val nums = half.map { it.first }
- print(nums)
- LinkedHashSet(nums)
- }
- println(" <- first numbers of pairs")
- val isFirstNumbersCombinationsUnique = firstNumbers.map { it.toList() }.toSet().size == firstNumbers.size
- val actualSecondNumbers = pairs.map { it.second }
- val expectedSecondNumbers = listOf(5, 6, 7, 5, 6, 7, 5, 6, 7, 5)
- val isHalvesWithCorrectSize = firstNumbers.all { it.size == size }
- if (!isHalvesWithCorrectSize) {
- throw IllegalStateException("halves have duplicates of first numbers")
- }
- if (!isFirstNumbersCombinationsUnique){
- throw IllegalStateException("halves have the same combinations of first numbers")
- }
- if (actualSecondNumbers != expectedSecondNumbers) {
- throw IllegalStateException("seconds numbers are incorrect")
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement