Search code examples
scalalistswap

how can I swap a random index from a list in scala?


I know how to do like this when you know which values to swap

val li: List[Int] = List(1.1,2.2,3.1, 1.11, 2.1)

li.updated(0,li(2)).updated(2,li(0))

But, how about if you wanna swap completely 2 random indexes, how would you do that??


Solution

  • val li: List[Double] = List( . . )
    
    val x = util.Random.nextInt(li.length)
    val y = util.Random.nextInt(li.length)
    
    li.updated(x,li(y)).updated(y,li(x))
    

    Note: There might be no swap when x == y but this is still safe, even for a small List.