Determine if a string is collapsible: Difference between revisions

Add Refal
(Add Refal)
 
(44 intermediate revisions by 25 users not shown)
Line 80:
{{Template:Strings}}
<br><br>
 
=={{header|11l}}==
{{trans|Kotlin}}
 
<syntaxhighlight lang="11l">F collapse(s)
V cs = ‘’
V last = Char("\0")
L(c) s
I c != last
cs ‘’= c
last = c
R cs
 
V strings = [
‘’,
‘"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’
]
 
L(s) strings
V c = collapse(s)
print(‘original : length = ’s.len‘, string = <<<’s‘>>>’)
print(‘collapsed : length = ’c.len‘, string = <<<’c‘>>>’)
print()</syntaxhighlight>
 
{{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>>>
 
</pre>
 
=={{header|8080 Assembly}}==
 
<langsyntaxhighlight lang="8080asm">bdos: equ 5
puts: equ 9
org 100h
Line 183 ⟶ 240:
db 'and they think it',39,'s hell. $'
str5: db ' '
db ' --- Harry S Truman $'</langsyntaxhighlight>
 
{{out}}
Line 199 ⟶ 256:
</pre>
 
=={{header|Action!}}==
<syntaxhighlight lang="action!">PROC Collapse(CHAR ARRAY in,out)
BYTE i,j
CHAR c
 
j=1 c=0
FOR i=1 TO in(0)
DO
IF in(i)#c THEN
c=in(i)
out(j)=c
j==+1
FI
OD
out(0)=j-1
RETURN
 
PROC Test(CHAR ARRAY s)
CHAR ARRAY c(100)
BYTE CH=$02FC ;Internal hardware value for last key pressed
 
Collapse(s,c)
PrintF("<<<%S>>> (len=%B)%E",s,s(0))
PrintF("<<<%S>>> (len=%B)%E",c,c(0))
PutE()
PrintE("Press any key to continue")
PutE()
 
DO UNTIL CH#$FF OD
CH=$FF
RETURN
 
PROC Main()
Test("")
Test("""If I were two-faced, would I be wearing this one?"" --- Abraham Lincoln ")
Test("..1111111111111111111111111111111111111111111111111111111111111117777888")
Test("I never give 'em hell, I just tell the truth, and they think it's hell. ")
Test(" --- Harry S Truman ")
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Determine_if_a_string_is_collapsible.png Screenshot from Atari 8-bit computer]
<pre>
<<<>>> (len=0)
<<<>>> (len=0)
 
<<<"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln >>> (len=72)
<<<"If I were two-faced, would I be wearing this one?" - Abraham Lincoln >>> (len=70)
 
<<<..1111111111111111111111111111111111111111111111111111111111111117777888>>> (len=72)
<<<.178>>> (len=4)
 
<<<I never give 'em hell, I just tell the truth, and they think it's hell. >>> (len=72)
<<<I never give 'em hel, I just tel the truth, and they think it's hel. >>> (len=69)
 
<<< --- Harry S Truman >>> (len=72)
<<< - Hary S Truman >>> (len=17)
</pre>
 
=={{header|Ada}}==
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO; use Ada.Text_IO;
procedure Test_Collapsible is
procedure Collapse (S : in String) is
Line 223 ⟶ 337:
Collapse (" --- Harry S Truman ");
end Test_Collapsible;
</syntaxhighlight>
</lang>
 
{{out}}
Line 238 ⟶ 352:
 
=={{header|ALGOL 68}}==
<langsyntaxhighlight lang="algol68">BEGIN
# returns a collapsed version of s #
# i.e. s with adjacent duplicate characters removed #
Line 270 ⟶ 384:
OD
END
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 288 ⟶ 402:
{{works with|Dyalog APL}}
 
<langsyntaxhighlight APLlang="apl">task←{
⍝ Collapse a string
collapse←{(1,¯1↓⍵≠1⌽⍵)/⍵}
Line 314 ⟶ 428:
⍝ Collapse each string and display it as specified
↑collapse display¨ strs
}</langsyntaxhighlight>
 
{{out}}
Line 330 ⟶ 444:
17 ««« - Hary S Truman »»»
</pre>
 
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebol">lines: [
{::}
{:"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 :}
]
 
loop lines 'line ->
print squeeze line</syntaxhighlight>
 
{{out}}
 
<pre>
"If I were two-faced, would I be wearing this one?" - Abraham Lincoln
.178
I never give 'em hel, I just tel the truth, and they think it's hel.
- Hary S Truman</pre>
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">collapsible_string(str){
for i, ch in StrSplit(str){
if (ch <> prev)
Line 339 ⟶ 474:
}
return "original string:`t" StrLen(str) " characters`t«««" str "»»»`nresultant string:`t" StrLen(res) " characters`t«««" res "»»»"
}</langsyntaxhighlight>
Examples:<langsyntaxhighlight AutoHotkeylang="autohotkey">data := [""
, """If I were two-faced, would I be wearing this one?"" --- Abraham Lincoln "
, "..1111111111111111111111111111111111111111111111111111111111111117777888"
Line 347 ⟶ 482:
for i, v in data
MsgBox % := collapsible_string(v)
return</langsyntaxhighlight>
Outputs:<pre>-----------------------------------------
original string: 0 characters «««»»»
Line 364 ⟶ 499:
resultant string: 17 characters ««« - Hary S Truman »»»
-----------------------------------------</pre>
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f DETERMINE_IF_A_STRING_IS_COLLAPSIBLE.AWK
BEGIN {
Line 396 ⟶ 532:
printf("new: %2d <<<%s>>>\n\n",length(new_str),new_str)
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 425 ⟶ 561:
 
=={{header|BaCon}}==
<langsyntaxhighlight lang="bacon">DATA ""
DATA "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln "
DATA "..1111111111111111111111111111111111111111111111111111111111111117777888"
Line 445 ⟶ 581:
NEXT
PRINT ">>> - length: ", found
DONE</langsyntaxhighlight>
{{out}}
<pre><<<>>> - length: 0
Line 464 ⟶ 600:
=={{header|BASIC}}==
 
<langsyntaxhighlight lang="basic">10 READ N%
20 FOR A% = 1 TO N%
30 READ I$: GOSUB 100
Line 489 ⟶ 625:
430 DATA "..1111111111111111111111111111111111111111111111111111111111111117777888"
440 DATA "I never give 'em hell, I just tell the truth, and they think it's hell. "
450 DATA " --- Harry S Truman "</langsyntaxhighlight>
 
{{out}}
Line 508 ⟶ 644:
17 <<< - Hary S Truman >>>
</pre>
 
=={{header|BCPL}}==
<syntaxhighlight lang="bcpl">get "libhdr"
 
// Collapse a string
let collapse(in, out) = valof
$( let o = 0
for i = 1 to in%0
unless i>1 & in%i = in%(i-1)
$( o := o + 1
out%o := in%i
$)
out%0 := o
resultis out
$)
 
// Print string with brackets and length
let brackets(s) be
writef("%N: <<<%S>>>*N", s%0, s)
 
// Print original and collapsed version
let show(s) be
$( let v = vec 1+255/BYTESPERWORD
brackets(s)
brackets(collapse(s, v))
wrch('*N')
$)
 
let start() be
$( show("")
show("*"If I were two-faced, would I be wearing this one?*" --- Abraham Lincoln ")
show("..1111111111111111111111111111111111111111111111111111111111111111111788")
show("I never give 'em hell, I just tell the truth, and they think it's hell. ")
show(" --- Harry S Truman ")
$)</syntaxhighlight>
{{out}}
<pre>0: <<<>>>
0: <<<>>>
 
72: <<<"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln >>>
70: <<<"If I were two-faced, would I be wearing this one?" - Abraham Lincoln >>>
 
72: <<<..1111111111111111111111111111111111111111111111111111111111111111111788>>>
4: <<<.178>>>
 
72: <<<I never give 'em hell, I just tell the truth, and they think it's hell. >>>
69: <<<I never give 'em hel, I just tel the truth, and they think it's hel. >>>
 
72: <<< --- Harry S Truman >>>
17: <<< - Hary S Truman >>></pre>
=={{header|BQN}}==
 
The base function is very simple: Keep adjacent unequal characters, make sure first character is always preserved.
 
<syntaxhighlight lang="bqn">Collapse←(≠↑1∾1↓≠⟜»)⊸/
 
>{
c←Collapse 𝕩
⟨⟨≠𝕩 ⋄ "<<<"∾𝕩∾">>>"⟩≍⟨≠c ⋄ "<<<"∾c∾">>>"⟩⟩
}¨⟨
"The better the 4-wheel drive, the further you'll be from help when ya get stuck!"
"headmistressship"
""
"""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 "
⟩</syntaxhighlight><syntaxhighlight lang="text">┌─
╵ ┌─
╵ 80 "<<<The better the 4-wheel drive, the further you'll be from help when ya get stuck!>>>"
77 "<<<The beter the 4-whel drive, the further you'l be from help when ya get stuck!>>>"
┌─
╵ 16 "<<<headmistressship>>>"
14 "<<<headmistreship>>>"
┌─
╵ 0 "<<<>>>"
0 "<<<>>>"
┌─
╵ 72 "<<<""If I were two-faced, would I be wearing this one?"" --- Abraham Lincoln >>>"
70 "<<<""If I were two-faced, would I be wearing this one?"" - Abraham Lincoln >>>"
┌─
╵ 72 "<<<..1111111111111111111111111111111111111111111111111111111111111117777888>>>"
4 "<<<.178>>>"
┌─
╵ 72 "<<<I never give 'em hell, I just tell the truth, and they think it's hell. >>>"
69 "<<<I never give 'em hel, I just tel the truth, and they think it's hel. >>>"
┌─
╵ 72 "<<< --- Harry S Truman >>>"
17 "<<< - Hary S Truman >>>"
┘</syntaxhighlight>
 
=={{header|Bracmat}}==
<langsyntaxhighlight Bracmatlang="bracmat"> ( colapse
= previous
. str
Line 538 ⟶ 771:
$ "I never give 'em hell, I just tell the truth, and they think it's hell. "
& testcolapse
$ " --- Harry S Truman "</langsyntaxhighlight>
'''Output'''
<pre>«««»»» 0
Line 554 ⟶ 787:
Identical implementation as in [[Determine_if_a_string_is_squeezable]], as both tasks are very similar. The Lincoln quote contains backslashes to accommodate the double quotes via the command line. strcmpi is not part of the C Standard Library, thus comment out the definition in the code if testing on a system where it is already included.
 
<syntaxhighlight lang="c">
<lang C>
#include<string.h>
#include<stdlib.h>
Line 725 ⟶ 958:
return 0;
}
</syntaxhighlight>
</lang>
Output :
<pre>
Line 778 ⟶ 1,011:
</pre>
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">using System;
using static System.Linq.Enumerable;
 
Line 804 ⟶ 1,037:
static string Collapse(string s) => string.IsNullOrEmpty(s) ? "" :
s[0] + new string(Range(1, s.Length - 1).Where(i => s[i] != s[i - 1]).Select(i => s[i]).ToArray());
}</langsyntaxhighlight>
{{out}}
<pre>
Line 825 ⟶ 1,058:
=={{header|C++}}==
The solution is a straightforward application of the standard library function "unique".
<langsyntaxhighlight lang="cpp">#include <string>
#include <iostream>
#include <algorithm>
Line 850 ⟶ 1,083:
test(" --- Harry S Truman ");
return 0;
}</langsyntaxhighlight>
 
{{out}}
Line 871 ⟶ 1,104:
 
=={{header|Clojure}}==
<syntaxhighlight lang="clojure">
<lang Clojure>
(defn collapse [s]
(let [runs (partition-by identity s)]
Line 880 ⟶ 1,113:
(str (format "Input: <<<%s>>> (len %d)\n" s (count s))
(format "becomes: <<<%s>>> (len %d)\n" out (count out)))))
</syntaxhighlight>
</lang>
 
{{out}}
Line 895 ⟶ 1,128:
becomes: <<< - Hary S Truman >>> (len 17)
</pre>
 
=={{header|CLU}}==
<syntaxhighlight lang="clu">% Collapse a string
collapse = proc (s: string) returns (string)
out: array[char] := array[char]$[]
last: char := '\000'
for c: char in string$chars(s) do
if c ~= last then
last := c
array[char]$addh(out,c)
end
end
return (string$ac2s(out))
end collapse
 
% Show a string in brackets, with its length
brackets = proc (s: string)
stream$putl(stream$primary_output(),
int$unparse(string$size(s))
|| " <<<"
|| s
|| ">>>")
end brackets
 
% Show a string and its collapsed version, and the corresponding lengths
show = proc (s: string)
brackets(s)
brackets(collapse(s))
stream$putl(stream$primary_output(), "")
end show
 
% Try the examples from the task description
start_up = proc ()
examples: array[string] := array[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 "
]
for ex: string in array[string]$elements(examples) do
show(ex)
end
end start_up</syntaxhighlight>
{{out}}
<pre>0 <<<>>>
0 <<<>>>
 
72 <<<"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln >>>
70 <<<"If I were two-faced, would I be wearing this one?" - Abraham Lincoln >>>
 
72 <<<..1111111111111111111111111111111111111111111111111111111111111117777888>>>
4 <<<.178>>>
 
72 <<<I never give 'em hell, I just tell the truth, and they think it's hell. >>>
69 <<<I never give 'em hel, I just tel the truth, and they think it's hel. >>>
 
72 <<< --- Harry S Truman >>>
17 <<< - Hary S Truman >>></pre>
 
=={{header|Cowgol}}==
<syntaxhighlight lang="cowgol">include "cowgol.coh";
include "strings.coh";
 
# Collapse the string at in, and store the result in the given buffer
sub collapse(in: [uint8], out: [uint8]) is
var ch := [in];
in := @next in;
loop
if ch == 0 then
[out] := 0;
return;
elseif [in] != ch then
[out] := ch;
out := @next out;
ch := [in];
end if;
in := @next in;
end loop;
end sub;
 
# Given a string, collapse it and print all required output
sub show(str: [uint8]) is
sub bracket_length(str: [uint8]) is
print_i32(StrLen(str) as uint32);
print(" <<<");
print(str);
print(">>>");
print_nl();
end sub;
var buf: uint8[256];
collapse(str, &buf[0]);
bracket_length(str);
bracket_length(&buf[0]);
print_nl();
end sub;
 
# Strings from the task
var strings: [uint8][] := {
"",
"\"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 "
};
 
# Collapse and print each string
var i: @indexof strings := 0;
while i < @sizeof strings loop
show(strings[i]);
i := i + 1;
end loop;</syntaxhighlight>
 
{{out}}
 
<pre>0 <<<>>>
0 <<<>>>
 
72 <<<"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln >>>
70 <<<"If I were two-faced, would I be wearing this one?" - Abraham Lincoln >>>
 
72 <<<..1111111111111111111111111111111111111111111111111111111111111117777888>>>
4 <<<.178>>>
 
72 <<<I never give 'em hell, I just tell the truth, and they think it's hell. >>>
69 <<<I never give 'em hel, I just tel the truth, and they think it's hel. >>>
 
72 <<< --- Harry S Truman >>>
17 <<< - Hary S Truman >>></pre>
 
=={{header|D}}==
<langsyntaxhighlight lang="d">import std.stdio;
 
void collapsible(string s) {
Line 923 ⟶ 1,288:
collapsible(`I never give 'em hell, I just tell the truth, and they think it's hell. `);
collapsible(` --- Harry S Truman `);
}</langsyntaxhighlight>
{{out}}
<pre>old: <<<>>>, length = 0
Line 939 ⟶ 1,304:
old: <<< --- Harry S Truman >>>, length = 72
new: <<< - Hary S Truman >>>, length = 17</pre>
=={{header|Delphi}}==
{{libheader| System.SysUtils}}
{{Trans|D}}
<syntaxhighlight lang="delphi">
program Determine_if_a_string_is_collapsible;
 
{$APPTYPE CONSOLE}
 
uses
System.SysUtils;
 
procedure collapsible(s: string);
var
c, last: char;
len: Integer;
begin
writeln('old: <<<', s, '>>>, length = ', s.length);
write('new: <<<');
last := #0;
len := 0;
for c in s do
begin
if c <> last then
begin
write(c);
inc(len);
end;
last := c;
end;
writeln('>>>, length = ', len, #10);
end;
 
begin
collapsible('');
collapsible('"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ');
collapsible('..1111111111111111111111111111111111111111111111111111111111111117777888');
collapsible('I never give ''em hell, I just tell the truth, and they think it''s hell. ');
collapsible(' --- Harry S Truman ');
readln;
end.</syntaxhighlight>
 
=={{header|EasyLang}}==
<syntaxhighlight>
func$ collapse s$ .
for c$ in strchars s$
if c$ <> cc$
r$ &= c$
.
cc$ = c$
.
return r$
.
s$[] &= ""
s$[] &= "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln "
s$[] &= "..1111111111111111111111111111111111111111111111111111111111111117777888"
s$[] &= "I never give 'em hell, I just tell the truth, and they think it's hell. "
s$[] &= " --- Harry S Truman "
for s$ in s$[]
print "«««" & s$ & "»»» (" & len s$ & ")"
r$ = collapse s$
print "«««" & r$ & "»»» (" & len r$ & ")"
print ""
.
</syntaxhighlight>
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">
// Collapse a String. Nigel Galloway: June 9th., 2020
//As per the task description a function which 'determines if a character string is collapsible' by testing if any consecutive characters are the same.
Line 959 ⟶ 1,388:
collapse " --- Harry S Truman "
collapse "withoutConsecutivelyRepeatedCharacters"
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 971 ⟶ 1,400:
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: formatting io kernel sbufs sequences strings ;
IN: rosetta-code.string-collapse
 
Line 999 ⟶ 1,428:
} [ show-collapse ] each ;
 
MAIN: collapse-demo</langsyntaxhighlight>
{{out}}
(Using some extra test cases from the Go entry.)
Line 1,034 ⟶ 1,463:
=={{header|FreeBASIC}}==
{{trans|BASIC}}
<langsyntaxhighlight lang="freebasic">Const numCad = 5
Data ""
Data "'If I were two-faced, would I be wearing this one?' --- Abraham Lincoln "
Line 1,064 ⟶ 1,493:
Next j
Sleep
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,088 ⟶ 1,517:
</pre>
 
=={{header|Frink}}==
<syntaxhighlight lang="frink">collapse[str] := str =~ %s/(.)\1+/$1/g
 
lines = ["",
""""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 "]
 
for line = lines
println[collapse[line]]</syntaxhighlight>
{{out}}
<pre>
 
"If I were two-faced, would I be wearing this one?" - Abraham Lincoln
.178
I never give 'em hel, I just tel the truth, and they think it's hel.
- Hary S Truman
</pre>
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
local fn CollapseString( inString as CFStringRef ) as CFStringRef
CFMutableStringRef outString = fn MutableStringWithCapacity(0)
long index
unichar prevChar = 0, currChar
for index = 0 to len(inString) - 1
currChar = fn StringCharacterAtIndex( inString, index )
if ( currChar != prevChar ) then MutableStringAppendFormat( outString, @"%C", currChar )
prevChar = currChar
next
end fn = outString
 
window 1, @"Collapse String", (0,0,600,300)
 
CFStringRef string, collapsedString
 
string = @""
collapsedString = fn CollapseString( string )
printf @"<<<%@>>> %ld\n<<<%@>>> %ld\n",string,len(string),collapsedString,len(collapsedString)
 
string = @"\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln "
collapsedString = fn CollapseString( string )
printf@"<<<%@>>> %ld\n<<<%@>>> %ld\n",string,len(string),collapsedString,len(collapsedString)
 
string = @"..1111111111111111111111111111111111111111111111111111111111111117777888"
collapsedString = fn CollapseString( string )
printf@"<<<%@>>> %ld\n<<<%@>>> %ld\n",string,len(string),collapsedString,len(collapsedString)
 
string = @"I never give 'em hell, I just tell the truth, and they think it's hell. "
collapsedString = fn CollapseString( string )
printf@"<<<%@>>> %ld\n<<<%@>>> %ld\n",string,len(string),collapsedString,len(collapsedString)
 
string = @" --- Harry S Truman "
collapsedString = fn CollapseString( string )
printf@"<<<%@>>> %ld\n<<<%@>>> %ld\n",string,len(string),collapsedString,len(collapsedString)
 
string = @"\"AAAAAll that glitters is not goldDDDD.\" - William Shakespeare"
collapsedString = fn CollapseString( string )
printf@"<<<%@>>> %ld\n<<<%@>>> %ld\n",string,len(string),collapsedString,len(collapsedString)
 
HandleEvents
</syntaxhighlight>
 
{{out}}
<pre>
<<<>>> 0
<<<>>> 0
 
<<<"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln >>> 72
<<<"If I were two-faced, would I be wearing this one?" - Abraham Lincoln >>> 70
 
<<<..1111111111111111111111111111111111111111111111111111111111111117777888>>> 72
<<<.178>>> 4
 
<<<I never give 'em hell, I just tell the truth, and they think it's hell. >>> 72
<<<I never give 'em hel, I just tel the truth, and they think it's hel. >>> 69
 
<<< --- Harry S Truman >>> 72
<<< - Hary S Truman >>> 17
 
<<<"AAAAAll that glitters is not goldDDDD." - William Shakespeare>>> 62
<<<"Al that gliters is not goldD." - Wiliam Shakespeare>>> 52
</pre>
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 1,129 ⟶ 1,643:
fmt.Printf("collapsed: length = %2d, string = «««%s»»»\n\n", clen, cs)
}
}</langsyntaxhighlight>
 
{{out}}
Line 1,160 ⟶ 1,674:
collapsed: length = 6, string = «««😍😀🙌💃😍🙌»»»
</pre>
 
=={{header|Groovy}}==
{{trans|Java}}
<langsyntaxhighlight lang="groovy">class StringCollapsible {
static void main(String[] args) {
for ( String s : [
Line 1,187 ⟶ 1,702:
return sb.toString()
}
}</langsyntaxhighlight>
{{out}}
<pre>old: 0 <<<>>>
Line 1,214 ⟶ 1,729:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import Text.Printf (printf)
import Data.Maybe (catMaybes)
import Control.Monad (guard)
Line 1,235 ⟶ 1,750:
main =
mapM_ (\(a, b) -> printf "old: %3d «««%s»»»\nnew: %3d «««%s»»»\n\n" (length a) a (length b) b)
$ ((,) <*> collapse) <$> input</langsyntaxhighlight>
{{out}}
<pre>
Line 1,265 ⟶ 1,780:
Note that we can also directly define a predicate, and a rewrite, in terms of ''Data.List group'',
 
<langsyntaxhighlight lang="haskell">import Data.List (group)
 
isCollapsible :: String -> Bool
Line 1,271 ⟶ 1,786:
 
collapsed :: String -> String
collapsed = map head . group</langsyntaxhighlight>
 
or, without imports, in terms of pattern matching:
 
<langsyntaxhighlight lang="haskell">isCollapsible :: String -> Bool
isCollapsible [] = False
isCollapsible [_] = False
Line 1,285 ⟶ 1,800:
collapsed (h:t@(x:_))
| h == x = collapsed t
| otherwise = h : collapsed t</langsyntaxhighlight>
 
=={{header|J}}==
Line 1,328 ⟶ 1,843:
 
=={{header|Java}}==
<langsyntaxhighlight lang="java">
// Title: Determine if a string is collapsible
 
Line 1,359 ⟶ 1,874:
 
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,387 ⟶ 1,902:
new: 14 <<<headmistreship>>>
</pre>
 
=={{header|JavaScript}}==
<syntaxhighlight lang="javascript">
String.prototype.collapse = function() {
let str = this;
for (let i = 0; i < str.length; i++) {
while (str[i] == str[i+1]) str = str.substr(0,i) + str.substr(i+1);
}
return str;
}
 
// testing
let strings = [
'',
'"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 '
];
for (let i = 0; i < strings.length; i++) {
let str = strings[i], col = str.collapse();
console.log(`«««${str}»»» (${str.length})`);
console.log(`«««${col}»»» (${col.length})`);
}
</syntaxhighlight>
 
{{out}} <pre>
«««»»» (0)
«««»»» (0)
«««"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln »»» (72)
«««"If I were two-faced, would I be wearing this one?" - Abraham Lincoln »»» (70)
«««..1111111111111111111111111111111111111111111111111111111111111117777888»»» (72)
«««.178»»» (4)
«««I never give 'em hell, I just tell the truth, and they think it's hell. »»» (72)
«««I never give 'em hel, I just tel the truth, and they think it's hel. »»» (69)
««« --- Harry S Truman »»» (72)
««« - Hary S Truman »»» (17)
</pre>
 
=={{header|jq}}==
Here we can use the Unix-like `uniq` function defined on (JSON) arrays to define `collapse` on (JSON) strings:
<syntaxhighlight lang="jq"># Input: an array
# Output: a stream
def uniq: foreach .[] as $x ({x:nan, y:.[0]}; {x:$x, y:.x}; select(.x != .y) | .x);
 
def collapse: explode | [uniq] | implode; </syntaxhighlight>
 
The program for the given task can now be written in three lines:
 
<syntaxhighlight lang="jq">def Guillemets: "«««\(.)»»»";
 
"Original: \(Guillemets) has length \(length)",
(collapse | "Collapsed \(Guillemets) has length \(length)")
</syntaxhighlight>
 
Using the following invocation on the five "raw" (i.e. unquoted) strings yields the results as shown:
 
jq -Rrf program.jq raw.txt
 
<syntaxhighlight lang="sh">Original: «««»»» has length 0
Collapsed «««»»» has length 0
Original: «««"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln »»» has length 72
Collapsed «««"If I were two-faced, would I be wearing this one?" - Abraham Lincoln »»» has length 70
Original: «««..1111111111111111111111111111111111111111111111111111111111111117777888»»» has length 72
Collapsed «««.178»»» has length 4
Original: «««I never give 'em hell, I just tell the truth, and they think it's hell. »»» has length 72
Collapsed «««I never give 'em hel, I just tel the truth, and they think it's hel. »»» has length 69
Original: ««« --- Harry S Truman »»» has length 72
Collapsed ««« - Hary S Truman »»» has length 17</syntaxhighlight>
 
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia">const teststrings = [
"",
""""If I were two-faced, would I be wearing this one?" --- Abraham Lincoln """,
Line 1,419 ⟶ 2,004:
 
testcollapse(teststrings)
</langsyntaxhighlight>{{out}}
<pre>
«««»»» (length 0)
Line 1,442 ⟶ 2,027:
</pre>
==== Condensed version: ====
<langsyntaxhighlight lang="julia">const teststrings = [
"",
""""If I were two-faced, would I be wearing this one?" --- Abraham Lincoln """,
Line 1,455 ⟶ 2,040:
println("«««$s»»» (length $n)\n collapses to:\n«««$t»»» (length $(length(t))).\n")
end
</syntaxhighlight>
</lang>
 
=={{header|Kotlin}}==
{{trans|Go}}
<langsyntaxhighlight lang="scala">fun collapse(s: String): String {
val cs = StringBuilder()
var last: Char = 0.toChar()
Line 1,488 ⟶ 2,073:
println()
}
}</langsyntaxhighlight>
{{out}}
<pre>original : length = 0, string = «««»»»
Line 1,513 ⟶ 2,098:
original : length = 8, string = «««aardvark»»»
collapsed : length = 7, string = «««ardvark»»»</pre>
 
=={{header|Ksh}}==
<syntaxhighlight lang="ksh">
#!/bin/ksh
 
# Determine if a string is collapsible (repeated letters)
 
# # Variables:
#
typeset -a strings
strings[0]=""
strings[1]='"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln'
strings[2]="..1111111111111111111111111111111111111111111111111111111111111117777888"
strings[3]="I never give 'em hell, I just tell the truth, and they think it's hell."
strings[4]=" --- Harry S Truman"
 
typeset -a Guillemet=( "«««" "»»»" )
 
# # Functions:
#
# # Function _collapse(str) - return colapsed version of str
#
function _collapse {
typeset _str ; _str="$1"
typeset _i _buff ; integer _i
 
for ((_i=1; _i<${#_str}; _i++)); do
if [[ "${_str:$((_i-1)):1}" == "${_str:${_i}:1}" ]]; then
continue
else
_buff+=${_str:$((_i-1)):1}
fi
done
[[ "${_str:$((_i-1)):1}" != "${_str:${_i}:1}" ]] && _buff+=${_str:$((_i-1)):1}
echo "${_buff}"
}
 
######
# main #
######
for ((i=0; i<${#strings[*]}; i++)); do
str=$(_collapse "${strings[i]}")
print ${#strings[i]} "${Guillemet[0]}${strings[i]}${Guillemet[1]}"
print ${#str} "${Guillemet[0]}${str}${Guillemet[1]}\n"
done</syntaxhighlight>
{{out}}<pre>0 «««»»»
0 «««»»»
 
71 «««"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln»»»
69 «««"If I were two-faced, would I be wearing this one?" - Abraham Lincoln»»»
 
72 «««..1111111111111111111111111111111111111111111111111111111111111117777888»»»
4 «««.178»»»
 
71 «««I never give 'em hell, I just tell the truth, and they think it's hell.»»»
68 «««I never give 'em hel, I just tel the truth, and they think it's hel.»»»
 
70 ««« --- Harry S Truman»»»
16 ««« - Hary S Truman»»»
</pre>
 
=={{header|Lua}}==
{{trans|C#}}
<langsyntaxhighlight lang="lua">function collapse(s)
local ns = ""
local last = nil
Line 1,549 ⟶ 2,194:
end
 
main()</langsyntaxhighlight>
{{out}}
<pre>old: 0 <<<>>>
Line 1,565 ⟶ 2,210:
old: 72 <<< --- Harry S Truman >>>
new: 17 <<< - Hary S Truman >>></pre>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">ClearAll[StringCollapse]
StringCollapse[s_String] := FixedPoint[StringReplace[y_ ~~ y_ :> y], s]
strings = {"",
"\"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 "};
Do[
Print["«««" <> s <> "»»»"];
Print["Length = ", StringLength[s]];
Print["«««" <> StringCollapse[s] <> "»»»"];
Print["Length = ", StringLength[StringCollapse[s]]]
,
{s, strings}
]</syntaxhighlight>
{{out}}
<pre>«««»»»
Length = 0
«««»»»
Length = 0
«««"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln »»»
Length = 72
«««"If I were two-faced, would I be wearing this one?" - Abraham Lincoln »»»
Length = 70
«««..1111111111111111111111111111111111111111111111111111111111111117777888»»»
Length = 72
«««.178»»»
Length = 4
«««I never give 'em hell, I just tell the truth, and they think it's hell. »»»
Length = 72
«««I never give 'em hel, I just tel the truth, and they think it's hel. »»»
Length = 69
««« --- Harry S Truman »»»
Length = 72
««« - Hary S Truman »»»
Length = 17</pre>
 
=={{header|MATLAB}} / {{header|Octave}}==
<syntaxhighlight lang="matlab">
<lang Matlab>
function r = collapse(s)
ix=find((s(1:end-1)==s(2:end))+1;
Line 1,589 ⟶ 2,272:
collapse('║ --- Harry S Truman ║', 'r')
 
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,618 ⟶ 2,301:
ans = ║ - Hary S Truman ║
PASSES 1 out of 1 test
</pre>
 
=={{header|Miranda}}==
<syntaxhighlight lang="miranda">main :: [sys_message]
main = [Stdout (lay (map test tests))]
 
tests :: [[char]]
tests
= [
"",
"\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ",
"..1111111111111111111111111111111111111111111111111111111111111111111788",
"I never give 'em hell, I just tell the truth, and they think it's hell. ",
" --- Harry S Truman "
]
 
test :: [char]->[char]
test s = lay [before, after]
where before = disp s
after = disp (collapse s)
 
disp :: [char]->[char]
disp s = show (#s) ++ ": <<<" ++ s ++ ">>>"
 
collapse :: [*]->[*]
collapse [] = []
collapse [x] = [x]
collapse (x:y:xs) = collapse (y:xs), if x=y
= x:collapse (y:xs), otherwise</syntaxhighlight>
{{out}}
<pre>0: <<<>>>
0: <<<>>>
 
72: <<<"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln >>>
70: <<<"If I were two-faced, would I be wearing this one?" - Abraham Lincoln >>>
 
72: <<<..1111111111111111111111111111111111111111111111111111111111111111111788>>>
4: <<<.178>>>
 
72: <<<I never give 'em hell, I just tell the truth, and they think it's hell. >>>
69: <<<I never give 'em hel, I just tel the truth, and they think it's hel. >>>
 
72: <<< --- Harry S Truman >>>
17: <<< - Hary S Truman >>>
</pre>
 
=={{header|Modula-2}}==
<syntaxhighlight lang="modula2">MODULE StrCollapse;
FROM InOut IMPORT WriteString, WriteCard, WriteLn;
FROM Strings IMPORT Length;
 
(* Collapse a string *)
PROCEDURE Collapse(in: ARRAY OF CHAR; VAR out: ARRAY OF CHAR);
VAR i, o: CARDINAL;
BEGIN
i := 0;
o := 0;
WHILE (i < HIGH(in)) AND (in[i] # CHR(0)) DO
IF (o = 0) OR (out[o-1] # in[i]) THEN
out[o] := in[i];
INC(o);
END;
INC(i);
END;
out[o] := CHR(0);
END Collapse;
 
(* Display a string and collapse it as stated in the task *)
PROCEDURE Task(s: ARRAY OF CHAR);
VAR buf: ARRAY [0..127] OF CHAR;
PROCEDURE LengthAndBrackets(s: ARRAY OF CHAR);
BEGIN
WriteCard(Length(s), 2);
WriteString(" <<<");
WriteString(s);
WriteString(">>>");
WriteLn();
END LengthAndBrackets;
BEGIN
LengthAndBrackets(s);
Collapse(s, buf);
LengthAndBrackets(buf);
WriteLn();
END Task;
 
BEGIN
Task("");
Task('"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ');
Task("..1111111111111111111111111111111111111111111111111111111111111117777888");
Task("I never give 'em hell, I just tell the truth, and they think it's hell. ");
Task(" --- Harry S Truman ");
END StrCollapse.</syntaxhighlight>
{{out}}
<pre> 0 <<<>>>
0 <<<>>>
 
72 <<<"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln >>>
70 <<<"If I were two-faced, would I be wearing this one?" - Abraham Lincoln >>>
 
72 <<<..1111111111111111111111111111111111111111111111111111111111111117777888>>>
4 <<<.178>>>
 
72 <<<I never give 'em hell, I just tell the truth, and they think it's hell. >>>
69 <<<I never give 'em hel, I just tel the truth, and they think it's hel. >>>
 
72 <<< --- Harry S Truman >>>
17 <<< - Hary S Truman >>></pre>
 
=={{header|NetLogo}}==
 
To run the task:
 
* Enter the code below into the Code Pane of NetLogo
* On the Interface Pane, in the Command Center, type "demo" and hit enter.
 
<syntaxhighlight lang="netlogo">
to-report split [ string ]
;; utility reporter to split a string into a list
report n-values length string [ [ n ] -> item n string ]
end
 
to-report collapse [ string ]
;; reporter that actually does the collapse function
ifelse ( string = "" )
[ report "" ]
[ report reduce [ [ a b ] -> (word a ifelse-value last a != b [ b ] [ "" ] ) ] split string ]
end
 
to-report format [ string ]
;; reporter to format the output as required
report ( word "<<<" string ">>> " length string )
end
 
to demo-collapse [ string ]
;; procedure to display the required output
output-print format string
output-print format collapse string
end
 
to demo
;; procedure to perform the test cases
foreach
[ ""
"\"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 "
]
demo-collapse
end
</syntaxhighlight>
 
{{out}}
 
<pre>
observer> demo
<<<>>> 0
<<<>>> 0
<<<"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln >>> 72
<<<"If I were two-faced, would I be wearing this one?" - Abraham Lincoln >>> 70
<<<..1111111111111111111111111111111111111111111111111111111111111117777888>>> 72
<<<.178>>> 4
<<<I never give 'em hell, I just tell the truth, and they think it's hell. >>> 72
<<<I never give 'em hel, I just tel the truth, and they think it's hel. >>> 69
<<< --- Harry S Truman >>> 72
<<< - Hary S Truman >>> 17
</pre>
 
=={{header|Nim}}==
<langsyntaxhighlight Nimlang="nim">import unicode, strformat
 
proc collapse(s: string) =
Line 1,648 ⟶ 2,497:
 
for s in Strings:
s.collapse()</langsyntaxhighlight>
 
{{out}}
Line 1,679 ⟶ 2,528:
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">use strict;
use warnings;
use utf8;
Line 1,700 ⟶ 2,549:
printf "\nLength: %2d <<<%s>>>\nCollapsible: %s\nLength: %2d <<<%s>>>\n",
length($_), $_, $_ ne $squish ? 'True' : 'False', length($squish), $squish
}</langsyntaxhighlight>
{{out}}
<pre>Length: 0 <<<>>>
Line 1,743 ⟶ 2,592:
If you don't have builtins/punique.e to hand, you may want to take a quick look at squeeze() in
[[https://rosettacode.org/wiki/Determine_if_a_string_is_squeezable#Phix]], but obviously w/o ch.
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>constant tests = {"",
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
`"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln `,
<span style="color: #008080;">constant</span> <span style="color: #000000;">tests</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #008000;">""</span><span style="color: #0000FF;">,</span>
"..1111111111111111111111111111111111111111111111111111111111111117777888",
<span style="Icolor: never#008000;">`"If giveI 'emwere helltwo-faced, would I justbe tellwearing thethis truth,one?" and--- theyAbraham thinkLincoln it's`</span><span hell.style="color: #0000FF;">,</span>
<span style="color: #008000;">"..1111111111111111111111111111111111111111111111111111111111111117777888"</span><span style="color: #0000FF;">,</span>
" --- Harry S Truman "},
<span style="color: #008000;">"I never give 'em hell, I just tell the truth, and they think it's hell. "</span><span style="color: #0000FF;">,</span>
fmt = """
<span style="color: #008000;">" --- Harry S Truman "</span><span style="color: #0000FF;">},</span>
length %2d input: <<<%s>>>
<span style="color: #000000;">fmt</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"""
length %2d output: <<<%s>>>
length %2d input: &lt;&lt;&lt;%s&gt;&gt;&gt;
"""
length %2d output: &lt;&lt;&lt;%s&gt;&gt;&gt;
for i=1 to length(tests) do
"""</span>
string ti = tests[i], ci = unique(ti, "PRESORTED")
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">tests</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
printf(1,fmt,{length(ti),ti,length(ci),ci})
<span style="color: #004080;">string</span> <span style="color: #000000;">ti</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">tests</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">],</span> <span style="color: #000000;">ci</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">unique</span><span style="color: #0000FF;">(</span><span style="color: #000000;">ti</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"PRESORTED"</span><span style="color: #0000FF;">)</span>
end for
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">fmt</span><span style="color: #0000FF;">,{</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">ti</span><span style="color: #0000FF;">),</span><span style="color: #000000;">ti</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">ci</span><span style="color: #0000FF;">),</span><span style="color: #000000;">ci</span><span style="color: #0000FF;">})</span>
 
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
function collapsible(string t)
-- sequence utf32 = utf8_to_utf32(t) -- maybe
<span style="color: #008080;">function</span> <span style="color: #000000;">collapsible</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">t</span><span style="color: #0000FF;">)</span>
-- for i=2 to length(utf32) do -- """
<span style="color: #000080;font-style:italic;">-- sequence utf32 = utf8_to_utf32(t) -- maybe
-- if utf32[i]=utf32[i-1] then -- """
-- for i=2 to length(tutf32) do -- """
-- if tutf32[i]=tutf32[i-1] then -- """</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">2</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">t</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
return true
<span style="color: #008080;">if</span> <span style="color: #000000;">t</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]=</span><span style="color: #000000;">t</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span> <span style="color: #008080;">then</span>
end if
<span style="color: #008080;">return</span> <span style="color: #004600;">true</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
return false
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
end function
<span style="color: #008080;">return</span> <span style="color: #004600;">false</span>
 
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
puts(1,"\nAs predicate: ")
for i=1 to length(tests) do
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"\nAs predicate: "</span><span style="color: #0000FF;">)</span>
printf(1,"%t ",collapsible(tests[i]))
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">tests</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
end for
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%t "</span><span style="color: #0000FF;">,</span><span style="color: #000000;">collapsible</span><span style="color: #0000FF;">(</span><span style="color: #000000;">tests</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]))</span>
puts(1,"\n")</lang>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"\n"</span><span style="color: #0000FF;">)</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 1,796 ⟶ 2,648:
=={{header|PHP}}==
 
<langsyntaxhighlight PHPlang="php"><?php
 
function collapseString($string) {
Line 1,837 ⟶ 2,689:
echo 'Collapse : string is not collapsing...', PHP_EOL, PHP_EOL;
}
}</langsyntaxhighlight>
 
{{out}}
Line 1,869 ⟶ 2,721:
Original : <<<😍😀🙌💃😍😍😍🙌>>> (len=8)
Collapse : <<<😍😀🙌💃😍🙌>>> (len=6)</pre>
=={{header|PL/M}}==
 
Because of the limited character set supported by the PL/M-80 compiler,
uppercase letters have been substituted for lowercase letters,
the question mark for the period,
and the single quotation mark for the double quotation mark.
This has no other effect on the output.
While it would be possible to write the ASCII values as numbers, this would make the code less clear.
The <code>COLLAPSE</code> procedure compares bytes and would be fine with any 8-bit input.
 
<syntaxhighlight lang="plm">100H:
BDOS: PROCEDURE (FN, ARG); DECLARE FN BYTE, ARG ADDRESS; GO TO 5; END BDOS;
EXIT: PROCEDURE; CALL BDOS(0,0); END EXIT;
PRINT: PROCEDURE (S); DECLARE S ADDRESS; CALL BDOS(9, S); END PRINT;
 
/* PRINT NUMBER */
PRINT$NUMBER: PROCEDURE (N);
DECLARE S (6) BYTE INITIAL ('.....$');
DECLARE (N, P) ADDRESS, C BASED P BYTE;
P = .S(5);
DIGIT:
P = P - 1;
C = N MOD 10 + '0';
N = N / 10;
IF N > 0 THEN GO TO DIGIT;
CALL PRINT(P);
END PRINT$NUMBER;
 
/* STRING LENGTH */
STR$LEN: PROCEDURE (STR) ADDRESS;
DECLARE (STR, I) ADDRESS, S BASED STR BYTE;
I = 0;
DO WHILE S(I) <> '$';
I = I + 1;
END;
RETURN I;
END STR$LEN;
 
/* COLLAPSE */
COLLAPSE: PROCEDURE (IN, OUT);
DECLARE (IN, OUT) ADDRESS, (I BASED IN, O BASED OUT, C) BYTE;
C = I;
DO WHILE C <> '$';
IN = IN + 1;
IF I <> C THEN DO;
O = C;
OUT = OUT + 1;
C = I;
END;
END;
O = '$';
END COLLAPSE;
 
/* PRINT STRING AND LENGTH WITH BRACKETS */
PRINT$BRACKETS: PROCEDURE (S);
DECLARE S ADDRESS;
CALL PRINT$NUMBER(STR$LEN(S));
CALL PRINT(.' <<<$');
CALL PRINT(S);
CALL PRINT(.('>>>',13,10,'$'));
END PRINT$BRACKETS;
 
/* GIVEN A STRING, PRINT IT AND ITS COLLAPSED FORM */
SHOW: PROCEDURE (S);
DECLARE S ADDRESS, BUFFER (256) BYTE;
CALL COLLAPSE(S, .BUFFER);
CALL PRINT$BRACKETS(S);
CALL PRINT$BRACKETS(.BUFFER);
CALL PRINT(.(13,10,'$'));
END SHOW;
 
/* STRINGS FROM THE TASK */
DECLARE X (5) ADDRESS;
X(0)=.'$';
X(1)=.('''IF I WERE TWO-FACED, WOULD I BE WEARING ',
'THIS ONE.'' --- ABRAHAM LINCOLN $');
X(2)=.('..111111111111111111111111111111111111111',
'1111111111111111111111117777888$');
X(3)=.('I NEVER GIVE ''EM HELL, I JUST TELL THE TR',
'UTH, AND THEY THINK IT''S HELL. $');
X(4)=.(' ',
' --- HARRY S TRUMAN $');
DECLARE I BYTE;
DO I=0 TO LAST(X);
CALL SHOW(X(I));
END;
CALL EXIT;
EOF
</syntaxhighlight>
{{out}}
<pre>0 <<<>>>
0 <<<>>>
 
72 <<<'IF I WERE TWO-FACED, WOULD I BE WEARING THIS ONE.' --- ABRAHAM LINCOLN >>>
70 <<<'IF I WERE TWO-FACED, WOULD I BE WEARING THIS ONE.' - ABRAHAM LINCOLN >>>
 
72 <<<..1111111111111111111111111111111111111111111111111111111111111117777888>>>
4 <<<.178>>>
 
72 <<<I NEVER GIVE 'EM HELL, I JUST TELL THE TRUTH, AND THEY THINK IT'S HELL. >>>
69 <<<I NEVER GIVE 'EM HEL, I JUST TEL THE TRUTH, AND THEY THINK IT'S HEL. >>>
 
72 <<< --- HARRY S TRUMAN >>>
17 <<< - HARY S TRUMAN >>></pre>
 
=={{header|Prolog}}==
<langsyntaxhighlight lang="prolog">collapse_( [], [] ).
collapse_( [A], [A] ).
collapse_( [A,A|T], R ) :- collapse_( [A|T], R ).
Line 1,879 ⟶ 2,836:
string_chars( Str, Chars ),
collapse_( Chars, Result ),
string_chars( Collapsed, Result ).</langsyntaxhighlight>
{{out}}
<pre>
Line 1,917 ⟶ 2,874:
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">EnableExplicit
DataSection
STR1:
Line 1,952 ⟶ 2,909:
*p_data+StringByteLength(PeekS(*p_data))+2
Wend
Input()</langsyntaxhighlight>
{{out}}
<pre>Before collapse: «««»»» (length: 0)
Line 1,971 ⟶ 2,928:
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">from itertools import groupby
 
def collapser(txt):
Line 1,993 ⟶ 2,950:
this = "Collapsed"
sqz = collapser(txt)
print(f"{this:>14} Size: {len(sqz)} «««{sqz}»»»" )</langsyntaxhighlight>
 
{{out}}
Line 2,026 ⟶ 2,983:
and for the missing predicate, foregrounded in the task title, and already forgotten in the listing of tests:
 
<langsyntaxhighlight lang="python">'''Determining if a string is collapsible'''
 
from operator import eq
Line 2,064 ⟶ 3,021:
# MAIN ---
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>[False, True, True, True, True, True, True, True, True, False]</pre>
Line 2,070 ⟶ 3,027:
=={{header|Quackery}}==
 
<langsyntaxhighlight Quackerylang="quackery"> [ false -1 rot
witheach
[ 2dup = iff
Line 2,104 ⟶ 3,061:
$ "..1111111111111111111111111111111111111111111111111111111111111117777888" task
$ "I never give 'em hell, I just tell the truth, and they think it's hell. " task
$ " --- Harry S Truman " task</langsyntaxhighlight>
 
{{out}}
Line 2,141 ⟶ 3,098:
 
 
</pre>
 
=={{header|R}}==
<syntaxhighlight lang="r">collapse_string <- function(string){
str_iterable <- strsplit(string, "")[[1]]
message(paste0("Original String: ", "<<<", string, ">>>\n",
"Length: ", length(str_iterable)))
detect <- rep(TRUE, length(str_iterable))
for(i in 2:length(str_iterable)){
if(length(str_iterable)==0) break
if(str_iterable[i] == str_iterable[i-1])
detect[i] <- FALSE
}
collapsed_string <- paste(str_iterable[detect],collapse = "")
message(paste0("Collapsed string: ", "<<<",collapsed_string, ">>>\n",
"Length: ", length(str_iterable[detect])), "\n")
}
 
test_strings <- c(
"",
"'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",
"Ciao Mamma, guarda come mi diverto!!"
)
 
for(test in test_strings){
collapse_string(test)
}
 
</syntaxhighlight>
 
{{out}}
<pre>
Original String: <<<>>>
Length: 0
Collapsed string: <<<>>>
Length: 0
 
Original String: <<<'If I were two-faced, would I be wearing this one?' --- Abraham Lincoln >>>
Length: 72
Collapsed string: <<<'If I were two-faced, would I be wearing this one?' - Abraham Lincoln >>>
Length: 70
 
Original String: <<<..1111111111111111111111111111111111111111111111111111111111111117777888>>>
Length: 72
Collapsed string: <<<.178>>>
Length: 4
 
Original String: <<<I never give 'em hell, I just tell the truth, and they think it's hell. >>>
Length: 72
Collapsed string: <<<I never give 'em hel, I just tel the truth, and they think it's hel. >>>
Length: 69
 
Original String: <<< --- Harry S Truman >>>
Length: 72
Collapsed string: <<< - Hary S Truman >>>
Length: 17
 
Original String: <<<The better the 4-wheel drive, the further you'll be from help when ya get stuck!>>>
Length: 80
Collapsed string: <<<The beter the 4-whel drive, the further you'l be from help when ya get stuck!>>>
Length: 77
 
Original String: <<<headmistressship>>>
Length: 16
Collapsed string: <<<headmistreship>>>
Length: 14
 
Original String: <<<aardvark>>>
Length: 8
Collapsed string: <<<ardvark>>>
Length: 7
 
Original String: <<<Ciao Mamma, guarda come mi diverto!!>>>
Length: 36
Collapsed string: <<<Ciao Mama, guarda come mi diverto!>>>
Length: 34
</pre>
 
=={{header|Racket}}==
 
<syntaxhighlight lang="racket">#lang racket
 
(define (collapse text)
(if (< (string-length text) 2)
text
(string-append
(if (equal? (substring text 0 1) (substring text 1 2))
"" (substring text 0 1))
(collapse (substring text 1)))))
 
; Test cases
(define tcs
'(""
"\"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 ([text tcs])
(let ([collapsed (collapse text)])
(display (format "Original (size ~a): «««~a»»»\nCollapsed (size ~a): «««~a»»»\n\n"
(string-length text) text
(string-length collapsed) collapsed))))
</syntaxhighlight>
{{out}}
<pre>Original (size 0): «««»»»
Collapsed (size 0): «««»»»
 
Original (size 72): «««"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln »»»
Collapsed (size 70): «««"If I were two-faced, would I be wearing this one?" - Abraham Lincoln »»»
 
Original (size 72): «««..1111111111111111111111111111111111111111111111111111111111111117777888»»»
Collapsed (size 4): «««.178»»»
 
Original (size 72): «««I never give 'em hell, I just tell the truth, and they think it's hell. »»»
Collapsed (size 69): «««I never give 'em hel, I just tel the truth, and they think it's hel. »»»
 
Original (size 72): ««« --- Harry S Truman »»»
Collapsed (size 17): ««« - Hary S Truman »»»
 
Original (size 80): «««The better the 4-wheel drive, the further you'll be from help when ya get stuck!»»»
Collapsed (size 77): «««The beter the 4-whel drive, the further you'l be from help when ya get stuck!»»»
 
Original (size 16): «««headmistressship»»»
Collapsed (size 14): «««headmistreship»»»
 
Original (size 8): «««aardvark»»»
Collapsed (size 7): «««ardvark»»»
 
Original (size 8): «««😍😀🙌💃😍😍😍🙌»»»
Collapsed (size 6): «««😍😀🙌💃😍🙌»»»
</pre>
 
Line 2,148 ⟶ 3,257:
Technically, the task is asking for a boolean. "Determine if a string is collapsible" is answerable with True/False, so return a boolean as well.
 
<syntaxhighlight lang="raku" perl6line>map {
my $squish = .comb.squish.join;
printf "\nLength: %2d <<<%s>>>\nCollapsible: %s\nLength: %2d <<<%s>>>\n",
Line 2,165 ⟶ 3,274:
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
STRINGS
</syntaxhighlight>
</lang>
{{out}}
<pre>Length: 0 <<<>>>
Line 2,203 ⟶ 3,312:
Length: 1 <<<A>>>
</pre>
 
=={{header|Refal}}==
<syntaxhighlight lang="refal">$ENTRY Go {
, ('')
('"If I were two-faced, would I be wearing this '
'one?" --- Abraham Lincoln ')
('..11111111111111111111111111111111111111111111'
'11111111111111111117777888')
('I never give \'em hell, I just tell the truth, '
'and they think it\'s hell. ')
(' '
' --- Harry S Truman '): e.Strings
= <Each Show e.Strings>;
};
 
Each {
s.F = ;
s.F t.I e.X = <Mu s.F t.I> <Each s.F e.X>;
};
 
Brackets {
e.X, <Lenw e.X>: s.L e.X =
<Prout <Symb s.L> ': <<<' e.X '>>>'>;
};
 
Show {
(e.X) = <Brackets e.X>
<Brackets <Collapse e.X>>
<Prout>;
};
 
Collapse {
= ;
s.C s.C e.S = <Collapse s.C e.S>;
s.C e.S = s.C <Collapse e.S>;
};</syntaxhighlight>
{{out}}
<pre>0: <<<>>>
0: <<<>>>
 
72: <<<"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln >>>
70: <<<"If I were two-faced, would I be wearing this one?" - Abraham Lincoln >>>
 
72: <<<..1111111111111111111111111111111111111111111111111111111111111117777888>>>
4: <<<.178>>>
 
72: <<<I never give 'em hell, I just tell the truth, and they think it's hell. >>>
69: <<<I never give 'em hel, I just tel the truth, and they think it's hel. >>>
 
72: <<< --- Harry S Truman >>>
17: <<< - Hary S Truman >>></pre>
 
=={{header|REXX}}==
<langsyntaxhighlight lang="rexx">/*REXX program "collapses" all immediately repeated characters in a string (or strings).*/
@.= /*define a default for the @. array. */
parse arg x /*obtain optional argument from the CL.*/
Line 2,233 ⟶ 3,393:
$= $ || _ /*append the character, it's different.*/
end /*j*/
collapsible= y\==$; return $ /*set boolean to true if collapsible.*/</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the internal default inputs:}}
<pre>
Line 2,260 ⟶ 3,420:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
load "stdlib.ring"
 
Line 2,287 ⟶ 3,447:
 
see "done..." + nl
</syntaxhighlight>
</lang>
Output:
<pre>
Line 2,302 ⟶ 3,462:
 
done...
</pre>
 
=={{header|RPL}}==
{{works with|Halcyon Calc|4.2.7}}
{{trans|Kotlin}}
{| class="wikitable"
! RPL code
! Comment
|-
|
≪ → string
≪ "" DUP
1 string SIZE '''FOR''' j
string j DUP SUB
'''IF''' DUP2 ≠ '''THEN'''
ROT OVER +
SWAP ROT
'''END''' DROP
'''NEXT''' DROP
≫ ≫ ‘'''<span style="color:blue">CLAPS</span>'''’ STO
|
'''<span style="color:blue">CLAPS</span>''' ''( "strrinng" → "string" )''
output string = last = ""
scan the input string
c = jth character
if c ≠ last
output string += c
last = c
forget c or previous last
clean stack
|}
{{works with|HP|49}}
« → string
« { "" }
string SIZE 1 '''FOR''' j
string j DUP SUB SWAP
'''IF''' DUP2 HEAD == '''THEN''' NIP '''ELSE''' + '''END'''
-1 '''STEP'''
∑LIST
» » ‘'''<span style="color:blue">CLAPS</span>'''’ STO
When displaying strings, RPL always adds double quotes. To fulfill the artistic touch requirement, we have used guillemets to bracket Lincoln's statement.
≪ { ""
"≪ 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 " }
1 5 '''FOR''' j DUP j GET <span style="color:blue">CLAPS</span> SWAP '''NEXT''' DROP
≫ EVAL
{{out}}
<pre>
5: ""
4: "≪ If I were two-faced, would I be wearing this one? ≫ - Abraham Lincoln "
3: ".178"
2: "I never give 'em hel, I just tel the truth, and they think it's hel. "
1: " - Hary S Truman "
</pre>
 
=={{header|Ruby}}==
This is built in since at least a decade under the method name 'squeeze'. squeeze(" ") would only squeeze spaces.
<langsyntaxhighlight lang="ruby">strings = ["",
'"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ',
"..1111111111111111111111111111111111111111111111111111111111111117777888",
Line 2,322 ⟶ 3,538:
puts
end
</syntaxhighlight>
</lang>
{{out}}
<pre>«««»»» (size 0)
Line 2,353 ⟶ 3,569:
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">fn collapse_string(val: &str) -> String {
let mut output = String::new();
let mut chars = val.chars().peekable();
Line 2,391 ⟶ 3,607:
println!();
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,422 ⟶ 3,638:
===Pure imperative programming 😃===
 
<langsyntaxhighlight Scalalang="scala">object CollapsibleString {
 
/**Collapse a string (if possible)*/
Line 2,475 ⟶ 3,691:
 
 
}</langsyntaxhighlight>
{{out}}
<pre>ORIGINAL : length = 0, string = «««»»»
Line 2,508 ⟶ 3,724:
COLLAPSED : length = 7, string = «««ardvark»»»
This string IS collapsible !</pre>
 
=={{header|sed}}==
Since sed has no native support for arithmetic, line length counting is omitted in this solution for simplicity:
<syntaxhighlight lang="sed">h
s/.*/<<<&>>>/
x
s/\(.\)\1*/\1/g
s/.*/<<<&>>>/
H
s/.*//
G</syntaxhighlight>
Test:
<pre>
printf '%s\n' \
'' \
'"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 ' \
| sed -f collapse.sed
</pre>
{{out}}
<pre>
 
<<<>>>
<<<>>>
 
<<<"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln >>>
<<<"If I were two-faced, would I be wearing this one?" - Abraham Lincoln >>>
 
<<<..1111111111111111111111111111111111111111111111111111111111111117777888>>>
<<<.178>>>
 
<<<I never give 'em hell, I just tell the truth, and they think it's hell. >>>
<<<I never give 'em hel, I just tel the truth, and they think it's hel. >>>
 
<<< --- Harry S Truman >>>
<<< - Hary S Truman >>>
</pre>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">func squeeze(str) {
str.gsub(/(.)\1+/, {|s1| s1 })
}
Line 2,528 ⟶ 3,783:
say "«««#{str}»»» (length: #{str.len})"
say "«««#{ssq}»»» (length: #{ssq.len})\n"
}</langsyntaxhighlight>
{{out}}
<pre style="font-size: 80%">
Line 2,561 ⟶ 3,816:
=={{header|Smalltalk}}==
{{works with|Smalltalk/X}}
<langsyntaxhighlight lang="smalltalk">#(
'The better the 4-wheel drive, the further you''ll be from help when ya get stuck!'
'headmistressship'
Line 2,579 ⟶ 3,834:
showCR:( eachWord,'(length:',eachWord size,')' );
showCR:( shortened,'(length:',shortened size,')' ).
]</langsyntaxhighlight>
{{out}}
<pre>The better the 4-wheel drive, the further you'll be from help when ya get stuck!(length:80)
Line 2,591 ⟶ 3,846:
 
=={{header|Swift}}==
<langsyntaxhighlight Swiftlang="swift">let strings = [
"",
#""If I were two-faced, would I be wearing this one?" --- Abraham Lincoln "#,
Line 2,607 ⟶ 3,862:
for (original, collapsed) in zip(strings, collapsedStrings) {
print (String(format: "%03d «%@»\n%03d «%@»\n", original.count, original, collapsed.count, collapsed))
}</langsyntaxhighlight>
 
{{out}}
Line 2,641 ⟶ 3,896:
=={{header|Tcl}}==
Please note the ;# ' comments, there appears to be a syntax hightlighting bug with RC
<langsyntaxhighlight lang="tcl">set test {
{}
{"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln }
Line 2,660 ⟶ 3,915:
puts ----------------------
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,688 ⟶ 3,943:
=={{header|Visual Basic .NET}}==
{{trans|C#}}
<langsyntaxhighlight lang="vbnet">Module Module1
 
Function Collapse(s As String) As String
Line 2,714 ⟶ 3,969:
End Sub
 
End Module</langsyntaxhighlight>
{{out}}
<pre>old: 0 «««»»»
Line 2,730 ⟶ 3,985:
old: 72 ««« --- Harry S Truman »»»
new: 17 ««« - Hary S Truman »»»</pre>
 
=={{header|VBA}}==
Function :
<syntaxhighlight lang="vb">Function Collapse(strIn As String) As String
Dim i As Long, strOut As String
If Len(strIn) > 0 Then
strOut = Mid$(strIn, 1, 1)
For i = 2 To Len(strIn)
If Mid$(strIn, i, 1) <> Mid$(strIn, i - 1, 1) Then
strOut = strOut & Mid$(strIn, i, 1)
End If
Next i
End If
Collapse = strOut
End Function</syntaxhighlight>
To Call :
<syntaxhighlight lang="vb">Sub CallCollapse()
Dim S As String
S = vbNullString
Debug.Print "String : <<<" & S & ">>>", "Lenght : " & Len(S)
Debug.Print "Collapsed : <<<" & Collapse(S) & ">>>", "Lenght : " & Len(Collapse(S))
S = """If I were two-faced, would I be wearing this one?"" --- Abraham Lincoln "
Debug.Print "String : <<<" & S & ">>>", "Lenght : " & Len(S)
Debug.Print "Collapsed : <<<" & Collapse(S) & ">>>", "Lenght : " & Len(Collapse(S))
S = "..1111111111111111111111111111111111111111111111111111111111111117777888"
Debug.Print "String : <<<" & S & ">>>", "Lenght : " & Len(S)
Debug.Print "Collapsed : <<<" & Collapse(S) & ">>>", "Lenght : " & Len(Collapse(S))
S = "I never give 'em hell, I just tell the truth, and they think it's hell. "
Debug.Print "String : <<<" & S & ">>>", "Lenght : " & Len(S)
Debug.Print "Collapsed : <<<" & Collapse(S) & ">>>", "Lenght : " & Len(Collapse(S))
S = " --- Harry S Truman "
Debug.Print "String : <<<" & S & ">>>", "Lenght : " & Len(S)
Debug.Print "Collapsed : <<<" & Collapse(S) & ">>>", "Lenght : " & Len(Collapse(S))
End Sub</syntaxhighlight>
{{out}}
<pre>String : <<<>>> Lenght : 0
Collapsed : <<<>>> Lenght : 0
String : <<<"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln >>> Lenght : 72
Collapsed : <<<"If I were two-faced, would I be wearing this one?" - Abraham Lincoln >>> Lenght : 70
String : <<<..1111111111111111111111111111111111111111111111111111111111111117777888>>> Lenght : 72
Collapsed : <<<.178>>> Lenght : 4
String : <<<I never give 'em hell, I just tell the truth, and they think it's hell. >>> Lenght : 72
Collapsed : <<<I never give 'em hel, I just tel the truth, and they think it's hel. >>> Lenght : 69
String : <<< --- Harry S Truman >>> Lenght : 72
Collapsed : <<< - Hary S Truman >>> Lenght : 17</pre>
 
=={{header|V (Vlang)}}==
{{trans|Go}}
<syntaxhighlight lang="v (vlang)">// Returns collapsed string, original and new lengths in
// unicode code points (not normalized).
fn collapse(s string) (string, int, int) {
mut r := s.runes()
le, mut del := r.len, 0
for i := le - 2; i >= 0; i-- {
if r[i] == r[i+1] {
r.delete(i)
del++
}
}
if del == 0 {
return s, le, le
}
r = r[..le-del]
return r.string(), le, r.len
}
fn main() {
strings:= [
"",
'"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 in strings {
cs, olen, clen := collapse(s)
println("original : length = ${olen:2}, string = «««$s»»»")
println("collapsed: length = ${clen:2}, string = «««$cs»»»\n")
}
}</syntaxhighlight>
 
{{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|Wren}}==
{{trans|Go}}
{{libheader|Wren-fmt}}
<langsyntaxhighlight ecmascriptlang="wren">import "./fmt" for Fmt
 
// Returns collapsed string, original and new lengths in
Line 2,765 ⟶ 4,134:
System.print("original : length = %(Fmt.d(2, r[1])), string = «««%(s)»»»")
System.print("collapsed: length = %(Fmt.d(2, r[2])), string = «««%(r[0])»»»\n")
}</langsyntaxhighlight>
 
{{out}}
Line 2,795 ⟶ 4,164:
original : length = 8, string = «««😍😀🙌💃😍😍😍🙌»»»
collapsed: length = 6, string = «««😍😀🙌💃😍🙌»»»
</pre>
 
=={{header|XPL0}}==
<syntaxhighlight lang="xpl0">string 0;
char C, I, J, Last;
 
proc Collapse(S); \Eliminate immediately repeated characters from string
char S;
[I:= 0; J:= 0; Last:= -1;
loop [if S(I) # Last then
[C(J):= S(I);
if S(I) = 0 then quit;
J:= J+1;
];
Last:= S(I);
I:= I+1;
];
];
 
int String, K;
[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 "];
C:= Reserve(79+1); \space for collapsed string
for K:= 0 to 4 do
[Collapse(String(K));
Text(0, "<<<"); Text(0, String(K)); Text(0, ">>> "); IntOut(0, I); CrLf(0);
Text(0, "<<<"); Text(0, C); Text(0, ">>> "); IntOut(0, J); CrLf(0);
];
]</syntaxhighlight>
 
{{out}}
<pre>
<<<>>> 0
<<<>>> 0
<<<"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln >>> 72
<<<"If I were two-faced, would I be wearing this one?" - Abraham Lincoln >>> 70
<<<..1111111111111111111111111111111111111111111111111111111111111117777888>>> 72
<<<.178>>> 4
<<<I never give 'em hell, I just tell the truth, and they think it's hell. >>> 72
<<<I never give 'em hel, I just tel the truth, and they think it's hel. >>> 69
<<< --- Harry S Truman >>> 72
<<< - Hary S Truman >>> 17
</pre>
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">fcn collapsible(str){ // no Unicode
sink:=Sink(String);
str.reduce('wrap(c1,c2){ if(c1!=c2) sink.write(c2); c2 },""); // prime with \0
cstr:=sink.close();
return(str.len()!=cstr.len(), cstr);
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">strings:=
0'^
"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln
Line 2,822 ⟶ 4,237:
_,cstr:=collapsible(s);
println("After: %3d >>>%s<<<\n".fmt(cstr.len(),cstr));
}</langsyntaxhighlight>
{{out}}
<pre>
2,094

edits