Jump to content

Determine if a string is collapsible: Difference between revisions

Added Go
(Added Go)
Line 87:
 
__TOC__
 
=={{header|Go}}==
<lang go>package main
 
import "fmt"
 
// Returns collapsed string, original and new lengths in
// unicode code points (not normalized).
func collapse(s string) (string, int, int) {
r := []rune(s)
le, del := len(r), 0
for i := le - 2; i >= 0; i-- {
if r[i] == r[i+1] {
copy(r[i:], r[i+1:])
del++
}
}
if del == 0 {
return s, le, le
}
r = r[:le-del]
return string(r), le, len(r)
}
func main() {
strings:= []string {
"",
`"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln `,
"..1111111111111111111111111111111111111111111111111111111111111117777888",
"I never give 'em hell, I just tell the truth, and they think it's hell. ",
" --- Harry S Truman ",
"The better the 4-wheel drive, the further you'll be from help when ya get stuck!",
"headmistressship",
"aardvark",
"😍😀🙌💃😍😍😍🙌",
}
for _, s := range strings {
cs, olen, clen := collapse(s)
fmt.Printf("original : length = %2d, string = «««%s»»»\n", olen, s)
fmt.Printf("collapsed: length = %2d, string = «««%s»»»\n\n", clen, cs)
}
}</lang>
 
{{out}}
<pre>
original : length = 0, string = «««»»»
collapsed: length = 0, string = «««»»»
 
original : length = 72, string = «««"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln »»»
collapsed: length = 70, string = «««"If I were two-faced, would I be wearing this one?" - Abraham Lincoln »»»
 
original : length = 72, string = «««..1111111111111111111111111111111111111111111111111111111111111117777888»»»
collapsed: length = 4, string = «««.178»»»
 
original : length = 72, string = «««I never give 'em hell, I just tell the truth, and they think it's hell. »»»
collapsed: length = 69, string = «««I never give 'em hel, I just tel the truth, and they think it's hel. »»»
 
original : length = 72, string = ««« --- Harry S Truman »»»
collapsed: length = 17, string = ««« - Hary S Truman »»»
 
original : length = 80, string = «««The better the 4-wheel 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!»»»
 
original : length = 16, string = «««headmistressship»»»
collapsed: length = 14, string = «««headmistreship»»»
 
original : length = 8, string = «««aardvark»»»
collapsed: length = 7, string = «««ardvark»»»
 
original : length = 8, string = «««😍😀🙌💃😍😍😍🙌»»»
collapsed: length = 6, string = «««😍😀🙌💃😍🙌»»»
</pre>
 
=={{header|Julia}}==
9,492

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.