Created
June 23, 2018 23:15
-
-
Save vicsstar/999b0e4bf5f1c7cf11099e6e0865f7aa to your computer and use it in GitHub Desktop.
Reverses a phrases/sentences without reversing the characters in the words.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
object ReverseSentence extends App { | |
if (args == null || args.length == 0) { | |
printf("%d arguments found; 2 arguments required.", Option(args).map(_.length).getOrElse(0)) | |
sys.exit(0); | |
} | |
if (args(0) == args(1)) { | |
println("The string parameters are equal.") | |
sys.exit(0) | |
} | |
var str = args(0).toCharArray(); | |
val goal = args(1).toCharArray(); | |
println("Original: '" + new String(str) + "'"); | |
reverse(str); | |
val success = new String(str).equals(new String(goal)); | |
println("Reversed: '" + new String(str) + "'\n\nReverse " | |
+ (if (success) "succeeded." else "failed!")); | |
def reverse(s: Array[Char]): Unit = { | |
var str = ""; | |
var newWord = ""; | |
for (i <- (s.length - 1) to 0 by -1) { | |
val char = s(i); | |
if (char != ' ') { | |
newWord = char + newWord; | |
} else { | |
str += newWord + char; | |
newWord = ""; | |
} | |
} | |
str += newWord; | |
for (i <- 0 until s.length) { | |
s(i) = str.charAt(i); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment