
Determine if a character string is collapsible.
And if so, collapse the string (by removing immediately repeated characters).
If a character string has immediately repeated character(s), the repeated characters are to bedeleted (removed), but not the primary (1st) character(s).
An immediately repeated character is any character that is immediately followed by anidentical character (or characters). Another word choice could've been duplicated character, but thatmight have ruled out (to some readers) triplicated characters ··· or more.
{This Rosetta Code task was inspired by a newly introduced (as of around November 2019) PL/I BIF: collapse.}
In the following character string:
The better the 4-wheel drive, the further you'll be from help when ya get stuck!
Only the 2nd t, e, and l are repeated characters, indicatedby underscores (above), even though they (those characters) appear elsewhere in the character string.
So, aftercollapsing the string, the result would be:
The beter the 4-whel drive, the further you'l be from help when ya get stuck!
Another example:In the following character string:
headmistressship
The "collapsed" string would be:
headmistreship
Write a subroutine/function/procedure/routine··· tolocate repeated characters and collapse (delete) them from the characterstring. The character string can be processed from either direction.
Show all output here, on this page:
Use (at least) the following five strings, all strings are length seventy-two (characters, including blanks), exceptthe 1st string:
string number ╔╗ 1 ║╚═══════════════════════════════════════════════════════════════════════╗ ◄■■■■■■ a null string (length zero) 2 ║"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ║ 3 ║..1111111111111111111111111111111111111111111111111111111111111117777888║ 4 ║I never give 'em hell, I just tell the truth, and they think it's hell. ║ 5 ║ --- Harry S Truman ║ ◄■■■■■■ has many repeated blanks ╚════════════════════════════════════════════════════════════════════════╝
F collapse(s) V cs = ‘’ V last = Char("\0") L(c) s I c != last cs ‘’= c last = c R csV 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()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>>>
bdos:equ5puts:equ9org100hjmpmain;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;Collapse the $-terminated string at [HL]colaps:movb,m; B = last character seeninxh; First character never collapsesmovd,h; DE = output pointermove,lmova,b; Empty string?cpi'$'rz; Then do nothingcloop:mova,m; Get characterinxh; Advance pointercmpb; Same as last one?jzcloop; Then keep scanningmovb,a; Otherwise, it is a new onestaxd; Store it,inxd; and increment output pointer.cpi'$'; Reached the end?jnzcloop; If not, next characterret ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;Code to print the output in the required formatmain:lxih,strs; List of string pointersloop:move,m; DE = string pointerinxhmovd,minxhmova,e; If zero, endoradrzpushh; Keep the list pointerpushd; Keep the string pointercallbrstr; Print original string in bracketspoph; Retrieve string pointerpushhcallcolaps; Collapse the stringpopd; Retrieve string pointercallbrstr; Print the collapsed string in bracketspoph; Retrieve the list pointerjmploop; Next string;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;Print string at DE in brackets with lengthbrstr:pushd; Store string pointermvic,puts; Print opening bracketslxid,opencallbdospopd; Print original stringpushdmvic,putscallbdosmvic,puts; Print closing bracketslxid,close callbdospophcallstrlen; Find string lengthmova,bjmpprnum; Print string length;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;Figure out the length of a string (max 255)strlen:mvib,0; Countermvia,'$'; Terminatorsloop:cmpm; Reached the end yet?rz; If so, stopinrb; If not, increment counter,inxh; and pointer,jmpsloop; and check next byte.;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;Print number in A as decimalprnum:lxid,num; End of number stringprdgt:mvib,-1; Quotientploop:inrb; Increment quotientsui10; Subtract 10jncploop; Subtract until negativeadi'0'+10; Make ASCII digitdcxd; Store in number stringstaxdmova,b; If more digits,anaajnzprdgt; find next digitmvic,puts; When done, print stringjmpbdos;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;Formatting stringsopen:db'<<<$'close:db'>>> $'db'***'num:db13,10,'$';;;Input stringsstrs:dwstr1,str2,str3,str4,str5,0str1:db'$'; Empty stringstr2:db'"If I were two-faced, would I be wearing 'db'this one?" --- Abraham Lincoln $'str3:db'..111111111111111111111111111111111111111'db'1111111111111111111111117777888$'str4:db'I never give ',39,'em hell, I just tell the truth, 'db'and they think it',39,'s hell. $'str5:db' 'db' --- Harry S Truman $'
<<<>>> 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
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-1RETURNPROC 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=$FFRETURNPROC 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 ")RETURNScreenshot from Atari 8-bit computer
<<<>>> (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)
withAda.Text_IO;useAda.Text_IO;procedureTest_CollapsibleisprocedureCollapse(S:inString)isRes:String(1..S'Length);Len:Natural:=0;beginPut_Line("Input = <<<"&S&">>>, length ="&S'Length'Image);forIinS'RangeloopifLen=0or elseS(I)/=Res(Len)thenLen:=Len+1;Res(Len):=S(I);endif;endloop;Put_Line("Output = <<<"&Res(1..Len)&">>>, length ="&Len'Image);endCollapse;beginCollapse("");Collapse("""If I were two-faced, would I be wearing this one?"" --- Abraham Lincoln ");Collapse("..1111111111111111111111111111111111111111111111111111111111111117777888");Collapse("I never give 'em hell, I just tell the truth, and they think it's hell. ");Collapse(" --- Harry S Truman ");endTest_Collapsible;
Input = <<<>>>, length = 0Output = <<<>>>, length = 0Input = <<<"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln >>>, length = 72Output = <<<"If I were two-faced, would I be wearing this one?" - Abraham Lincoln >>>, length = 70Input = <<<..1111111111111111111111111111111111111111111111111111111111111117777888>>>, length = 72Output = <<<.178>>>, length = 4Input = <<<I never give 'em hell, I just tell the truth, and they think it's hell. >>>, length = 72Output = <<<I never give 'em hel, I just tel the truth, and they think it's hel. >>>, length = 69Input = <<< --- Harry S Truman >>>, length = 72Output = <<< - Hary S Truman >>>, length = 17
BEGIN # returns a collapsed version of s # # i.e. s with adjacent duplicate characters removed # PROC collapse = ( STRING s )STRING: IF s = "" THEN "" # empty string # ELSE # non-empty string # [ LWB s : UPB s ]CHAR result; INT r pos := LWB result; result[ r pos ] := s[ LWB s ]; FOR s pos FROM LWB s + 1 TO UPB s DO IF result[ r pos ] /= s[ s pos ] THEN r pos +:= 1; result[ r pos ] := s[ s pos ] FI OD; result[ LWB result : r pos ] FI # callapse # ; # task test cases # []STRING tests = ( "" , """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 t pos FROM LWB tests TO UPB tests DO STRING s = tests[ t pos ]; STRING c = collapse( s ); print( ( " <<<", s, ">>> (length ", whole( ( UPB s + 1 ) - LWB s, 0 ), ")", newline ) ); print( ( "result <<<", c, ">>> (length ", whole( ( UPB c + 1 ) - LWB c, 0 ), ")", newline ) ) ODEND
<<<>>> (length 0)result <<<>>> (length 0) <<<"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln >>> (length 72)result <<<"If I were two-faced, would I be wearing this one?" - Abraham Lincoln >>> (length 70) <<<..1111111111111111111111111111111111111111111111111111111111111117777888>>> (length 72)result <<<.178>>> (length 4) <<<I never give 'em hell, I just tell the truth, and they think it's hell. >>> (length 72)result <<<I never give 'em hel, I just tel the truth, and they think it's hel. >>> (length 69) <<< --- Harry S Truman >>> (length 72)result <<< - Hary S Truman >>> (length 17)
task←{⍝ Collapse a stringcollapse←{(1,¯1↓⍵≠1⌽⍵)/⍵}⍝ Given a function ⍺⍺, display a string in brackets,⍝ along with its length, and do the same for the result⍝ of applying ⍺⍺ to the string.display←{bracket←{(⍕⍴⍵),' «««',⍵,'»»»'}↑(⊂bracket⍵),(⊂bracket⍺⍺⍵)}⍝ Strings from the tasks1←''s2←'"If I were two-faced, would I be wearing this one?"'s2,←' --- Abraham Lincoln 's3←'..1111111111111111111111111111111111111111111111111's3,←'111111111111117777888's4←'I never give ''em hell, I just tell the truth, 's4,←'and they think it''s hell. 's5←' 's5,←' --- Harry S Truman 'strs←s1s2s3s4s5⍝ Collapse each string and display it as specified↑collapsedisplay¨strs}
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 »»»
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:}]looplines'line->printsqueezeline
"If I were two-faced, would I be wearing this one?" - Abraham Lincoln .178I never give 'em hel, I just tel the truth, and they think it's hel. - Hary S Truman
collapsible_string(str){fori,chinStrSplit(str){if(ch<>prev)res.=chprev:=ch}return"original string:`t"StrLen(str)" characters`t«««"str"»»»`nresultant string:`t"StrLen(res)" characters`t«««"res"»»»"}
Examples:
data:=["","""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 "]fori,vindataMsgBox%:=collapsible_string(v)return
Outputs:
-----------------------------------------original string:0 characters«««»»»resultant string:0 characters«««»»»-----------------------------------------original string:72 characters«««"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln »»»resultant string:70 characters«««"If I were two-faced, would I be wearing this one?" - Abraham Lincoln »»»-----------------------------------------original string:72 characters«««..1111111111111111111111111111111111111111111111111111111111111117777888»»»resultant string:4 characters«««.178»»»-----------------------------------------original string:72 characters«««I never give 'em hell, I just tell the truth, and they think it's hell. »»»resultant string:69 characters«««I never give 'em hel, I just tel the truth, and they think it's hel. »»»-----------------------------------------original string:72 characters««« --- Harry S Truman »»»resultant string:17 characters««« - Hary S Truman »»»-----------------------------------------
# syntax: GAWK -f DETERMINE_IF_A_STRING_IS_COLLAPSIBLE.AWKBEGIN{for(i=1;i<=9;i++){for(j=1;j<=i;j++){arr[0]=arr[0]i}}arr[++n]=""arr[++n]="\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln "arr[++n]="..1111111111111111111111111111111111111111111111111111111111111117777888"arr[++n]="I never give 'em hell, I just tell the truth, and they think it's hell. "arr[++n]=" --- Harry S Truman "arr[++n]="The better the 4-wheel drive, the further you'll be from help when ya get stuck!"arr[++n]="headmistressship"for(i=0;i<=n;i++){main(arr[i])}exit(0)}functionmain(str,c,i,new_str,prev_c){for(i=1;i<=length(str);i++){c=substr(str,i,1)if(prev_c!=c){prev_c=cnew_str=new_strc}}printf("old: %2d <<<%s>>>\n",length(str),str)printf("new: %2d <<<%s>>>\n\n",length(new_str),new_str)}
old: 45 <<<122333444455555666666777777788888888999999999>>>new: 9 <<<123456789>>>old: 0 <<<>>>new: 0 <<<>>>old: 72 <<<"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln >>>new: 70 <<<"If I were two-faced, would I be wearing this one?" - Abraham Lincoln >>>old: 72 <<<..1111111111111111111111111111111111111111111111111111111111111117777888>>>new: 4 <<<.178>>>old: 72 <<<I never give 'em hell, I just tell the truth, and they think it's hell. >>>new: 69 <<<I never give 'em hel, I just tel the truth, and they think it's hel. >>>old: 72 <<< --- Harry S Truman >>>new: 17 <<< - Hary S Truman >>>old: 80 <<<The better the 4-wheel drive, the further you'll be from help when ya get stuck!>>>new: 77 <<<The beter the 4-whel drive, the further you'l be from help when ya get stuck!>>>old: 16 <<<headmistressship>>>new: 14 <<<headmistreship>>>
DATA ""DATA "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln "DATA "..1111111111111111111111111111111111111111111111111111111111111117777888"DATA "I never give 'em hell, I just tell the truth, and they think it's hell. "DATA " --- Harry S Truman "DATA "The better the 4-wheel drive, the further you'll be from help when ya get stuck!"DATA "headmistressship"DOTIMES 7 READ x$ found = 0 PRINT "<<<", x$, ">>> - length: ", LEN(x$) PRINT "<<<"; FOR y = 1 TO LEN(x$) IF MID$(x$, y, 1) <> MID$(x$, y+1, 1) THEN PRINT MID$(x$, y, 1); INCR found ENDIF NEXT PRINT ">>> - length: ", foundDONE
<<<>>> - 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<<<The better the 4-wheel drive, the further you'll be from help when ya get stuck!>>> - length: 80<<<The beter the 4-whel drive, the further you'l be from help when ya get stuck!>>> - length: 77<<<headmistressship>>> - length: 16<<<headmistreship>>> - length: 14
10READN%20FORA%=1TON%30READI$:GOSUB10040PRINTLEN(I$);"<<<";I$;">>>"50PRINTLEN(O$);"<<<";O$;">>>"55PRINT60NEXT70END100REM Collapse I$ into O$105IFI$=""THENO$=I$:RETURN110O$=SPACE$(LEN(I$))120P$=LEFT$(I$,1)130MID$(O$,1,1)=P$140O%=2150FORI%=2TOLEN(I$)160C$=MID$(I$,I%,1)170IFP$<>C$THENMID$(O$,O%,1)=C$:O%=O%+1:P$=C$180NEXT190O$=LEFT$(O$,O%-1)200RETURN400DATA5:REMThereare5strings410DATA""420DATA"'If I were two-faced, would I be wearing this one?' --- Abraham Lincoln "430DATA"..1111111111111111111111111111111111111111111111111111111111111117777888"440DATA"I never give 'em hell, I just tell the truth, and they think it's hell. "450DATA" --- Harry S Truman "
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 >>>
10READN20FORA=1TON30READI$40GOSUB100"COLLAPSE50PRINTLEN(I$)" <<<"I$">>>"60PRINTLEN(O$)" <<<"O$">>>"70PRINT80NEXT90ENDREM COLLAPSE100O$=I$110IFLEN(I$)<2THENRETURN120O$=""130P$=""140FORI=1TOLEN(i$)150C$=MID$(I$,I,1)160IFC$<>P$THENO$=O$+C$170P$=C$180NEXTI190RETURN400DATA5410DATA""420DATA"'If I were two-faced, would I be wearing this one?' --- Abraham Lincoln "430DATA"..1111111111111111111111111111111111111111111111111111111111111117777888"440DATA"I never give 'em hell, I just tell the truth, and they think it's hell. "450DATA" --- Harry S Truman "
get "libhdr"// Collapse a stringlet 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 lengthlet brackets(s) be writef("%N: <<<%S>>>*N", s%0, s)// Print original and collapsed versionlet 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 ")$)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 >>>
The base function is very simple: Keep adjacent unequal characters, make sure the first character is always preserved.
Collapse←(1»≠⟜«)⊸/>⍉⊢‿Collapse(≠⋈"<<<"⊸∾∘∾⟜">>>")∘{𝕎𝕩}⌜⟨"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 "⟩
┌─╎ 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 >>>" ┘
( colapse = previous . str $ ( vap $ ( ( = . !arg:!previous& | !arg:?previous ) . !arg ) ) )& ( testcolapse = len . (len=.@(!arg:? [?arg)&!arg) & out$(str$(««« !arg "»»» " len$!arg)) & colapse$!arg:?arg & out$(str$(««« !arg "»»» " len$!arg)) )& testcolapse$& testcolapse $ "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln "& testcolapse $ "..1111111111111111111111111111111111111111111111111111111111111117777888"& testcolapse $ "I never give 'em hell, I just tell the truth, and they think it's hell. "& testcolapse $ " --- Harry S Truman "
Output
«««»»» 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
Identical implementation as inDetermine_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.
#include<string.h>#include<stdlib.h>#include<stdio.h>#define COLLAPSE 0#define SQUEEZE 1typedefstructcharList{charc;structcharList*next;}charList;/*Implementing strcmpi, the case insensitive string comparator, as it is not part of the C Standard Library.Comment this out if testing on a compiler where it is already defined.*/intstrcmpi(char*str1,char*str2){intlen1=strlen(str1),len2=strlen(str2),i;if(len1!=len2){return1;}else{for(i=0;i<len1;i++){if((str1[i]>='A'&&str1[i]<='Z')&&(str2[i]>='a'&&str2[i]<='z')&&(str2[i]-65!=str1[i]))return1;elseif((str2[i]>='A'&&str2[i]<='Z')&&(str1[i]>='a'&&str1[i]<='z')&&(str1[i]-65!=str2[i]))return1;elseif(str1[i]!=str2[i])return1;}}return0;}charList*strToCharList(char*str){intlen=strlen(str),i;charList*list,*iterator,*nextChar;list=(charList*)malloc(sizeof(charList));list->c=str[0];list->next=NULL;iterator=list;for(i=1;i<len;i++){nextChar=(charList*)malloc(sizeof(charList));nextChar->c=str[i];nextChar->next=NULL;iterator->next=nextChar;iterator=nextChar;}returnlist;}char*charListToString(charList*list){charList*iterator=list;intcount=0,i;char*str;while(iterator!=NULL){count++;iterator=iterator->next;}str=(char*)malloc((count+1)*sizeof(char));iterator=list;for(i=0;i<count;i++){str[i]=iterator->c;iterator=iterator->next;}free(list);str[i]='\0';returnstr;}char*processString(charstr[100],intoperation,charsqueezeChar){charList*strList=strToCharList(str),*iterator=strList,*scout;if(operation==SQUEEZE){while(iterator!=NULL){if(iterator->c==squeezeChar){scout=iterator->next;while(scout!=NULL&&scout->c==squeezeChar){iterator->next=scout->next;scout->next=NULL;free(scout);scout=iterator->next;}}iterator=iterator->next;}}else{while(iterator!=NULL&&iterator->next!=NULL){if(iterator->c==(iterator->next)->c){scout=iterator->next;squeezeChar=iterator->c;while(scout!=NULL&&scout->c==squeezeChar){iterator->next=scout->next;scout->next=NULL;free(scout);scout=iterator->next;}}iterator=iterator->next;}}returncharListToString(strList);}voidprintResults(charoriginalString[100],charfinalString[100],intoperation,charsqueezeChar){if(operation==SQUEEZE){printf("Specified Operation : SQUEEZE\nTarget Character : %c",squeezeChar);}elseprintf("Specified Operation : COLLAPSE");printf("\nOriginal %c%c%c%s%c%c%c\nLength : %d",174,174,174,originalString,175,175,175,(int)strlen(originalString));printf("\nFinal %c%c%c%s%c%c%c\nLength : %d\n",174,174,174,finalString,175,175,175,(int)strlen(finalString));}intmain(intargc,char**argv){intoperation;charsqueezeChar;if(argc<3||argc>4){printf("Usage : %s <SQUEEZE|COLLAPSE> <String to be processed> <Character to be squeezed, if operation is SQUEEZE>\n",argv[0]);return0;}if(strcmpi(argv[1],"SQUEEZE")==0&&argc!=4){scanf("Please enter characted to be squeezed : %c",&squeezeChar);operation=SQUEEZE;}elseif(argc==4){operation=SQUEEZE;squeezeChar=argv[3][0];}elseif(strcmpi(argv[1],"COLLAPSE")==0){operation=COLLAPSE;}if(strlen(argv[2])<2){printResults(argv[2],argv[2],operation,squeezeChar);}else{printResults(argv[2],processString(argv[2],operation,squeezeChar),operation,squeezeChar);}return0;}
Output :
C:\My Projects\networks>a collapse "The better the 4-wheel drive, the further you'll be from help when ya get stuck!"Specified Operation : COLLAPSEOriginal «««The better the 4-wheel drive, the further you'll be from help when ya get stuck!»»»Length : 80Final «««The beter the 4-whel drive, the further you'l be from help when ya get stuck!»»»Length : 77C:\My Projects\networks>a collapse headmistressshipSpecified Operation : COLLAPSEOriginal «««headmistressship»»»Length : 16Final «««headmistreship»»»Length : 14C:\My Projects\networks>a collapse ""Specified Operation : COLLAPSEOriginal «««»»»Length : 0Final «««»»»Length : 0C:\My Projects\networks>a collapse "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln"Specified Operation : COLLAPSEOriginal «««"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln»»»Length : 71Final «««"If I were two-faced, would I be wearing this one?" - Abraham Lincoln»»»Length : 69C:\My Projects\networks>a collapse ..1111111111111111111111111111111111111111111111111111111111111117777888Specified Operation : COLLAPSEOriginal «««..1111111111111111111111111111111111111111111111111111111111111117777888»»»Length : 72Final «««.178»»»Length : 4C:\My Projects\networks>a collapse "I never give 'em hell, I just tell the truth, and they think it's hell."Specified Operation : COLLAPSEOriginal «««I never give 'em hell, I just tell the truth, and they think it's hell.»»»Length : 71Final «««I never give 'em hel, I just tel the truth, and they think it's hel.»»»Length : 68C:\My Projects\networks>a collapse " --- Harry S Truman"Specified Operation : COLLAPSEOriginal ««« --- Harry S Truman»»»Length : 70Final ««« - Hary S Truman»»»Length : 16
usingSystem;usingstaticSystem.Linq.Enumerable;publicclassProgram{staticvoidMain(){string[]input={"","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 "};foreach(stringsininput){Console.WriteLine($"old: {s.Length} «««{s}»»»");stringc=Collapse(s);Console.WriteLine($"new: {c.Length} «««{c}»»»");}}staticstringCollapse(strings)=>string.IsNullOrEmpty(s)?"":s[0]+newstring(Range(1,s.Length-1).Where(i=>s[i]!=s[i-1]).Select(i=>s[i]).ToArray());}
old: 0 «««»»»new: 0 «««»»»old: 80 «««The better the 4-wheel drive, the further you'll be from help when ya get stuck!»»»new: 77 «««The beter the 4-whel drive, the further you'l be from help when ya get stuck!»»»old: 16 «««headmistressship»»»new: 14 «««headmistreship»»»old: 72 «««"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln »»»new: 70 «««"If I were two-faced, would I be wearing this one?" - Abraham Lincoln »»»old: 72 «««..1111111111111111111111111111111111111111111111111111111111111117777888»»»new: 4 «««.178»»»old: 72 «««I never give 'em hell, I just tell the truth, and they think it's hell. »»»new: 69 «««I never give 'em hel, I just tel the truth, and they think it's hel. »»»old: 72 ««« --- Harry S Truman »»»new: 17 ««« - Hary S Truman »»»
The solution is a straightforward application of the standard library function "unique".
#include<string>#include<iostream>#include<algorithm>template<typenamechar_type>std::basic_string<char_type>collapse(std::basic_string<char_type>str){autoi=std::unique(str.begin(),str.end());str.erase(i,str.end());returnstr;}voidtest(conststd::string&str){std::cout<<"original string: <<<"<<str<<">>>, length = "<<str.length()<<'\n';std::stringcollapsed(collapse(str));std::cout<<"result string: <<<"<<collapsed<<">>>, length = "<<collapsed.length()<<'\n';std::cout<<'\n';}intmain(intargc,char**argv){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 ");return0;}
original string: <<<>>>, length = 0result string: <<<>>>, length = 0original string: <<<"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln >>>, length = 72result string: <<<"If I were two-faced, would I be wearing this one?" - Abraham Lincoln >>>, length = 70original string: <<<..1111111111111111111111111111111111111111111111111111111111111117777888>>>, length = 72result string: <<<.178>>>, length = 4original string: <<<I never give 'em hell, I just tell the truth, and they think it's hell. >>>, length = 72result string: <<<I never give 'em hel, I just tel the truth, and they think it's hel. >>>, length = 69original string: <<< --- Harry S Truman >>>, length = 72result string: <<< - Hary S Truman >>>, length = 17
(defncollapse[s](let[runs(partition-byidentitys)](apply str(map firstruns))))(defnrun-test[s](let[out(collapses)](str(format"Input: <<<%s>>> (len %d)\n"s(counts))(format"becomes: <<<%s>>> (len %d)\n"out(countout)))))
Input: <<<>>> (len 0)becomes: <<<>>> (len 0)Input: <<<"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln >>> (len 72)becomes: <<<"If I were two-faced, would I be wearing this one?" - Abraham Lincoln >>> (len 70)Input: <<<..1111111111111111111111111111111111111111111111111111111111111117777888>>> (len 72)becomes: <<<.178>>> (len 4)Input: <<<I never give 'em hell, I just tell the truth, and they think it's hell. >>> (len 72)becomes: <<<I never give 'em hel, I just tel the truth, and they think it's hel. >>> (len 69)Input: <<< --- Harry S Truman >>> (len 72)becomes: <<< - Hary S Truman >>> (len 17)
% 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 lengthbrackets = 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 lengthsshow = proc (s: string) brackets(s) brackets(collapse(s)) stream$putl(stream$primary_output(), "")end show% Try the examples from the task descriptionstart_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) endend start_up
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 >>>
include "cowgol.coh";include "strings.coh";# Collapse the string at in, and store the result in the given buffersub 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 outputsub 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 taskvar 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 stringvar i: @indexof strings := 0;while i < @sizeof strings loop show(strings[i]); i := i + 1;end loop;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 >>>
Copied verbatim fromRuby, except changing a string delimiter to double quotes (in Crystal, single quotes delimit characters and double quotes strings).
For the output see that entry, it's exactly the same.
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","😍😀🙌💃😍😍😍🙌",]strings.eachdo|str|puts"«««#{str}»»» (size#{str.size})"ssq=str.squeezeputs"«««#{ssq}»»» (size#{ssq.size})"putsend
importstd.stdio;voidcollapsible(strings){writeln("old: <<<",s,">>>, length = ",s.length);write("new: <<<");charlast='\0';intlen=0;foreach(c;s){if(c!=last){write(c);len++;}last=c;}writeln(">>>, length = ",len);writeln;}voidmain(){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 `);}
old: <<<>>>, length = 0new: <<<>>>, length = 0old: <<<"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln >>>, length = 72new: <<<"If I were two-faced, would I be wearing this one?" - Abraham Lincoln >>>, length = 70old: <<<..1111111111111111111111111111111111111111111111111111111111111117777888>>>, length = 72new: <<<.178>>>, length = 4old: <<<I never give 'em hell, I just tell the truth, and they think it's hell. >>>, length = 72new: <<<I never give 'em hel, I just tel the truth, and they think it's hel. >>>, length = 69old: <<< --- Harry S Truman >>>, length = 72new: <<< - Hary S Truman >>>, length = 17
programDetermine_if_a_string_is_collapsible;{$APPTYPE CONSOLE}usesSystem.SysUtils;procedurecollapsible(s:string);varc,last:char;len:Integer;beginwriteln('old: <<<',s,'>>>, length = ',s.length);write('new: <<<');last:=#0;len:=0;forcinsdobeginifc<>lastthenbeginwrite(c);inc(len);end;last:=c;end;writeln('>>>, length = ',len,#10);end;begincollapsible('');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.
createorreplacefunctionuniq(lst)aslist_filter(lst,(x,i)->i=1orlst[i-1]!=x);createorreplacefunctioncollapse(str)asstring_split(str,'').uniq().array_to_string('');.maxwidth200selectlength(s),collapse(s)ascollapsed,length(collapsed)fromunnest(['','"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 '])_(s);
┌───────────┬────────────────────────────────────────────────────────────────────────┬───────────────────┐│ length(s) │ collapsed │ length(collapsed) ││ int64 │ varchar │ int64 │├───────────┼────────────────────────────────────────────────────────────────────────┼───────────────────┤│ 0 │ │ 0 ││ 72 │ "If I were two-faced, would I be wearing this one?" - Abraham Lincoln │ 70 ││ 72 │ .178 │ 4 ││ 72 │ I never give 'em hel, I just tel the truth, and they think it's hel. │ 69 ││ 72 │ - Hary S Truman │ 17 │└───────────┴────────────────────────────────────────────────────────────────────────┴───────────────────┘
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 "".«««»»» (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)
# by Artyom BologovHg/\(.\)\1*/s//\1/g,pQ
$ ed -s collapsible.input < collapsible.ed Newline appended"If I were two-faced, would I be wearing this one?" - Abraham Lincoln.178I never give 'em hel, I just tel the truth, and they think it's hel. - Hary S Truman
// 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.letisCollapsiblen=n|>Seq.pairwise|>Seq.tryFind(fun(n,g)->n=g)//As per the task description a function which 'if the string is collapsable, collapses the string (by removing immediately repeated characters).letcollapsen=matchisCollapsiblenwithSome_->leti=Seq.headnletfN=letmutableg=iin(funn->ifn=gthenfalseelseg<-n;true)letg=System.String([|yieldi;yield!Seq.tailn|>Seq.filterfN|])printfn"<<<%s>>> (length %d) colapses to <<<%s>>> (length %d)"nn.Lengthgg.Length|_->printfn"<<<%s>>> (length %d) does not colapse"nn.Lengthcollapse""collapse"\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln "collapse"..1111111111111111111111111111111111111111111111111111111111111117777888"collapse"I never give 'em hell, I just tell the truth, and they think it's hell. "collapse" --- Harry S Truman "collapse"withoutConsecutivelyRepeatedCharacters"
<<<>>> (length 0) does not colapse<<<"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln >>> (length 72) collapses to <<<"If I were two-faced, would I be wearing this one?" - Abraham Lincoln >>> (length 70)<<<..1111111111111111111111111111111111111111111111111111111111111117777888>>> (length 72) collapses to <<<.178>>> (length 4)<<<I never give 'em hell, I just tell the truth, and they think it's hell. >>> (length 72) collapses to <<<I never give 'em hel, I just tel the truth, and they think it's hel. >>> (length 69)<<< --- Harry S Truman >>> (length 72) collapses to <<< - Hary S Truman >>> (length 17)<<<withoutConsecutivelyRepeatedCharacters>>> (length 38) does not collapse
USING:formattingiokernelsbufssequencesstrings;IN:rosetta-code.string-collapse:(collapse)(str--str)unclip-slice1string>sbuf[overlastover=[drop][suffix!]if]reduce>string;:collapse(str--str)[""][(collapse)]if-empty;:.str(str--)duplength"«««%s»»» (length %d)\n"printf;:show-collapse(str--)["Before collapse: "write.str]["After collapse: "writecollapse.str]binl;:collapse-demo(--){"""\"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""😍😀🙌💃😍😍😍🙌"}[show-collapse]each;MAIN:collapse-demo
(Using some extra test cases from the Go entry.)
Before collapse: «««»»» (length 0)After collapse: «««»»» (length 0)Before collapse: «««"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln »»» (length 72)After collapse: «««"If I were two-faced, would I be wearing this one?" - Abraham Lincoln »»» (length 70)Before collapse: «««..1111111111111111111111111111111111111111111111111111111111111117777888»»» (length 72)After collapse: «««.178»»» (length 4)Before collapse: «««I never give 'em hell, I just tell the truth, and they think it's hell. »»» (length 72)After collapse: «««I never give 'em hel, I just tel the truth, and they think it's hel. »»» (length 69)Before collapse: ««« --- Harry S Truman »»» (length 72)After collapse: ««« - Hary S Truman »»» (length 17)Before collapse: «««The better the 4-wheel drive, the further you'll be from help when ya get stuck!»»» (length 80)After collapse: «««The beter the 4-whel drive, the further you'l be from help when ya get stuck!»»» (length 77)Before collapse: «««headmistressship»»» (length 16)After collapse: «««headmistreship»»» (length 14)Before collapse: «««aardvark»»» (length 8)After collapse: «««ardvark»»» (length 7)Before collapse: «««😍😀🙌💃😍😍😍🙌»»» (length 8)After collapse: «««😍😀🙌💃😍🙌»»» (length 6)
ConstnumCad=5Data""Data"'If I were two-faced, would I be wearing this one?' --- Abraham Lincoln "Data"..1111111111111111111111111111111111111111111111111111111111111117777888"Data"I never give 'em hell, I just tell the truth, and they think it's hell. "Data" --- Harry S Truman "DimSharedAsStringcadIN,cadOUTSubCollapseDimAsStringa,bIfcadIN=""ThencadOUT=cadIN:ExitSubcadOUT=Space(Len(cadIN))a=Left(cadIN,1)Mid(cadOUT,1,1)=aDimAsIntegertxtOUT=2ForiAsInteger=2ToLen(cadIN)b=Mid(cadIN,i,1)Ifa<>bThenMid(cadOUT,txtOUT,1)=b:txtOUT+=1:a=bNexticadOUT=Left(cadOUT,txtOUT-1)EndSubForjAsInteger=1TonumCadReadcadINCollapsePrint" <<<";cadIN;">>> (longitud ";Len(cadIN);_!")\n se pliega a:\n <<<";cadOUT;">>> (longitud ";Len(cadOUT);!")\n"NextjSleep
<<<>>> (longitud 0) se pliega a: <<<>>> (longitud 0) <<<'If I were two-faced, would I be wearing this one?' --- Abraham Lincoln >>> (longitud 72) se pliega a: <<<'If I were two-faced, would I be wearing this one?' - Abraham Lincoln >>> (longitud 70) <<<..1111111111111111111111111111111111111111111111111111111111111117777888>>> (longitud 72) se pliega a: <<<.178>>> (longitud 4) <<<I never give 'em hell, I just tell the truth, and they think it's hell. >>> (longitud 72) se pliega a: <<<I never give 'em hel, I just tel the truth, and they think it's hel. >>> (longitud 69) <<< --- Harry S Truman >>> (longitud 72) se pliega a: <<< - Hary S Truman >>> (longitud 17)
collapse[str] := str =~ %s/(.)\1+/$1/glines = ["", """"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]]
"If I were two-faced, would I be wearing this one?" - Abraham Lincoln .178I never give 'em hel, I just tel the truth, and they think it's hel. - Hary S Truman
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 nextend fn = outStringwindow 1, @"Collapse String", (0,0,600,300)CFStringRef string, collapsedStringstring = @""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
<<<>>> 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
packagemainimport"fmt"// Returns collapsed string, original and new lengths in// unicode code points (not normalized).funccollapse(sstring)(string,int,int){r:=[]rune(s)le,del:=len(r),0fori:=le-2;i>=0;i--{ifr[i]==r[i+1]{copy(r[i:],r[i+1:])del++}}ifdel==0{returns,le,le}r=r[:le-del]returnstring(r),le,len(r)}funcmain(){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:=rangestrings{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)}}
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 = «««😍😀🙌💃😍🙌»»»
classStringCollapsible{staticvoidmain(String[]args){for(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 ","122333444455555666666777777788888888999999999","The better the 4-wheel drive, the further you'll be from help when ya get stuck!","headmistressship"]){Stringresult=collapse(s)System.out.printf("old: %2d <<<%s>>>%nnew: %2d <<<%s>>>%n%n",s.length(),s,result.length(),result)}}privatestaticStringcollapse(Stringinput){StringBuildersb=newStringBuilder()for(inti=0;i<input.length();i++){if(i==0||input.charAt(i-1)!=input.charAt(i)){sb.append(input.charAt(i))}}returnsb.toString()}}
old: 0 <<<>>>new: 0 <<<>>>old: 72 <<<"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln >>>new: 70 <<<"If I were two-faced, would I be wearing this one?" - Abraham Lincoln >>>old: 72 <<<..1111111111111111111111111111111111111111111111111111111111111117777888>>>new: 4 <<<.178>>>old: 72 <<<I never give 'em hell, I just tell the truth, and they think it's hell. >>>new: 69 <<<I never give 'em hel, I just tel the truth, and they think it's hel. >>>old: 72 <<< --- Harry S Truman >>>new: 17 <<< - Hary S Truman >>>old: 45 <<<122333444455555666666777777788888888999999999>>>new: 9 <<<123456789>>>old: 80 <<<The better the 4-wheel drive, the further you'll be from help when ya get stuck!>>>new: 77 <<<The beter the 4-whel drive, the further you'l be from help when ya get stuck!>>>old: 16 <<<headmistressship>>>new: 14 <<<headmistreship>>>
importText.Printf(printf)importData.Maybe(catMaybes)importControl.Monad(guard)input::[String]input=["","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 ","😍😀🙌💃😍😍😍🙌"]collapse::Eqa=>[a]->[a]collapse=catMaybes.(\xs->zipWith(\ab->guard(a/=b)>>a)(Nothing:xs)(xs<>[Nothing])).mapJustmain::IO()main=mapM_(\(a,b)->printf"old: %3d «««%s»»»\nnew: %3d «««%s»»»\n\n"(lengtha)a(lengthb)b)$((,)<*>collapse)<$>input
old: 0 «««»»»new: 0 «««»»»old: 80 «««The better the 4-wheel drive, the further you'll be from help when ya get stuck!»»»new: 77 «««The beter the 4-whel drive, the further you'l be from help when ya get stuck!»»»old: 16 «««headmistressship»»»new: 14 «««headmistreship»»»old: 72 «««"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln »»»new: 70 «««"If I were two-faced, would I be wearing this one?" - Abraham Lincoln »»»old: 72 «««..1111111111111111111111111111111111111111111111111111111111111117777888»»»new: 4 «««.178»»»old: 72 «««I never give 'em hell, I just tell the truth, and they think it's hell. »»»new: 69 «««I never give 'em hel, I just tel the truth, and they think it's hel. »»»old: 72 ««« --- Harry S Truman »»»new: 17 ««« - Hary S Truman »»»old: 8 «««😍😀🙌💃😍😍😍🙌»»»new: 6 «««😍😀🙌💃😍🙌»»»
Note that we can also directly define a predicate, and a rewrite, in terms ofData.List group,
importData.List(group)isCollapsible::String->BoolisCollapsible=any((1<).length).groupcollapsed::String->Stringcollapsed=maphead.group
or, without imports, in terms of pattern matching:
isCollapsible::String->BoolisCollapsible[]=FalseisCollapsible[_]=FalseisCollapsible(h:t@(x:_))=h==x||isCollapsibletcollapsed::String->Stringcollapsed[]=[]collapsed[x]=[x]collapsed(h:t@(x:_))|h==x=collapsedt|otherwise=h:collapsedt
The following works in both languages.
procedure 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 " ] while collapse(!strings)endprocedure collapse(s) ns := "" s ? while ns ||:= move(1) do tab(many(ns[*ns])) write("original: <<<",s,">>>",*s) write("collapsed:<<<",ns,">>>",*ns)endOutput:
original: <<<>>>0collapsed:<<<>>>0original: <<<"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln >>>72collapsed:<<<"If I were two-faced, would I be wearing this one?" - Abraham Lincoln >>>70original: <<<..1111111111111111111111111111111111111111111111111111111111111117777888>>>72collapsed:<<<.178>>>4original: <<<I never give 'em hell, I just tell the truth, and they think it's hell. >>>72collapsed:<<<I never give 'em hel, I just tel the truth, and they think it's hel. >>>69original: <<< --- Harry S Truman >>>72collapsed:<<< - Hary S Truman >>>1
STRINGS =: <;._2]0 :0"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ..1111111111111111111111111111111111111111111111111111111111111117777888I never give 'em hell, I just tell the truth, and they think it's hell. --- Harry S Truman ) collapse =: (#~ (1 , 2 ~:/\ ])) ::(''"_) NB. copy dissimilar neighbors assert 1 2 3 2 3 1 2 1 -: collapse 1 2 3 2 2 2 2 3 1 1 2 2 1 NB. test task =: ,&(<@:(;~ (_6 + #)))&('<<<' , '>>>' ,~ ]) collapse NB. assemble the output task&> STRINGS NB. operate on the data+-----------------------------------------------------------------------------------+---------------------------------------------------------------------------------+|+-+------+ |+-+------+ |||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 >>>| ||+--+------------------------------------------------------------------------------+|+--+-----------------------+ |+-----------------------------------------------------------------------------------+---------------------------------------------------------------------------------+// Title: Determine if a string is collapsiblepublicclassStringCollapsible{publicstaticvoidmain(String[]args){for(Strings:newString[]{"","\"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 ","122333444455555666666777777788888888999999999","The better the 4-wheel drive, the further you'll be from help when ya get stuck!","headmistressship"}){Stringresult=collapse(s);System.out.printf("old: %2d <<<%s>>>%nnew: %2d <<<%s>>>%n%n",s.length(),s,result.length(),result);}}privatestaticStringcollapse(Stringin){StringBuildersb=newStringBuilder();for(inti=0;i<in.length();i++){if(i==0||in.charAt(i-1)!=in.charAt(i)){sb.append(in.charAt(i));}}returnsb.toString();}}
old: 0 <<<>>>new: 0 <<<>>>old: 72 <<<"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln >>>new: 70 <<<"If I were two-faced, would I be wearing this one?" - Abraham Lincoln >>>old: 72 <<<..1111111111111111111111111111111111111111111111111111111111111117777888>>>new: 4 <<<.178>>>old: 72 <<<I never give 'em hell, I just tell the truth, and they think it's hell. >>>new: 69 <<<I never give 'em hel, I just tel the truth, and they think it's hel. >>>old: 72 <<< --- Harry S Truman >>>new: 17 <<< - Hary S Truman >>>old: 45 <<<122333444455555666666777777788888888999999999>>>new: 9 <<<123456789>>>old: 80 <<<The better the 4-wheel drive, the further you'll be from help when ya get stuck!>>>new: 77 <<<The beter the 4-whel drive, the further you'l be from help when ya get stuck!>>>old: 16 <<<headmistressship>>>new: 14 <<<headmistreship>>>
String.prototype.collapse=function(){letstr=this;for(leti=0;i<str.length;i++){while(str[i]==str[i+1])str=str.substr(0,i)+str.substr(i+1);}returnstr;}// testingletstrings=['','"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(leti=0;i<strings.length;i++){letstr=strings[i],col=str.collapse();console.log(`«««${str}»»» (${str.length})`);console.log(`«««${col}»»» (${col.length})`);}
«««»»» (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)
Here we can use the Unix-like `uniq` function defined on (JSON) arrays to define `collapse` on (JSON) strings:
# Input: an array# Output: a streamdef uniq: foreach .[] as $x ({x:nan, y:.[0]}; {x:$x, y:.x}; select(.x != .y) | .x);def collapse: explode | [uniq] | implode;The program for the given task can now be written in three lines:
def Guillemets: "«««\(.)»»»";"Original: \(Guillemets) has length \(length)",(collapse | "Collapsed \(Guillemets) has length \(length)")
Using the following invocation on the five "raw" (i.e. unquoted) strings yields the results as shown:
jq -Rrf program.jq raw.txt
Original:«««»»»haslength0Collapsed«««»»»haslength0Original:«««"If I were two-faced, would I be wearing this one?"---AbrahamLincoln»»»haslength72Collapsed«««"If I were two-faced, would I be wearing this one?"-AbrahamLincoln»»»haslength70Original:«««..1111111111111111111111111111111111111111111111111111111111111117777888»»»haslength72Collapsed«««.178»»»haslength4Original:«««Inevergive'em hell, I just tell the truth, and they think it'shell.»»»haslength72Collapsed«««Inevergive'em hel, I just tel the truth, and they think it'shel.»»»haslength69Original:«««---HarrySTruman»»»haslength72Collapsed«««-HarySTruman»»»haslength17
constteststrings=["",""""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 "]functioncollapse(s)len=length(s)iflen<2returns,len,s,lenendresult=last=s[1]forcins[2:end]ifc!=lastlast=cresult*=cendendreturns,len,result,length(result)endfunctiontestcollapse(arr)forsinarr(s1,len1,s2,len2)=collapse(s)println("«««$s1»»» (length$len1)\n collapses to:\n«««$s2»»» (length$len2).\n")endendtestcollapse(teststrings)
«««»»» (length 0) collapses to:«««»»» (length 0).«««"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln »»» (length 72) collapses to:«««"If I were two-faced, would I be wearing this one?" - Abraham Lincoln »»» (length 70).«««..1111111111111111111111111111111111111111111111111111111111111117777888»»» (length 72) collapses to:«««.178»»» (length 4).«««I never give 'em hell, I just tell the truth, and they think it's hell. »»» (length 72) collapses to:«««I never give 'em hel, I just tel the truth, and they think it's hel. »»» (length 69).««« --- Harry S Truman »»» (length 72) collapses to:««« - Hary S Truman »»» (length 17).
constteststrings=["",""""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(s)=(t=isempty(s)?"":s[1:1];forcinsifc!=t[end]t*=cend;end;t)forsinteststringsn,t=length(s),collapse(s)println("«««$s»»» (length$n)\n collapses to:\n«««$t»»» (length$(length(t))).\n")end
funcollapse(s:String):String{valcs=StringBuilder()varlast:Char=0.toChar()for(cins){if(c!=last){cs.append(c)last=c}}returncs.toString()}funmain(){valstrings=arrayOf("","\"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(sinstrings){valc=collapse(s)println("original : length = ${s.length}, string = «««$s»»»")println("collapsed : length = ${c.length}, string = «««$c»»»")println()}}
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»»»
#!/bin/ksh# Determine if a string is collapsible (repeated letters)## Variables:#typeset-astringsstrings[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-aGuillemet=("«««""»»»")## Functions:### Function _collapse(str) - return colapsed version of str#function_collapse{typeset_str;_str="$1"typeset_i_buff;integer_ifor((_i=1;_i<${#_str};_i++));doif[["${_str:$((_i-1)):1}"=="${_str:${_i}:1}"]];thencontinueelse_buff+=${_str:$((_i-1)):1}fidone[["${_str:$((_i-1)):1}"!="${_str:${_i}:1}"]]&&_buff+=${_str:$((_i-1)):1}echo"${_buff}"}####### main #######for((i=0;i<${#strings[*]};i++));dostr=$(_collapse"${strings[i]}")print${#strings[i]}"${Guillemet[0]}${strings[i]}${Guillemet[1]}"print${#str}"${Guillemet[0]}${str}${Guillemet[1]}\n"done
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»»»
functioncollapse(s)localns=""locallast=nilforcins:gmatch"."doiflasttheniflast~=cthenns=ns..cendlast=celsens=ns..clast=cendendreturnnsendfunctiontest(s)print("old: "..s:len().." <<<"..s..">>>")locala=collapse(s)print("new: "..a:len().." <<<"..a..">>>")endfunctionmain()test("")test("The better the 4-wheel drive, the further you'll be from help when ya get stuck!")test("headmistressship")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 ")endmain()
old: 0 <<<>>>new: 0 <<<>>>old: 80 <<<The better the 4-wheel drive, the further you'll be from help when ya get stuck!>>>new: 77 <<<The beter the 4-whel drive, the further you'l be from help when ya get stuck!>>>old: 16 <<<headmistressship>>>new: 14 <<<headmistreship>>>old: 72 <<<"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln >>>new: 70 <<<"If I were two-faced, would I be wearing this one?" - Abraham Lincoln >>>old: 72 <<<..1111111111111111111111111111111111111111111111111111111111111117777888>>>new: 4 <<<.178>>>old: 72 <<<I never give 'em hell, I just tell the truth, and they think it's hell. >>>new: 69 <<<I never give 'em hel, I just tel the truth, and they think it's hel. >>>old: 72 <<< --- Harry S Truman >>>new: 17 <<< - Hary S Truman >>>
ClearAll[StringCollapse]StringCollapse[s_String]:=FixedPoint[StringReplace[y_~~y_:>y],s]strings={"","\"IfIweretwo-faced,wouldIbewearingthisone?\" --- 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}]
«««»»»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
functionr=collapse(s)ix=find((s(1:end-1)==s(2:end))+1;r=s;r(ix)=[];fprintf(1,'Input: <<<%s>>> length: %d\n',s,length(s));fprintf(1,'Output: <<<%s>>> length: %d\n',r,length(r));fprintf(1,'Character to be squeezed: "%s"\n',c);endcollapse('',' ')collapse('║╚═══════════════════════════════════════════════════════════════════════╗','-')collapse('║"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ║','7')collapse('║..1111111111111111111111111111111111111111111111111111111111111117777888║','.')collapse('║I never give ''em hell, I just tell the truth, and they think it''s hell. ║','.')collapse('║ --- Harry S Truman ║','.')collapse('║ --- Harry S Truman ║','-')collapse('║ --- Harry S Truman ║','r')
Input: <<<>>> length: 0Output: <<<>>> length: 0ans = Input: <<<║╚═══════════════════════════════════════════════════════════════════════╗>>> length: 222Output: <<<║╚═══════════════════════════════════════════════════════════════════════╗>>> length: 222ans = ║╚═══════════════════════════════════════════════════════════════════════╗Input: <<<║"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ║>>> length: 78Output: <<<║"If I were two-faced, would I be wearing this one?" - Abraham Lincoln ║>>> length: 76ans = ║"If I were two-faced, would I be wearing this one?" - Abraham Lincoln ║Input: <<<║..1111111111111111111111111111111111111111111111111111111111111117777888║>>> length: 78Output: <<<║.178║>>> length: 10ans = ║.178║Input: <<<║I never give 'em hell, I just tell the truth, and they think it's hell. ║>>> length: 78Output: <<<║I never give 'em hel, I just tel the truth, and they think it's hel. ║>>> length: 75ans = ║I never give 'em hel, I just tel the truth, and they think it's hel. ║Input: <<<║ --- Harry S Truman ║>>> length: 78Output: <<<║ - Hary S Truman ║>>> length: 23ans = ║ - Hary S Truman ║Input: <<<║ --- Harry S Truman ║>>> length: 78Output: <<<║ - Hary S Truman ║>>> length: 23ans = ║ - Hary S Truman ║Input: <<<║ --- Harry S Truman ║>>> length: 78Output: <<<║ - Hary S Truman ║>>> length: 23ans = ║ - Hary S Truman ║PASSES 1 out of 1 test
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
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 >>>
MODULEStrCollapse;FROMInOutIMPORTWriteString,WriteCard,WriteLn;FROMStringsIMPORTLength;(* Collapse a string *)PROCEDURECollapse(in:ARRAYOFCHAR;VARout:ARRAYOFCHAR);VARi,o:CARDINAL;BEGINi:=0;o:=0;WHILE(i<HIGH(in))AND(in[i]#CHR(0))DOIF(o=0)OR(out[o-1]#in[i])THENout[o]:=in[i];INC(o);END;INC(i);END;out[o]:=CHR(0);ENDCollapse;(* Display a string and collapse it as stated in the task *)PROCEDURETask(s:ARRAYOFCHAR);VARbuf:ARRAY[0..127]OFCHAR;PROCEDURELengthAndBrackets(s:ARRAYOFCHAR);BEGINWriteCard(Length(s),2);WriteString(" <<<");WriteString(s);WriteString(">>>");WriteLn();ENDLengthAndBrackets;BEGINLengthAndBrackets(s);Collapse(s,buf);LengthAndBrackets(buf);WriteLn();ENDTask;BEGINTask("");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 ");ENDStrCollapse.
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 >>>
To run the task:
to-report split [ string ] ;; utility reporter to split a string into a list report n-values length string [ [ n ] -> item n string ]endto-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 ]endto-report format [ string ] ;; reporter to format the output as required report ( word "<<<" string ">>> " length string )endto demo-collapse [ string ] ;; procedure to display the required output output-print format string output-print format collapse stringendto 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-collapseend
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
importunicode,strformatproccollapse(s:string)=letoriginal=s.toRunesechofmt"Original: length = {original.len}, string = «««{s}»»»"varprevious=Rune(0)varcollapsed:seq[Rune]forruneinoriginal:ifrune!=previous:collapsed.add(rune)previous=runeechofmt"Collapsed: length = {collapsed.len}, string = «««{collapsed}»»»"echo""constStrings=["","\"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","😍😀🙌💃😍😍😍🙌",]forsinStrings:s.collapse()
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 = «««😍😀🙌💃😍🙌»»»
usestrict;usewarnings;useutf8;binmodeSTDOUT,":utf8";my@lines=split"\n",<<~'STRINGS';"If I were two-faced, would I be wearing this one?"---AbrahamLincoln..1111111111111111111111111111111111111111111111111111111111111117777888Inevergive'em hell, I just tell the truth, and they think it'shell.---HarrySTrumanTheAmericanpeoplehavearighttoknowiftheirpresidentisacrook.---RichardNixonAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAASTRINGSfor(@lines){my$squish=s/(.)\1+/$1/gr;printf"\nLength: %2d <<<%s>>>\nCollapsible: %s\nLength: %2d <<<%s>>>\n",length($_),$_,$_ne$squish?'True':'False',length($squish),$squish}
Length: 0 <<<>>>Collapsible: FalseLength: 0 <<<>>>Length: 72 <<<"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln >>>Collapsible: TrueLength: 70 <<<"If I were two-faced, would I be wearing this one?" - Abraham Lincoln >>>Length: 72 <<<..1111111111111111111111111111111111111111111111111111111111111117777888>>>Collapsible: TrueLength: 4 <<<.178>>>Length: 72 <<<I never give 'em hell, I just tell the truth, and they think it's hell. >>>Collapsible: TrueLength: 69 <<<I never give 'em hel, I just tel the truth, and they think it's hel. >>>Length: 72 <<< --- Harry S Truman >>>Collapsible: TrueLength: 17 <<< - Hary S Truman >>>Length: 72 <<<The American people have a right to know if their president is a crook. >>>Collapsible: TrueLength: 71 <<<The American people have a right to know if their president is a crok. >>>Length: 72 <<< --- Richard Nixon >>>Collapsible: TrueLength: 17 <<< - Richard Nixon >>>Length: 120 <<<AАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑ>>>Collapsible: FalseLength: 120 <<<AАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑ>>>Length: 72 <<<AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA>>>Collapsible: TrueLength: 1 <<<A>>>
##functionCollapse(s:String):=ifString.IsNullOrEmpty(s)Then''elses[1]+newString(Range(2,s.Length).Where(i->s[i]<>s[i-1]).Select(i->s[i]).ToArray);varinput:=|'','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 '|;foreachvarsininputdobeginWriteln('old: ',s.Length,' «««',s,'»»»');varc:=Collapse(s);WriteLn('new: ',c.Length,' «««',c,'»»»')end;
old: 0 «««»»»new: 0 «««»»»old: 80 «««The better the 4-wheel drive, the further you'll be from help when ya get stuck!»»»new: 77 «««The beter the 4-whel drive, the further you'l be from help when ya get stuck!»»»old: 16 «««headmistressship»»»new: 14 «««headmistreship»»»old: 72 «««"If I were two-faced, would I be wearing this one? --- Abraham Lincoln "»»»new: 70 «««"If I were two-faced, would I be wearing this one? - Abraham Lincoln "»»»old: 72 «««..1111111111111111111111111111111111111111111111111111111111111117777888»»»new: 4 «««.178»»»old: 72 «««I never give 'em hell, I just tell the truth, and they think it's hell. »»»new: 69 «««I never give 'em hel, I just tel the truth, and they think it's hel. »»»old: 72 ««« --- Harry S Truman »»»new: 17 ««« - Hary S Truman »»»
PROGRAMcollapsible;(*)collapsible: example of python-like List versionFree Pascal Compiler version 3.2.2 [2024/05/01] for x86_64Free to use, as is, experimentaldirectives:https://www.freepascal.org/docs-html/prog/progch1.html The free and readable alternative at C/C++ speeds compiles natively to almost any platform, including raspberry PI * Can run independently from DELPHI / Lazarus https://www.freepascal.org/advantage.var(*){$IFDEF FPC}{$LONGSTRINGS ON}(*) aka {H+} = ansistrings (*){$RANGECHECKS ON}(*) aka {$R+} (*){$S+}(*) stack checking on (*){$TYPEDADDRESS ON}(*) aka {$T+} (*){$ELSE}{$APPTYPE CONSOLE}{$ENDIF}{$MACRO ON}{$DEFINE crlf := #13#10 }{$DEFINE quot := #39 }USESVariants;{$WARN 6058 off : Call to subroutine "$1" marked as inline is not inlined}// Use for variants, complex numbersTYPEList=arrayofvariant;(*) a mixed list almost like Python uses: all basic types possible - at a cost obviously - (*)FUNCTIONcollapsible(S:string):List;VARk:integer;_:string;BEGIN_:=S[1];FORk:=2TOlength(s)DOIFS[k-1]<>S[k]THEN_:=_+S[k];collapsible:=[_,length(_)];END;VARL:List;S:arrayofstring=('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 ');k:string;(*) END OF MAIN VAR (*)BEGINSetLength(L,2);FORkINSDOBEGINWriteLn(crlf,'Before: ',quot,k,quot,', ',length(k));L:=collapsible(k);WriteLn('After: ',quot,L[0],quot,', ',L[1],crlf);END;SetLength(L,0);ReadLn;END.(*) OF PROGRAM collapsible (*)(*)
JPD 2024/10/16Output:Before: 'headmistressship', 16After: 'headmistreship', 14Before: '"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ', 72After: '"If I were two-faced, would I be wearing this one?" - Abraham Lincoln ', 70Before: '..1111111111111111111111111111111111111111111111111111111111111117777888', 72After: '.178', 4Before: 'I never give 'em hell, I just tell the truth, and they think it's hell. ', 72After: 'I never give 'em hel, I just tel the truth, and they think it's hel. ', 69Before: ' --- Harry S Truman ', 72After: ' - Hary S Truman ', 17
(*)
There is already a builtin we can abuse for this. The documentation of unique() [added for 0.8.1] states:
`If "PRESORTED" is specified, but s is not actually sorted, then only adjacent duplicates are removed.`
If you don't have builtins/punique.e to hand, you may want to take a quick look at squeeze() in[[1]], but obviously w/o ch.
withjavascript_semanticsconstanttests={"",`"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 "},fmt="""length %2d input: <<<%s>>>length %2d output: <<<%s>>>"""fori=1tolength(tests)dostringti=tests[i],ci=unique(ti,"PRESORTED")printf(1,fmt,{length(ti),ti,length(ci),ci})endforfunctioncollapsible(stringt)-- sequence utf32 = utf8_to_utf32(t) -- maybe-- for i=2 to length(utf32) do -- """-- if utf32[i]=utf32[i-1] then -- """fori=2tolength(t)doift[i]=t[i-1]thenreturntrueendifendforreturnfalseendfunctionputs(1,"\nAs predicate: ")fori=1tolength(tests)doprintf(1,"%t ",collapsible(tests[i]))endforputs(1,"\n")
length 0 input: <<<>>>length 0 output: <<<>>>length 72 input: <<<"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln >>>length 70 output: <<<"If I were two-faced, would I be wearing this one?" - Abraham Lincoln >>>length 72 input: <<<..1111111111111111111111111111111111111111111111111111111111111117777888>>>length 4 output: <<<.178>>>length 72 input: <<<I never give 'em hell, I just tell the truth, and they think it's hell. >>>length 69 output: <<<I never give 'em hel, I just tel the truth, and they think it's hel. >>>length 72 input: <<< --- Harry S Truman >>>length 17 output: <<< - Hary S Truman >>>As predicate: false true true true true
<?phpfunctioncollapseString($string){$previousChar=null;$collapse='';$charArray=preg_split('//u',$string,-1,PREG_SPLIT_NO_EMPTY);for($i=0;$i<count($charArray);$i++){$currentChar=$charArray[$i];if($previousChar!==$currentChar){$collapse.=$charArray[$i];}$previousChar=$currentChar;}return$collapse;}functionisCollapsible($string){return($string!==collapseString($string));}$strings=array('','another non colapsing 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 ','0112223333444445555556666666777777778888888889999999999',"The better the 4-wheel drive, the further you'll be from help when ya get stuck!",'headmistressship',"😍😀🙌💃😍😍😍🙌",);foreach($stringsas$original){echo'Original : <<<',$original,'>>> (len=',mb_strlen($original),')',PHP_EOL;if(isCollapsible($original)){$collapse=collapseString($original);echo'Collapse : <<<',$collapse,'>>> (len=',mb_strlen($collapse),')',PHP_EOL,PHP_EOL;}else{echo'Collapse : string is not collapsing...',PHP_EOL,PHP_EOL;}}
Original : <<<>>> (len=0)Collapse : string is not collapsing...Original : <<<another non colapsing string>>> (len=28)Collapse : string is not collapsing...Original : <<<"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln >>> (len=72)Collapse : <<<"If I were two-faced, would I be wearing this one?" - Abraham Lincoln >>> (len=70)Original : <<<..1111111111111111111111111111111111111111111111111111111111111117777888>>> (len=72)Collapse : <<<.178>>> (len=4)Original : <<<I never give 'em hell, I just tell the truth, and they think it's hell. >>> (len=72)Collapse : <<<I never give 'em hel, I just tel the truth, and they think it's hel. >>> (len=69)Original : <<< --- Harry S Truman >>> (len=72)Collapse : <<< - Hary S Truman >>> (len=17)Original : <<<0112223333444445555556666666777777778888888889999999999>>> (len=55)Collapse : <<<0123456789>>> (len=10)Original : <<<The better the 4-wheel drive, the further you'll be from help when ya get stuck!>>> (len=80)Collapse : <<<The beter the 4-whel drive, the further you'l be from help when ya get stuck!>>> (len=77)Original : <<<headmistressship>>> (len=16)Collapse : <<<headmistreship>>> (len=14)Original : <<<😍😀🙌💃😍😍😍🙌>>> (len=8)Collapse : <<<😍😀🙌💃😍🙌>>> (len=6)
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.TheCOLLAPSE procedure compares bytes and would be fine with any 8-bit input.
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;EOF0 <<<>>>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 >>>
localfmt=require"fmt"require"uchar"-- Returns collapsed string, original and new lengths in-- unicode code points (not normalized).localfunctioncollapse(s)localc=uchar.of(s)localle=c:len()ifle<2thenreturns,le,leendfori=le-1,1,-1doifc:get(i)==c:get(i+1)thenc:remove(i)endendreturnc:tostring(),le,c:len()endlocalstrings={"","\"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","😍😀🙌💃😍😍😍🙌"}forstringsassdolocalcc,le,lcc=collapse(s)fmt.print("original : length = %2d, string = «««%s»»»",le,s)fmt.print("collapsed: length = %2d, string = «««%s»»»\n",lcc,cc)end
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 = «««😍😀🙌💃😍🙌»»»
collapse_([],[]).collapse_([A],[A]).collapse_([A,A|T],R):-collapse_([A|T],R).collapse_([A,B|T],[A|R]):-dif(A,B),collapse_([B|T],R).collapse(Str,Collapsed):-string_chars(Str,Chars),collapse_(Chars,Result),string_chars(Collapsed,Result).
?- collapse("122333444455555666666777777788888888999999999", New).New = "123456789" .?- collapse("", New).New = "" .?- collapse("\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", New).New = "\"If I were two-faced, would I be wearing this one?\" - Abraham Lincoln " .?- collapse("..1111111111111111111111111111111111111111111111111111111111111117777888", New).New = ".178" .?- collapse("I never give 'em hell, I just tell the truth, and they think it's hell. ", New).New = "I never give 'em hel, I just tel the truth, and they think it's hel. " .?- collapse(" --- Harry S Truman ", New).New = " - Hary S Truman " .?- collapse("The better the 4-wheel drive, the further you'll be from help when ya get stuck!", New).New = "The beter the 4-whel drive, the further you'l be from help when ya get stuck!" .33 ?- collapse("headmistressship", New).New = "headmistreship" .To determine if a string is collapsed or not, query if the result string is the same as the starting string. eg:
35 ?- S = "122333444455555666666777777788888888999999999", collapse(S,S).false.37 ?- S = "123456789", collapse(S,S).S = "123456789" .
EnableExplicitDataSectionSTR1:Data.s""STR2:Data.s"'If I were two-faced, would I be wearing this one?' --- Abraham Lincoln "STR3:Data.s"..1111111111111111111111111111111111111111111111111111111111111117777888"STR4:Data.s"I never give 'em hell, I just tell the truth, and they think it's hell. "STR5:Data.s" --- Harry S Truman "EndDataSectionProcedure.scollapse(txt$)Define*c.Character=@txt$,last.c=0,result$While*c\cIf*c\c<>lastresult$+Chr(*c\c)last=*c\cEndIf*c+SizeOf(Character)WendProcedureReturnresult$EndProcedureOpenConsole("")Define*p_data=?STR1,buf$While*p_data<=?STR4+StringByteLength(PeekS(?STR4))+2buf$=PeekS(*p_data)PrintN("Before collapse: «««"+buf$+"»»» (length: "+Str(Len(buf$))+")")buf$=collapse(PeekS(*p_data))PrintN("After collapse: «««"+buf$+~"»»» (length: "+Str(Len(buf$))+~")\n")*p_data+StringByteLength(PeekS(*p_data))+2WendInput()
Before collapse: «««»»» (length: 0)After collapse: «««»»» (length: 0)Before collapse: «««'If I were two-faced, would I be wearing this one?' --- Abraham Lincoln »»» (length: 72)After collapse: «««'If I were two-faced, would I be wearing this one?' - Abraham Lincoln »»» (length: 70)Before collapse: «««..1111111111111111111111111111111111111111111111111111111111111117777888»»» (length: 72)After collapse: «««.178»»» (length: 4)Before collapse: «««I never give 'em hell, I just tell the truth, and they think it's hell. »»» (length: 72)After collapse: «««I never give 'em hel, I just tel the truth, and they think it's hel. »»» (length: 69)Before collapse: ««« --- Harry S Truman »»» (length: 72)After collapse: ««« - Hary S Truman »»» (length: 17)
fromitertoolsimportgroupbydefcollapser(txt):return''.join(itemforitem,grpingroupby(txt))if__name__=='__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","😍😀🙌💃😍😍😍🙌",]fortxtinstrings:this="Original"print(f"\n{this:14} Size:{len(txt)} «««{txt}»»»")this="Collapsed"sqz=collapser(txt)print(f"{this:>14} Size:{len(sqz)} «««{sqz}»»»")
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 «««😍😀🙌💃😍🙌»»»
and for the missing predicate, foregrounded in the task title, and already forgotten in the listing of tests:
'''Determining if a string is collapsible'''fromoperatorimporteq# isCollapsible :: String -> BooldefisCollapsible(s):'''True if s contains any consecutively repeated characters. '''returnFalseif2>len(s)else(any(map(eq,s,s[1:])))# ------------------------- TEST --------------------------# main :: IO ()defmain():'''Determining whether each string is collapsible'''xs=["",'"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","😍😀🙌💃😍😍😍🙌","abcdefghijklmnopqrstuvwxyz"]print([isCollapsible(x)forxinxs])# MAIN ---if__name__=='__main__':main()
[False, True, True, True, True, True, True, True, True, False]
[ false -1 rot witheach [ 2dup = iff [ drop dip not conclude ] else nip ] drop ] is collapsible ( $ --> b ) [ [] -1 rot witheach [ 2dup = iff drop else [ nip dup dip join ] ] drop ] is collapse ( $ --> $ ) [ dup collapsible iff [ dup collapse swap 2 ] else [ say "(Not collapsible.)" cr 1 ] times [ say "<<<" dup echo$ say ">>>" cr say " Length: " size echo say " characters" cr cr ] cr ] is 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 " task
(Not collapsible.)<<<>>> Length: 0 characters<<<"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln >>> Length: 72 characters<<<"If I were two-faced, would I be wearing this one?" - Abraham Lincoln >>> Length: 70 characters<<<..1111111111111111111111111111111111111111111111111111111111111117777888>>> Length: 72 characters<<<.178>>> Length: 4 characters<<<I never give 'em hell, I just tell the truth, and they think it's hell. >>> Length: 72 characters<<<I never give 'em hel, I just tel the truth, and they think it's hel. >>> Length: 69 characters<<< --- Harry S Truman >>> Length: 72 characters<<< - Hary S Truman >>> Length: 17 characters
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(iin2:length(str_iterable)){if(length(str_iterable)==0)breakif(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(testintest_strings){collapse_string(test)}
Original String: <<<>>> Length: 0Collapsed string: <<<>>> Length: 0Original String: <<<'If I were two-faced, would I be wearing this one?' --- Abraham Lincoln >>> Length: 72Collapsed string: <<<'If I were two-faced, would I be wearing this one?' - Abraham Lincoln >>> Length: 70Original String: <<<..1111111111111111111111111111111111111111111111111111111111111117777888>>> Length: 72Collapsed string: <<<.178>>> Length: 4Original String: <<<I never give 'em hell, I just tell the truth, and they think it's hell. >>> Length: 72Collapsed string: <<<I never give 'em hel, I just tel the truth, and they think it's hel. >>> Length: 69Original String: <<< --- Harry S Truman >>> Length: 72Collapsed string: <<< - Hary S Truman >>> Length: 17Original String: <<<The better the 4-wheel drive, the further you'll be from help when ya get stuck!>>>Length: 80Collapsed string: <<<The beter the 4-whel drive, the further you'l be from help when ya get stuck!>>> Length: 77Original String: <<<headmistressship>>> Length: 16Collapsed string: <<<headmistreship>>> Length: 14Original String: <<<aardvark>>> Length: 8Collapsed string: <<<ardvark>>> Length: 7Original String: <<<Ciao Mamma, guarda come mi diverto!!>>> Length: 36Collapsed string: <<<Ciao Mama, guarda come mi diverto!>>> Length: 34
#langracket(define(collapsetext)(if(<(string-lengthtext)2)text(string-append(if(equal?(substringtext01)(substringtext12))""(substringtext01))(collapse(substringtext1))))); Test cases(definetcs'("""\"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([texttcs])(let([collapsed(collapsetext)])(display(format"Original (size ~a): «««~a»»»\nCollapsed (size ~a): «««~a»»»\n\n"(string-lengthtext)text(string-lengthcollapsed)collapsed))))
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): «««😍😀🙌💃😍🙌»»»
(formerly Perl 6)
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.
map {my$squish = .comb.squish.join;printf"\nLength: %2d <<<%s>>>\nCollapsible: %s\nLength: %2d <<<%s>>>\n", .chars,$_, .chars !=$squish.chars,$squish.chars,$squish},linesq:to/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 American people have a right to know if their president is a crook. --- Richard Nixon AАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA STRINGS
Length: 0 <<<>>>Collapsible: FalseLength: 0 <<<>>>Length: 72 <<<"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln >>>Collapsible: TrueLength: 70 <<<"If I were two-faced, would I be wearing this one?" - Abraham Lincoln >>>Length: 72 <<<..1111111111111111111111111111111111111111111111111111111111111117777888>>>Collapsible: TrueLength: 4 <<<.178>>>Length: 72 <<<I never give 'em hell, I just tell the truth, and they think it's hell. >>>Collapsible: TrueLength: 69 <<<I never give 'em hel, I just tel the truth, and they think it's hel. >>>Length: 72 <<< --- Harry S Truman >>>Collapsible: TrueLength: 17 <<< - Hary S Truman >>>Length: 72 <<<The American people have a right to know if their president is a crook. >>>Collapsible: TrueLength: 71 <<<The American people have a right to know if their president is a crok. >>>Length: 72 <<< --- Richard Nixon >>>Collapsible: TrueLength: 17 <<< - Richard Nixon >>>Length: 72 <<<AАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑ>>>Collapsible: FalseLength: 72 <<<AАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑ>>>Length: 72 <<<AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA>>>Collapsible: TrueLength: 1 <<<A>>>
$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>;};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 >>>
/*REXX program "collapses" all immediately repeated characters in a string (or strings).*/@.=/*define a default for the @. array. */parseargx/*obtain optional argument from the CL.*/ifx\=''then@.1=x/*if user specified an arg, use that. */elsedo;@.1=@.2='"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln '@.3=..1111111111111111111111111111111111111111111111111111111111111117777888@.4="I never give 'em hell, I just tell the truth, and they think it's hell. "@.5=' --- Harry S Truman 'enddoj=1;L=length(@.j)/*obtain the length of an array element*/saycopies('═',105)/*show a separator line between outputs*/ifj>1&L==0thenleave/*if arg is null and J>1, then leave. */new=collapse(@.j)say'string'word("isn't is",1+collapsible)'collapsible'/*display semaphore value*/say' length='right(L,3)" input=«««"||@.j||'»»»'w=length(new)say' length='right(w,3)" output=«««"||new||'»»»'end/*j*/exit/*stick a fork in it, we're all done. *//*──────────────────────────────────────────────────────────────────────────────────────*/collapse:procedureexposecollapsible;parseargy1$2/*get the arg; get 1st char. */dok=2tolength(y)/*traipse through almost all the chars.*/_=substr(y,k,1)/*pick a character from Y (1st arg). */if_==right($,1)theniterate/*Is this the same character? Skip it.*/$=$||_/*append the character, it's different.*/end/*j*/collapsible=y\==$;return$/*set boolean to true if collapsible.*/
═════════════════════════════════════════════════════════════════════════════════════════════════════════string isn't collapsible length= 0 input=«««»»» length= 0 output=«««»»»═════════════════════════════════════════════════════════════════════════════════════════════════════════string is collapsible length= 72 input=«««"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln »»» length= 70 output=«««"If I were two-faced, would I be wearing this one?" - Abraham Lincoln »»»═════════════════════════════════════════════════════════════════════════════════════════════════════════string is collapsible length= 72 input=«««..1111111111111111111111111111111111111111111111111111111111111117777888»»» length= 4 output=«««.178»»»═════════════════════════════════════════════════════════════════════════════════════════════════════════string is collapsible length= 72 input=«««I never give 'em hell, I just tell the truth, and they think it's hell. »»» length= 69 output=«««I never give 'em hel, I just tel the truth, and they think it's hel. »»»═════════════════════════════════════════════════════════════════════════════════════════════════════════string is collapsible length= 72 input=««« --- Harry S Truman »»» length= 17 output=««« - Hary S Truman »»»═════════════════════════════════════════════════════════════════════════════════════════════════════════
load "stdlib.ring"see "working..." + nl + nlstr = ["The better the 4-wheel drive, the further you'll be from help when ya get stuck!", "I never give 'em hell, I just tell the truth, and they think it's hell.", "..1111111111111111111111111111111111111111111111111111111111111117777888"]strsave = strfor n = 1 to len(str) for m = 1 to len(str[n])-1 if substr(str[n],m,1) = substr(str[n],m+1,1) str[n] = left(str[n],m) + right(str[n],len(str[n])-m-1) for p = len(str[n]) to 2 step -1 if substr(str[n],p,1) = substr(str[n],p-1,1) str[n] = left(str[n],p-1) + right(str[n],len(str[n])-p) ok next ok nextnextfor n = 1 to len(str) see "" + len(strsave[n]) + "«««" + strsave[n] + "»»»" + nl see "" + len(str[n]) + "«««" + str[n] + "»»»" + nl + nlnextsee "done..." + nl
Output:
working...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!»»»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.»»»72«««..1111111111111111111111111111111111111111111111111111111111111117777888»»»4«««.178»»»done...
| RPL code | Comment |
|---|---|
≪ → string ≪ "" DUP 1 string SIZEFOR j string j DUP SUBIF DUP2 ≠THEN ROT OVER + SWAP ROTEND DROPNEXT DROP≫ ≫ ‘CLAPS’ STO | CLAPS( "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 |
« → string « { "" } string SIZE 1FOR j string j DUP SUB SWAPIF DUP2 HEAD ==THEN NIPELSE +END -1STEP ∑LIST » » ‘CLAPS’ STOWhen 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 5FOR j DUP j GETCLAPS SWAPNEXT DROP≫ EVAL5: ""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 "
This is built in since at least a decade under the method name 'squeeze'. squeeze(" ") would only squeeze spaces.
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","😍😀🙌💃😍😍😍🙌",]strings.eachdo|str|puts"«««#{str}»»» (size#{str.size})"ssq=str.squeezeputs"«««#{ssq}»»» (size#{ssq.size})"putsend
«««»»» (size 0)«««»»» (size 0)«««"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln »»» (size 72)«««"If I were two-faced, would I be wearing this one?" - Abraham Lincoln »»» (size 70)«««..1111111111111111111111111111111111111111111111111111111111111117777888»»» (size 72)«««.178»»» (size 4)«««I never give 'em hell, I just tell the truth, and they think it's hell. »»» (size 72)«««I never give 'em hel, I just tel the truth, and they think it's hel. »»» (size 69)««« --- Harry S Truman »»» (size 72)««« - Hary S Truman »»» (size 17)«««The better the 4-wheel drive, the further you'll be from help when ya get stuck!»»» (size 80)«««The beter the 4-whel drive, the further you'l be from help when ya get stuck!»»» (size 77)«««headmistressship»»» (size 16)«««headmistreship»»» (size 14)«««aardvark»»» (size 8)«««ardvark»»» (size 7)«««😍😀🙌💃😍😍😍🙌»»» (size 8)«««😍😀🙌💃😍🙌»»» (size 6)
fncollapse_string(val:&str)->String{letmutoutput=String::new();letmutchars=val.chars().peekable();whileletSome(c)=chars.next(){whileletSome(&b)=chars.peek(){ifb==c{chars.next();}else{break;}}output.push(c);}output}fnmain(){lettests=["122333444455555666666777777788888888999999999","","\"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",];forsin&tests{println!("Old: {:>3} <<<{}>>>",s.len(),s);letcollapsed=collapse_string(s);println!("New: {:>3} <<<{}>>>",collapsed.len(),collapsed);println!();}}
Old: 45 <<<122333444455555666666777777788888888999999999>>>New: 9 <<<123456789>>>Old: 0 <<<>>>New: 0 <<<>>>Old: 72 <<<"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln >>>New: 70 <<<"If I were two-faced, would I be wearing this one?" - Abraham Lincoln >>>Old: 72 <<<..1111111111111111111111111111111111111111111111111111111111111117777888>>>New: 4 <<<.178>>>Old: 72 <<<I never give 'em hell, I just tell the truth, and they think it's hell. >>>New: 69 <<<I never give 'em hel, I just tel the truth, and they think it's hel. >>>Old: 72 <<< --- Harry S Truman >>>New: 17 <<< - Hary S Truman >>>Old: 80 <<<The better the 4-wheel drive, the further you'll be from help when ya get stuck!>>>New: 77 <<<The beter the 4-whel drive, the further you'l be from help when ya get stuck!>>>Old: 16 <<<headmistressship>>>New: 14 <<<headmistreship>>>
objectCollapsibleString{/**Collapse a string (if possible)*/defcollapseString(s:String):String={varres=svarisOver=falsevari=0if(res.size==0)reselsewhile(!isOver){if(res(i)==res(i+1)){res=res.take(i)++res.drop(i+1)i-=1}i+=1if(i==res.size-1)isOver=true}res}/**Check if a string is collapsible*/defisCollapsible(s:String):Boolean=collapseString(s).length!=s.length/**Display results as asked in the task*/defreportResults(s:String):String={valsCollapsed=collapseString(s)valoriginalRes="ORIGINAL : length = "+s.length()+", string = «««"+s+"»»»"valcollapsedRes="COLLAPSED : length = "+sCollapsed.length()+", string = «««"+sCollapsed+"»»»"//In order to avoid useless computations, the function isCollapsible isn't calledif(s.length!=sCollapsed.length)originalRes+"\n"+collapsedRes+"\n"+"This string IS collapsible !"elseoriginalRes+"\n"+collapsedRes+"\n"+"This string is NOT collapsible !"}defmain(args:Array[String]):Unit={println(reportResults(""))println("------------")println(reportResults("\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln "))println("------------")println(reportResults("..1111111111111111111111111111111111111111111111111111111111111117777888"))println("------------")println(reportResults("I never give 'em hell, I just tell the truth, and they think it's hell. "))println("------------")println(reportResults(" --- Harry S Truman "))println("------------")println(reportResults("The better the 4-wheel drive, the further you'll be from help when ya get stuck!"))println("------------")println(reportResults("headmistressship"))println("------------")println(reportResults("aardvark"))}}
ORIGINAL : length = 0, string = «««»»»COLLAPSED : length = 0, string = «««»»»This string is NOT collapsible !------------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 »»»This string IS collapsible !------------ORIGINAL : length = 72, string = «««..1111111111111111111111111111111111111111111111111111111111111117777888»»»COLLAPSED : length = 4, string = «««.178»»»This string IS collapsible !------------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. »»»This string IS collapsible !------------ORIGINAL : length = 72, string = ««« --- Harry S Truman »»»COLLAPSED : length = 17, string = ««« - Hary S Truman »»»This string IS collapsible !------------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!»»»This string IS collapsible !------------ORIGINAL : length = 16, string = «««headmistressship»»»COLLAPSED : length = 14, string = «««headmistreship»»»This string IS collapsible !------------ORIGINAL : length = 8, string = «««aardvark»»»COLLAPSED : length = 7, string = «««ardvark»»»This string IS collapsible !
Since sed has no native support for arithmetic, line length counting is omitted in this solution for simplicity:
hs/.*/<<<&>>>/xs/\(.\)\1*/\1/gs/.*/<<<&>>>/Hs/.*//G
Test:
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
<<<>>><<<>>><<<"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 >>>
funcsqueeze(str){str.gsub(/(.)\1+/,{|s1|s1})}varstrings=["",'"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","😍😀🙌💃😍😍😍🙌"]strings.each{|str|varssq=squeeze(str)say"«««#{str}»»» (length:#{str.len})"say"«««#{ssq}»»» (length:#{ssq.len})\n"}
«««»»» (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)«««The better the 4-wheel drive, the further you'll be from help when ya get stuck!»»» (length: 80)«««The beter the 4-whel drive, the further you'l be from help when ya get stuck!»»» (length: 77)«««headmistressship»»» (length: 16)«««headmistreship»»» (length: 14)«««aardvark»»» (length: 8)«««ardvark»»» (length: 7)«««😍😀🙌💃😍😍😍🙌»»» (length: 8)«««😍😀🙌💃😍🙌»»» (length: 6)
#('The better the 4-wheel drive, the further you''ll be from help when ya get stuck!''headmistressship''aardvark''😍😀🙌💃😍😍😍🙌')do:[:eachWord||shortened|shortened:=StringstreamContents:[:out|eachWordinject:nilinto:[:prev:this|prev~=thisifTrue:[outnextPut:this].this ] ].TranscriptshowCR:(eachWord,'(length:',eachWordsize,')' );showCR:(shortened,'(length:',shortenedsize,')' ). ]
The better the 4-wheel drive, the further you'll be from help when ya get stuck!(length:80)The beter the 4-whel drive, the further you'l be from help when ya get stuck!(length:77)headmistressship(length:16)headmistreship(length:14)aardvark(length:8)ardvark(length:7)😍😀🙌💃😍😍😍🙌(length:8)😍😀🙌💃😍🙌(length:6)
letstrings=["",#""IfIweretwo-faced,wouldIbewearingthisone?" --- 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","😍😀🙌💃😍😍😍🙌"]letcollapsedStrings=strings.map{$0.replacingOccurrences(of:#"(.)\1*"#,with:"$1",options:.regularExpression)}for(original,collapsed)inzip(strings,collapsedStrings){print(String(format:"%03d «%@»\n%03d «%@»\n",original.count,original,collapsed.count,collapsed))}
000 «»000 «»072 «"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln »070 «"If I were two-faced, would I be wearing this one?" - Abraham Lincoln »072 «..1111111111111111111111111111111111111111111111111111111111111117777888»004 «.178»072 «I never give 'em hell, I just tell the truth, and they think it's hell. »069 «I never give 'em hel, I just tel the truth, and they think it's hel. »072 « --- Harry S Truman »017 « - Hary S Truman »080 «The better the 4-wheel drive, the further you'll be from help when ya get stuck!»077 «The beter the 4-whel drive, the further you'l be from help when ya get stuck!»016 «headmistressship»014 «headmistreship»008 «aardvark»007 «ardvark»008 «😍😀🙌💃😍😍😍🙌»006 «😍😀🙌💃😍🙌»
Please note the ;# ' comments, there appears to be a syntax hightlighting bug with RC
settest{{}{"If I were two-faced, would I be wearing this one?"---AbrahamLincoln}{..1111111111111111111111111111111111111111111111111111111111111117777888}{Inevergive'emhell,Ijusttellthetruth,andtheythinkit'shell.};# '{---HarrySTruman}{Thebetterthe4-wheeldrive,thefurtheryou'llbefromhelpwhenyagetstuck!};# '{headmistressship}}foreach{str}$test{# Uses regexp lookbehind to detect repeated characterssetsub[regsub-all{(.)(\1+)}$str{\1}]# Outputputs[format"Original (length %3d): %s"[stringlength$str]$str]puts[format"Subbed (length %3d): %s"[stringlength$sub]$sub]puts----------------------}
Original (length 0):Subbed (length 0):----------------------Original (length 72): "If I were two-faced, would I be wearing this one?" --- Abraham LincolnSubbed (length 70): "If I were two-faced, would I be wearing this one?" - Abraham Lincoln----------------------Original (length 72): ..1111111111111111111111111111111111111111111111111111111111111117777888Subbed (length 4): .178----------------------Original (length 72): I never give 'em hell, I just tell the truth, and they think it's hell.Subbed (length 69): I never give 'em hel, I just tel the truth, and they think it's hel.----------------------Original (length 72): --- Harry S TrumanSubbed (length 17): - Hary S Truman----------------------Original (length 80): The better the 4-wheel drive, the further you'll be from help when ya get stuck!Subbed (length 77): The beter the 4-whel drive, the further you'l be from help when ya get stuck!----------------------Original (length 16): headmistressshipSubbed (length 14): headmistreship----------------------
S ← {"" "\"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" "😍😀🙌💃😍😍😍🙌" "unnecessary bookkeeping"}Collapse ← ⊜⊢+1⊛.≡(&p""≡(&p$"_ chars \t«_»" ⊸⧻°□))≡(⊟⟜⍜°□Collapse)S0 chars «»0 chars «»71 chars «"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln»69 chars «"If I were two-faced, would I be wearing this one?" - Abraham Lincoln»72 chars «..1111111111111111111111111111111111111111111111111111111111111117777888»4 chars «.178»72 chars «I never give 'em hell, I just tell the truth, and they think it's hell. »69 chars «I never give 'em hel, I just tel the truth, and they think it's hel. »72 chars « --- Harry S Truman »17 chars « - Hary S Truman »80 chars «The better the 4-wheel drive, the further you'll be from help when ya get stuck!»77 chars «The beter the 4-whel drive, the further you'l be from help when ya get stuck!»16 chars «headmistressship»14 chars «headmistreship»8 chars «aardvark»7 chars «ardvark»8 chars «😍😀🙌💃😍😍😍🙌»6 chars «😍😀🙌💃😍🙌»23 chars «unnecessary bookkeeping»18 chars «unecesary bokeping»
ModuleModule1FunctionCollapse(sAsString)AsStringIfString.IsNullOrEmpty(s)ThenReturn""EndIfReturns(0)+NewString(Enumerable.Range(1,s.Length-1).Where(Function(i)s(i)<>s(i-1)).Select(Function(i)s(i)).ToArray)EndFunctionSubMain()Diminput()={"","The better the 4-wheel drive, the further you'll be from help when ya get stuck!","headmistressship",ControlChars.Quote+"If I were two-faced, would I be wearing this one?"+ControlChars.Quote+" --- Abraham Lincoln ","..1111111111111111111111111111111111111111111111111111111111111117777888","I never give 'em hell, I just tell the truth, and they think it's hell. "," --- Harry S Truman "}ForEachsIninputConsole.WriteLine($"old: {s.Length} «««{s}»»»")Dimc=Collapse(s)Console.WriteLine($"new: {c.Length} «««{c}»»»")NextEndSubEndModule
old: 0 «««»»»new: 0 «««»»»old: 80 «««The better the 4-wheel drive, the further you'll be from help when ya get stuck!»»»new: 77 «««The beter the 4-whel drive, the further you'l be from help when ya get stuck!»»»old: 16 «««headmistressship»»»new: 14 «««headmistreship»»»old: 72 «««"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln »»»new: 70 «««"If I were two-faced, would I be wearing this one?" - Abraham Lincoln »»»old: 72 «««..1111111111111111111111111111111111111111111111111111111111111117777888»»»new: 4 «««.178»»»old: 72 «««I never give 'em hell, I just tell the truth, and they think it's hell. »»»new: 69 «««I never give 'em hel, I just tel the truth, and they think it's hel. »»»old: 72 ««« --- Harry S Truman »»»new: 17 ««« - Hary S Truman »»»
Function :
FunctionCollapse(strInAsString)AsStringDimiAsLong,strOutAsStringIfLen(strIn)>0ThenstrOut=Mid$(strIn,1,1)Fori=2ToLen(strIn)IfMid$(strIn,i,1)<>Mid$(strIn,i-1,1)ThenstrOut=strOut&Mid$(strIn,i,1)EndIfNextiEndIfCollapse=strOutEndFunction
To Call :
SubCallCollapse()DimSAsStringS=vbNullStringDebug.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))EndSub
String : <<<>>> Lenght : 0Collapsed : <<<>>> Lenght : 0String : <<<"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln >>> Lenght : 72Collapsed : <<<"If I were two-faced, would I be wearing this one?" - Abraham Lincoln >>> Lenght : 70String : <<<..1111111111111111111111111111111111111111111111111111111111111117777888>>> Lenght : 72Collapsed : <<<.178>>> Lenght : 4String : <<<I never give 'em hell, I just tell the truth, and they think it's hell. >>> Lenght : 72Collapsed : <<<I never give 'em hel, I just tel the truth, and they think it's hel. >>> Lenght : 69String : <<< --- Harry S Truman >>> Lenght : 72Collapsed : <<< - Hary S Truman >>> Lenght : 17
// 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") }}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 = «««😍😀🙌💃😍🙌»»»
import"./fmt"forFmt// Returns collapsed string, original and new lengths in// unicode code points (not normalized).varcollapse=Fn.new{|s|varc=s.codePoints.toListvarle=c.countif(le<2)return[s,le,le]for(iinle-2..0){if(c[i]==c[i+1])c.removeAt(i)}varcc=c.reduce(""){|acc,cp|acc+String.fromCodePoint(cp)}return[cc,le,cc.count]}varstrings=["","\"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(sinstrings){varr=collapse.call(s)System.print("original : length =%(Fmt.d(2,r[1])), string = «««%(s)»»»")System.print("collapsed: length =%(Fmt.d(2,r[2])), string = «««%(r[0])»»»\n")}
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 = «««😍😀🙌💃😍🙌»»»
string 0;char C, I, J, Last;proc Collapse(S); \Eliminate immediately repeated characters from stringchar 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 stringfor 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); ];]
<<<>>> 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
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);}strings:=0'^"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ..1111111111111111111111111111111111111111111111111111111111111117777888I never give 'em hell, I just tell the truth, and they think it's hell. --- Harry S Truman The American people have a right to know if their president is a crook. --- Richard Nixon The better the 4-wheel drive, the further you'll be from help when ya get stuck!headmistressshipaardvark^.split("\n");#<<<foreach s in (strings){ println("Before: %3d >>>%s<<<".fmt(s.len(),s)); _,cstr:=collapsible(s); println("After: %3d >>>%s<<<\n".fmt(cstr.len(),cstr));}Before: 0 >>><<<After: 0 >>><<<Before: 72 >>>"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln <<<After: 70 >>>"If I were two-faced, would I be wearing this one?" - Abraham Lincoln <<<Before: 72 >>>..1111111111111111111111111111111111111111111111111111111111111117777888<<<After: 4 >>>.178<<<Before: 72 >>>I never give 'em hell, I just tell the truth, and they think it's hell. <<<After: 69 >>>I never give 'em hel, I just tel the truth, and they think it's hel. <<<Before: 72 >>> --- Harry S Truman <<<After: 17 >>> - Hary S Truman <<<Before: 72 >>>The American people have a right to know if their president is a crook. <<<After: 71 >>>The American people have a right to know if their president is a crok. <<<Before: 72 >>> --- Richard Nixon <<<After: 17 >>> - Richard Nixon <<<Before: 80 >>>The better the 4-wheel drive, the further you'll be from help when ya get stuck!<<<After: 77 >>>The beter the 4-whel drive, the further you'l be from help when ya get stuck!<<<Before: 16 >>>headmistressship<<<After: 14 >>>headmistreship<<<Before: 8 >>>aardvark<<<After: 7 >>>ardvark<<<