How to print all possible permutations (all possible orderings) of the words in Scala

3 Answers

0 votes
object Permutations {
  def main(args: Array[String]): Unit = {
    val words = List("Scala", "Programming", "Language")

    val permutations = words.permutations.toList

    for (perm <- permutations) {
      println(s"${perm(0)}, ${perm(1)}, ${perm(2)}")
    }
  }
}

  
  
/*
run:
    
Scala, Programming, Language
Scala, Language, Programming
Programming, Scala, Language
Programming, Language, Scala
Language, Scala, Programming
Language, Programming, Scala

*/

 



answered Jan 21, 2025 by avibootz
0 votes
object Main extends App {
  val words = List("word-1", "word-2", "word-3")

  words.permutations.foreach { perm =>
    println(perm.mkString(" "))
  }
}


/*
run:

word-1 word-2 word-3
word-1 word-3 word-2
word-2 word-1 word-3
word-2 word-3 word-1
word-3 word-1 word-2
word-3 word-2 word-1

*/

 



answered Apr 14 by avibootz
0 votes
object Main extends App {

  def print_words_permutations(words: List[String], current: List[String] = Nil): Unit = {
    if (words.isEmpty) {
      println(current.mkString(" "))
    } else {
      for (i <- words.indices) {
        val remaining = words.take(i) ++ words.drop(i + 1)
        print_words_permutations(remaining, current :+ words(i)) // Recursive permutation
      }
    }
  }

  val words = List("word-1", "word-2", "word-3")
  print_words_permutations(words)
}



/*
run:

word-1 word-2 word-3
word-1 word-3 word-2
word-2 word-1 word-3
word-2 word-3 word-1
word-3 word-1 word-2
word-3 word-2 word-1

*/

 



answered Apr 14 by avibootz

Related questions

...