Advertisement
Guest User

Untitled

a guest
Feb 18th, 2021
178
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 1.70 KB | None | 0 0
  1. fun main() {
  2.     println(generateListOfLists(2, 5, 0, 100, 4))
  3. }
  4.  
  5. fun generateListOfLists(
  6.     minSize: Int,
  7.     maxSize: Int,
  8.     minNumber: Int,
  9.     maxNumber: Int,
  10.     numberOfLists: Int
  11. ): List<List<Int>> {
  12.     val sizes = generateDistinctSizes(minSize, maxSize, numberOfLists)
  13.     return generateLists(sizes, minNumber, maxNumber, mutableListOf(), 0)
  14. }
  15.  
  16. private fun generateDistinctSizes(
  17.     minSize: Int,
  18.     maxSize: Int,
  19.     numberOfLists: Int
  20. ): List<Int> {
  21.     val distinctRandomSizes = mutableSetOf<Int>()
  22.     while (distinctRandomSizes.size < numberOfLists) {
  23.         distinctRandomSizes.add((minSize..maxSize).random())
  24.     }
  25.     return distinctRandomSizes.toList()
  26. }
  27.  
  28. tailrec fun generateLists(
  29.     sizes: List<Int>,
  30.     minNumber: Int,
  31.     maxNumber: Int, acc: MutableList<List<Int>>, currentSizeIndex: Int
  32. ): List<List<Int>> {
  33.     return if (currentSizeIndex == sizes.size) {
  34.         acc
  35.     } else {
  36.         val size = sizes[currentSizeIndex]
  37.         acc.add(generateRandomSortedList(size, minNumber, maxNumber, chooseComparator(currentSizeIndex)))
  38.         generateLists(sizes, minNumber, maxNumber, acc, currentSizeIndex + 1)
  39.     }
  40. }
  41.  
  42. fun generateRandomSortedList(
  43.     size: Int,
  44.     minNumber: Int,
  45.     maxNumber: Int,
  46.     comparator: Comparator<Int>
  47. ): List<Int> =
  48.     List(size) { (minNumber..maxNumber).random() }
  49.         .sortedWith(comparator)
  50.  
  51.  
  52. fun chooseComparator(i: Int): Comparator<Int> =
  53.     if (i % 2 == 0)
  54.         ascending
  55.     else
  56.         descending
  57.  
  58. object ascending : Comparator<Int> {
  59.     override fun compare(x: Int, y: Int): Int = x - y
  60. }
  61.  
  62. object descending : Comparator<Int> {
  63.     override fun compare(x: Int, y: Int): Int = y - x
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement