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

Create your online store today with Shopify

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

Disclosure: My content contains affiliate links.

43,406 questions

56,397 answers

573 users

How to use XOR to swap two characters in a string in Scala

1 Answer

0 votes
object XorSwapProgram {

  /** Swaps two characters in a character array in-place using the XOR swap algorithm.
    *
    * @note This function demonstrates bitwise XOR swapping for educational purposes.
    *       In production Scala code, using pattern matching or a temporary variable
    *       is strongly preferred for clarity and compiler optimizations.
    *
    * @param text  Mutable array of characters containing elements to swap.
    * @param left  Zero-based index of the first character.
    * @param right Zero-based index of the second character.
    */
  def xorSwapCharacters(text: Array[Char], left: Int, right: Int): Unit = {
    // Bounds checking, null check, and empty array protection
    if (text == null || text.isEmpty || left < 0 || left >= text.length || right < 0 || right >= text.length) {
      return
    }

    // XOR swap fails if left == right because (x ^ x) evaluates to 0
    if (left == right) {
      return
    }

    // Perform bitwise XOR and cast the resulting Int back to Char
    text(left)  = (text(left) ^ text(right)).toChar
    text(right) = (text(right) ^ text(left)).toChar
    text(left)  = (text(left) ^ text(right)).toChar
  }

  def main(args: Array[String]): Unit = {
    val original: String = "hello"
    val textArray: Array[Char] = original.toCharArray

    println(s"Before: ${new String(textArray)}")

    xorSwapCharacters(textArray, 1, 4)

    val result: String = new String(textArray)
    println(s"After:  $result")
  }
}



/*
run:

Before: hello
After:  holle

*/

 



answered 5 days ago by avibootz
...