Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,623 questions

55,358 answers

573 users

How to generate all possible permutations and combinations of an array of chars in Scala

1 Answer

0 votes
object PermutationsAndCombinations {

  // Print a sequence of characters
  def printSeq(seq: Seq[Char]): Unit =
    println(seq.mkString(" "))

  // Recursive function to generate permutations
  def permute(arr: Array[Char], l: Int, r: Int): Unit = {
    if (l == r) {
      printSeq(arr)
    } else {
      for (i <- l to r) {
        swap(arr, l, i)
        permute(arr, l + 1, r)
        swap(arr, l, i) // backtrack
      }
    }
  }

  // Swap two elements in an array
  def swap(arr: Array[Char], i: Int, j: Int): Unit = {
    val tmp = arr(i)
    arr(i) = arr(j)
    arr(j) = tmp
  }

  // Generate all combinations using bitmask
  def generateCombinations(arr: Array[Char]): Unit = {
    val size = arr.length
    for (mask <- 1 until (1 << size)) {
      val combo = for {
        i <- 0 until size
        if (mask & (1 << i)) != 0
      } yield arr(i)
      println(combo.mkString(" "))
    }
  }

  def main(args: Array[String]): Unit = {
    val input = Array('a', 'b', 'c')
    val size = input.length

    println("All permutations:")
    permute(input.clone(), 0, size - 1)

    println("\nAll combinations:")
    generateCombinations(input)
  }
}




/*
run:

All permutations:
a b c
a c b
b a c
b c a
c b a
c a b

All combinations:
a
b
a b
c
a c
b c
a b c

*/

 



answered Nov 22, 2025 by avibootz

Related questions

...