Determine if a string is collapsible: Difference between revisions
Content added Content deleted
m (elided the forced __TOC__ (table of contents).) |
No edit summary |
||
Line 456: | Line 456: | ||
length= 17 output=««« - Hary S Truman »»» |
length= 17 output=««« - Hary S Truman »»» |
||
═════════════════════════════════════════════════════════════════════════════════════════════════════════ |
═════════════════════════════════════════════════════════════════════════════════════════════════════════ |
||
</pre> |
|||
=={{header|Scala}}== |
|||
<lang Scala> |
|||
/**Collapse a string (if possible)*/ |
|||
def collapseString (s : String) : String = { |
|||
var res = s |
|||
for(i <- 0 to s.toList.length-2 by 1) if(s(i) == s(i+1)) res = res.take(i) ++ res.drop(i + 1) |
|||
res |
|||
} |
|||
/**Check if a string is collapsible*/ |
|||
def isCollapsible (s : String) : Boolean = if(collapseString(s).length == s.length) false else true |
|||
/**Display results as asked in the task*/ |
|||
def reportResults (s : String) : String = { |
|||
val sCollapsed = collapseString(s) |
|||
val originalRes = "ORIGINAL : length = " + s.length() + ", string = «««" + s + "»»»" |
|||
val collapsedRes = "COLLAPSED : length = " + sCollapsed.length() + ", string = «««" + sCollapsed + "»»»" |
|||
if(s.length != sCollapsed.length) originalRes + "\n" + collapsedRes + "\n" + "This string IS collapsible !" |
|||
else originalRes + "\n" + collapsedRes + "\n" + "This string is NOT collapsible !" |
|||
} |
|||
println(reportResults("The better the 4-whel drive, the further you'll be from help when ya get stuck!")) |
|||
println("------------") |
|||
println(reportResults("headmistressship")) |
|||
println("------------") |
|||
println(reportResults("ab cd ef")) |
|||
</lang> |
|||
{{out}} |
|||
<pre> |
|||
ORIGINAL : length = 79, string = «««The better the 4-whel drive, the further you'll be from help when ya get stuck!»»» |
|||
COLLAPSED : length = 77, string = «««The beter the 4-whel drive, the further you'l be from help when ya get stuck!»»» |
|||
This string IS collapsible ! |
|||
------------ |
|||
ORIGINAL : length = 16, string = «««headmistressship»»» |
|||
COLLAPSED : length = 14, string = «««headmistreship»»» |
|||
This string IS collapsible ! |
|||
------------ |
|||
ORIGINAL : length = 8, string = «««ab cd ef»»» |
|||
COLLAPSED : length = 8, string = «««ab cd ef»»» |
|||
This string is NOT collapsible ! |
|||
</pre> |
</pre> |
||