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
*/