Data commit
This commit is contained in:
parent
7387c8f97b
commit
cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions
2
Task/Determine-if-a-string-is-squeezable/00-META.yaml
Normal file
2
Task/Determine-if-a-string-is-squeezable/00-META.yaml
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
---
|
||||
from: http://rosettacode.org/wiki/Determine_if_a_string_is_squeezable
|
||||
97
Task/Determine-if-a-string-is-squeezable/00-TASK.txt
Normal file
97
Task/Determine-if-a-string-is-squeezable/00-TASK.txt
Normal file
|
|
@ -0,0 +1,97 @@
|
|||
Determine if a character string is ''squeezable''.
|
||||
|
||||
And if so, squeeze the string (by removing any number of
|
||||
a ''specified'' ''immediately repeated'' character).
|
||||
|
||||
|
||||
This task is very similar to the task '''Determine if a character string is collapsible''' except
|
||||
that only a specified character is ''squeezed'' instead of any character that is ''immediately repeated''.
|
||||
|
||||
|
||||
If a character string has a specified ''immediately repeated'' character(s), the repeated characters are to be
|
||||
deleted (removed), but not the primary (1<sup>st</sup>) character(s).
|
||||
|
||||
|
||||
A specified ''immediately repeated'' character is any specified character that is <u>immediately</u>
|
||||
followed by an identical character (or characters). Another word choice could've been ''duplicated
|
||||
character'', but that might 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: '''squeeze'''.}
|
||||
|
||||
|
||||
;Examples:
|
||||
In the following character string with a specified ''immediately repeated'' character of '''e''':
|
||||
|
||||
|
||||
<big><big> The better the 4-whe<u>e</u>l drive, the further you'll be from help when ya get stuck! </big></big>
|
||||
|
||||
|
||||
Only the 2<sup>nd</sup> '''e''' is an specified repeated character, indicated by an underscore
|
||||
(above), even though they (the characters) appear elsewhere in the character string.
|
||||
|
||||
|
||||
|
||||
So, after ''squeezing'' the string, the result would be:
|
||||
|
||||
<big><big> The better the 4-whel drive, the further you'll be from help when ya get stuck! </big></big>
|
||||
|
||||
|
||||
|
||||
|
||||
Another example:
|
||||
In the following character string, using a specified immediately repeated character '''s''':
|
||||
|
||||
<big><big> headmistres<u>ss</u>hip </big></big>
|
||||
|
||||
|
||||
The "squeezed" string would be:
|
||||
|
||||
<big><big> headmistreship </big></big>
|
||||
|
||||
|
||||
|
||||
;Task:
|
||||
Write a subroutine/function/procedure/routine··· to locate a ''specified immediately repeated'' character
|
||||
and ''squeeze'' (delete) them from the character string. The
|
||||
character string can be processed from either direction.
|
||||
|
||||
|
||||
Show all output here, on this page:
|
||||
:* the specified repeated character (to be searched for and possibly ''squeezed''):
|
||||
:* the original string and its length
|
||||
:* the resultant string and its length
|
||||
:* the above strings should be "bracketed" with '''<<<''' and '''>>>''' (to delineate blanks)
|
||||
;* «««Guillemets may be used instead for "bracketing" for the more artistic programmers, shown used here»»»
|
||||
<!-- Guillemots shouldn't be used as they stink. !-->
|
||||
|
||||
|
||||
Use (at least) the following five strings, all strings are length seventy-two (characters, including blanks), except
|
||||
the 1<sup>st</sup> string:
|
||||
|
||||
immediately
|
||||
string repeated
|
||||
number character
|
||||
( ↓ a blank, a minus, a seven, a period)
|
||||
╔╗
|
||||
1 ║╚═══════════════════════════════════════════════════════════════════════╗ ' ' ◄■■■■■■ a null string (length zero)
|
||||
2 ║"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ║ '-'
|
||||
3 ║..1111111111111111111111111111111111111111111111111111111111111117777888║ '7'
|
||||
4 ║I never give 'em hell, I just tell the truth, and they think it's hell. ║ '.'
|
||||
5 ║ --- Harry S Truman ║ (below) ◄■■■■■■ has many repeated blanks
|
||||
╚════════════════════════════════════════════════════════════════════════╝ ↑
|
||||
│
|
||||
│
|
||||
For the 5<sup>th</sup> string (Truman's signature line), use each of these specified immediately repeated characters:
|
||||
• a blank
|
||||
• a minus
|
||||
• a lowercase '''r'''
|
||||
|
||||
|
||||
Note: there should be seven results shown, one each for the 1<sup>st</sup> four strings, and three results for
|
||||
the 5<sup>th</sup> string.
|
||||
|
||||
{{Template:Strings}}
|
||||
<br><br>
|
||||
|
||||
|
|
@ -0,0 +1,34 @@
|
|||
F squeeze(input, include)
|
||||
V s = ‘’
|
||||
L(i) 0 .< input.len
|
||||
I i == 0 | input[i - 1] != input[i] | (input[i - 1] == input[i] & input[i] != include)
|
||||
s ‘’= input[i]
|
||||
R s
|
||||
|
||||
V testStrings = [
|
||||
‘’,
|
||||
‘"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’
|
||||
]
|
||||
|
||||
V testChar = [
|
||||
‘ ’,
|
||||
‘-’,
|
||||
‘7’,
|
||||
‘.’,
|
||||
‘ -r’,
|
||||
‘5’,
|
||||
‘e’,
|
||||
‘s’
|
||||
]
|
||||
|
||||
L(testNum) 0 .< testStrings.len
|
||||
V s = testStrings[testNum]
|
||||
L(c) testChar[testNum]
|
||||
V result = squeeze(s, c)
|
||||
print("use: '#.'\nold: #2 <<<#.>>>\nnew: #2 <<<#.>>>\n".format(c, s.len, s, result.len, result))
|
||||
|
|
@ -0,0 +1,116 @@
|
|||
puts: equ 9
|
||||
org 100h
|
||||
jmp demo
|
||||
;;; Squeeze the string at DE on the character in C.
|
||||
;;; The result is written starting at HL.
|
||||
squeez: mvi b,'$' ; Last character seen
|
||||
dcx d ; Move pointer back one item
|
||||
sqzlp: mvi m,'$' ; Stop on end of string
|
||||
inx d ; Increment input pointer
|
||||
ldax d ; Grab character from input string
|
||||
cmp m ; End reached?
|
||||
rz ; Then stop
|
||||
cmp c ; Was it equal to the character to squeeze?
|
||||
jnz sqzwr ; If not, then write it to the output
|
||||
mov a,b ; If so, is the previous character?
|
||||
cmp c
|
||||
jz sqzlp ; If so, ignore this one
|
||||
sqzwr: ldax d ; Retrieve the character again
|
||||
mov m,a ; It goes in the output
|
||||
mov b,a ; And it is the last character seen
|
||||
inx h ; Increment output pointer
|
||||
jmp sqzlp
|
||||
;;; Print the string in DE and character in C as specified,
|
||||
;;; squeeze the string and print the output.
|
||||
prsqz: push b ; Save input parameters
|
||||
push d
|
||||
mov a,c ; Store character
|
||||
sta chval
|
||||
lxi d,chstr ; Print character
|
||||
mvi c,puts
|
||||
call 5
|
||||
pop h ; Retrieve input string pointer
|
||||
push h
|
||||
call prbrkt ; Print the string in brackets
|
||||
pop d ; Retrieve both input parameters
|
||||
pop b
|
||||
lxi h,buffer
|
||||
call squeez ; Squeeze the input string
|
||||
lxi h,buffer ; ... fall through to print the result
|
||||
;;; Write the string at HL and its length in brackets
|
||||
prbrkt: push h ; Keep the pointer
|
||||
mvi b,0FFh ; Find the length
|
||||
mvi a,'$' ; End marker
|
||||
dcx h
|
||||
lscan: inr b ; Scan through the string incrementing B
|
||||
inx h ; and HL until the end is found
|
||||
cmp m
|
||||
jnz lscan
|
||||
mov a,b ; Find high and low digit (assuming < 100)
|
||||
mvi b,'0'-1
|
||||
pdigit: inr b ; B = high digit
|
||||
sui 10
|
||||
jnc pdigit
|
||||
lxi h,bstart+1
|
||||
adi '0'+10
|
||||
mov m,a ; Write low digit
|
||||
dcx h
|
||||
mov m,b ; Write high digit
|
||||
xchg
|
||||
mvi c,puts ; Print length and brackets
|
||||
call 5
|
||||
pop d ; Retrieve the string pointer
|
||||
mvi c,puts ; Print the string
|
||||
call 5
|
||||
lxi d,bend ; Print the ending brackets
|
||||
mvi c,puts
|
||||
jmp 5
|
||||
;;; Squeeze each string by the given character
|
||||
demo: lxi h,list ; Pointer to start of list
|
||||
loop: mov e,m ; Load pointer and character
|
||||
inx h
|
||||
mov d,m
|
||||
inx h
|
||||
mov c,m
|
||||
inx h
|
||||
xra a ; Stop when zero reached
|
||||
ora c
|
||||
rz
|
||||
push h ; Keep list pointer
|
||||
call prsqz ; Squeeze and print
|
||||
pop h ; Restore list pointer
|
||||
jmp loop
|
||||
;;; Formatting strings
|
||||
chstr: db 'Character: "'
|
||||
chval: db '*"',13,10,'$'
|
||||
bstart: db '##<<<$'
|
||||
bend: db '>>>'
|
||||
nl: db 13,10,'$'
|
||||
;;; Input strings
|
||||
str1: db '$'
|
||||
str2: db '"If I were two-faced, would I be wearing'
|
||||
db ' this one?" --- Abraham Lincoln $'
|
||||
str3: db '..11111111111111111111111111111111111111'
|
||||
db '11111111111111111111111117777888$'
|
||||
str4: db 'I never give ',39,'em hell, I just tell the t'
|
||||
db 'ruth, and they think it',39,'s hell. $'
|
||||
str5: db ' '
|
||||
db ' --- Harry S Truman $'
|
||||
;;; Pairs of string pointers and characters to squeeze
|
||||
list: dw str1
|
||||
db ' '
|
||||
dw str2
|
||||
db '-'
|
||||
dw str3
|
||||
db '7'
|
||||
dw str4
|
||||
db '.'
|
||||
dw str5
|
||||
db ' '
|
||||
dw str5
|
||||
db '-'
|
||||
dw str5
|
||||
db 'r'
|
||||
dw 0
|
||||
db 0
|
||||
buffer: equ $
|
||||
|
|
@ -0,0 +1,38 @@
|
|||
BEGIN
|
||||
# returns a squeezed version of s #
|
||||
# i.e. s with adjacent duplicate c characters removed #
|
||||
PRIO SQUEEZE = 9;
|
||||
OP SQUEEZE = ( STRING s, CHAR c )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 ]
|
||||
OR result[ r pos ] /= c
|
||||
THEN
|
||||
r pos +:= 1;
|
||||
result[ r pos ] := s[ s pos ]
|
||||
FI
|
||||
OD;
|
||||
result[ LWB result : r pos ]
|
||||
FI # SQUEEZE # ;
|
||||
# test the SQUEEZE operator #
|
||||
PROC test squeeze = ( STRING s, CHAR c )VOID:
|
||||
BEGIN
|
||||
STRING z = s SQUEEZE c;
|
||||
print( ( "Squeezing """, c, """ in ", "<<<", s, ">>> (length ", whole( ( UPB s + 1 ) - LWB s, 0 ), ")", newline ) );
|
||||
print( ( " -> ", "<<<", z, ">>> (length ", whole( ( UPB z + 1 ) - LWB z, 0 ), ")", newline ) )
|
||||
END # test squeeze # ;
|
||||
# task test cases #
|
||||
test squeeze( "", " " );
|
||||
test squeeze( """If I were two-faced, would I be wearing this one?"" --- Abraham Lincoln ", "-" );
|
||||
test squeeze( "..1111111111111111111111111111111111111111111111111111111111111117777888", "7" );
|
||||
test squeeze( "I never give 'em hell, I just tell the truth, and they think it's hell. ", "." );
|
||||
STRING hst = " --- Harry S Truman ";
|
||||
test squeeze( hst, " " );
|
||||
test squeeze( hst, "-" );
|
||||
test squeeze( hst, "r" )
|
||||
END
|
||||
|
|
@ -0,0 +1,32 @@
|
|||
task←{
|
||||
⍝ Squeeze a string
|
||||
squeeze ← ⊢(/⍨)≠∨1,1↓⊣≠¯1⌽⊢
|
||||
|
||||
⍝ Display string and length in the manner given in the task
|
||||
display ← {(¯2↑⍕≢⍵),' «««',⍵,'»»»'}
|
||||
|
||||
⍝ Squeeze string and display output
|
||||
show ← {
|
||||
r← ⊂'chr: ''',⍺,''''
|
||||
r←r,⊂' in: ',display ⍵
|
||||
r←r,⊂'out: ',display ⍺ squeeze ⍵
|
||||
↑r,⊂''
|
||||
}
|
||||
|
||||
⍝ Strings from the task
|
||||
s1←''
|
||||
s2←'"If I were two-faced, would I be wearing this one?"'
|
||||
s2←s2,' --- Abraham Lincoln '
|
||||
s3←'..1111111111111111111111111111111111111111111111111'
|
||||
s3←s3,'111111111111117777888'
|
||||
s4←'I never give ''em hell, I just tell the truth, and t'
|
||||
s4←s4,'hey think it''s hell. '
|
||||
s5←' '
|
||||
s5←s5,' --- Harry S Truman '
|
||||
|
||||
⎕←' ' show s1
|
||||
⎕←'-' show s2
|
||||
⎕←'7' show s3
|
||||
⎕←'.' show s4
|
||||
{⎕←⍵ show s5}¨' -r' ⍝⍝ note use of 'show' here in a lambda (dfn)
|
||||
}
|
||||
|
|
@ -0,0 +1,36 @@
|
|||
#!/usr/local/bin/apl --script
|
||||
|
||||
∇r ← c squeeze s
|
||||
s ← 0,s,0
|
||||
r ← 1↓¯2↓∊((s≠c)⊂s),¨c
|
||||
∇
|
||||
|
||||
∇r ← display s
|
||||
r ← (¯2↑⍕≢s),' «««',s,'»»»'
|
||||
∇
|
||||
|
||||
∇r ← c show s
|
||||
r ← ⊂ ("chr: '",c,"'")
|
||||
r ← r, ⊂(" in: ",display s)
|
||||
r ← r, ⊂ ("out: ",display c squeeze s)
|
||||
r ← ⊃r
|
||||
∇
|
||||
|
||||
∇main
|
||||
s1←''
|
||||
s2←'"If I were two-faced, would I be wearing this one?"'
|
||||
s2←s2,' --- Abraham Lincoln '
|
||||
s3←'..1111111111111111111111111111111111111111111111111'
|
||||
s3←s3,'111111111111117777888'
|
||||
s4←'I never give ''em hell, I just tell the truth, and t'
|
||||
s4←s4,'hey think it''s hell. '
|
||||
s5←' '
|
||||
s5←s5,' --- Harry S Truman '
|
||||
|
||||
⎕←' ' show s1
|
||||
⎕←'-' show s2
|
||||
⎕←'7' show s3
|
||||
⎕←'.' show s4
|
||||
|
||||
⊃ {⍵ show s5}¨' -r'
|
||||
∇
|
||||
|
|
@ -0,0 +1,28 @@
|
|||
# syntax: GAWK -f DETERMINE_IF_A_STRING_IS_SQUEEZABLE.AWK
|
||||
BEGIN {
|
||||
arr[++n] = "" ; arr2[n] = " "
|
||||
arr[++n] = "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln " ; arr2[n] = "-"
|
||||
arr[++n] = "..1111111111111111111111111111111111111111111111111111111111111117777888" ; arr2[n] = "7"
|
||||
arr[++n] = "I never give 'em hell, I just tell the truth, and they think it's hell. " ; arr2[n] = "."
|
||||
arr[++n] = " --- Harry S Truman " ; arr2[n] = " -r"
|
||||
arr[++n] = "The better the 4-wheel drive, the further you'll be from help when ya get stuck!" ; arr2[n] = "e"
|
||||
arr[++n] = "headmistressship" ; arr2[n] = "s"
|
||||
for (i=1; i<=n; i++) {
|
||||
for (j=1; j<=length(arr2[i]); j++) {
|
||||
main(arr[i],substr(arr2[i],j,1))
|
||||
}
|
||||
}
|
||||
exit(0)
|
||||
}
|
||||
function main(str,chr, c,i,new_str,prev_c) {
|
||||
for (i=1; i<=length(str); i++) {
|
||||
c = substr(str,i,1)
|
||||
if (!(prev_c == c && c == chr)) {
|
||||
prev_c = c
|
||||
new_str = new_str c
|
||||
}
|
||||
}
|
||||
printf("use: '%s'\n",chr)
|
||||
printf("old: %2d <<<%s>>>\n",length(str),str)
|
||||
printf("new: %2d <<<%s>>>\n\n",length(new_str),new_str)
|
||||
}
|
||||
|
|
@ -0,0 +1,41 @@
|
|||
PROC Squeeze(CHAR ARRAY in,out CHAR a)
|
||||
BYTE i,j
|
||||
CHAR c
|
||||
|
||||
j=1 c=0
|
||||
FOR i=1 TO in(0)
|
||||
DO
|
||||
IF in(i)#c OR in(i)#a THEN
|
||||
c=in(i)
|
||||
out(j)=c
|
||||
j==+1
|
||||
FI
|
||||
OD
|
||||
out(0)=j-1
|
||||
RETURN
|
||||
|
||||
PROC Test(CHAR ARRAY s CHAR a)
|
||||
CHAR ARRAY c(100)
|
||||
BYTE CH=$02FC ;Internal hardware value for last key pressed
|
||||
|
||||
Squeeze(s,c,a)
|
||||
PrintF("Character to squeeze: ""%C""%E",a)
|
||||
PrintF("<<<%S>>> (len=%B)%E",s,s(0))
|
||||
PrintF("<<<%S>>> (len=%B)%E",c,c(0))
|
||||
PutE()
|
||||
PrintE("Press any key to continue")
|
||||
PutE()
|
||||
|
||||
DO UNTIL CH#$FF OD
|
||||
CH=$FF
|
||||
RETURN
|
||||
|
||||
PROC Main()
|
||||
Test("",' )
|
||||
Test("""If I were two-faced, would I be wearing this one?"" --- Abraham Lincoln ",'-)
|
||||
Test("..1111111111111111111111111111111111111111111111111111111111111117777888",'7)
|
||||
Test("I never give 'em hell, I just tell the truth, and they think it's hell. ",'.)
|
||||
Test(" --- Harry S Truman ",' )
|
||||
Test(" --- Harry S Truman ",'-)
|
||||
Test(" --- Harry S Truman ",'r)
|
||||
RETURN
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
with Ada.Text_IO; use Ada.Text_IO;
|
||||
procedure Test_Squeezable is
|
||||
procedure Squeeze (S : in String; C : in Character) is
|
||||
Res : String (1 .. S'Length);
|
||||
Len : Natural := 0;
|
||||
begin
|
||||
Put_Line ("Character to be squeezed: '" & C & "'");
|
||||
Put_Line ("Input = <<<" & S & ">>>, length =" & S'Length'Image);
|
||||
for I in S'Range loop
|
||||
if Len = 0 or else (S(I) /= Res(Len) or S(I) /= C) then
|
||||
Len := Len + 1;
|
||||
Res(Len) := S(I);
|
||||
end if;
|
||||
end loop;
|
||||
Put_Line ("Output = <<<" & Res (1 .. Len) & ">>>, length =" & Len'Image);
|
||||
end Squeeze;
|
||||
begin
|
||||
Squeeze ("", ' ');
|
||||
Squeeze ("""If I were two-faced, would I be wearing this one?"" --- Abraham Lincoln ", '-');
|
||||
Squeeze ("..1111111111111111111111111111111111111111111111111111111111111117777888", '7');
|
||||
Squeeze ("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.');
|
||||
Squeeze (" --- Harry S Truman ", ' ');
|
||||
Squeeze (" --- Harry S Truman ", '-');
|
||||
Squeeze (" --- Harry S Truman ", 'r');
|
||||
end Test_Squeezable;
|
||||
|
|
@ -0,0 +1,14 @@
|
|||
squeezable_string(str, char){
|
||||
for i, ch in StrSplit(str){
|
||||
if (ch <> prev) || !InStr(ch, char)
|
||||
res .= ch
|
||||
prev := ch
|
||||
}
|
||||
result := "
|
||||
(ltrim
|
||||
Original string:`t" StrLen(str) " characters`t«««" str "»»»
|
||||
Squeezable Character «««" char "»»»
|
||||
Resultant string:`t" StrLen(res) " characters`t«««" res "»»»
|
||||
)"
|
||||
return result
|
||||
}
|
||||
|
|
@ -0,0 +1,12 @@
|
|||
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. "]
|
||||
char := ["","-","7","."]
|
||||
for i, str in data
|
||||
MsgBox % squeezable_string(str, char[i])
|
||||
|
||||
str := " --- Harry S Truman "
|
||||
for i, char in [" ","-","r"]
|
||||
MsgBox % squeezable_string(str, char)
|
||||
return
|
||||
|
|
@ -0,0 +1,33 @@
|
|||
10 DEFINT A-Z
|
||||
20 READ N: DIM S$(N): FOR I=1 TO N: READ S$(I): NEXT
|
||||
30 READ S,C$: IF S=0 THEN END
|
||||
40 PRINT "Character: '";C$;"'"
|
||||
50 O$=S$(S): GOSUB 200
|
||||
60 I$=S$(S): GOSUB 100: GOSUB 200
|
||||
70 PRINT
|
||||
80 GOTO 30
|
||||
100 REM --
|
||||
101 REM -- Squeeze I$ on character C$, output in O$
|
||||
102 REM --
|
||||
105 O$ = ""
|
||||
110 X = INSTR(I$,C$)
|
||||
120 IF X = 0 THEN O$ = O$ + I$: RETURN
|
||||
130 O$ = O$ + LEFT$(I$,X)
|
||||
140 FOR X=X TO LEN(I$): IF MID$(I$,X,1) = C$ THEN NEXT
|
||||
150 I$ = RIGHT$(I$,LEN(I$)-X+1)
|
||||
160 GOTO 110
|
||||
200 REM --
|
||||
201 REM -- Display O$ and its length in brackets
|
||||
202 REM --
|
||||
210 PRINT USING "##";LEN(O$);
|
||||
220 PRINT "<<<";O$;">>>"
|
||||
230 RETURN
|
||||
400 REM -- Strings
|
||||
410 DATA 5
|
||||
415 DATA""
|
||||
420 DATA"'If I were two-faced, would I be wearing this one?' --- Abraham Lincoln "
|
||||
430 DATA"..1111111111111111111111111111111111111111111111111111111111111117777888"
|
||||
440 DATA"I never give 'em hell, I just tell the truth, and they think it's hell. "
|
||||
450 DATA" --- Harry S Truman "
|
||||
500 REM -- String index and character to squeeze
|
||||
510 DATA 1," ", 2,"-", 3,"7", 4,".", 5," ", 5,"-", 5,"r", 0,""
|
||||
|
|
@ -0,0 +1,41 @@
|
|||
get "libhdr"
|
||||
|
||||
// Squeeze a string
|
||||
let squeeze(in, ch, out) = valof
|
||||
$( out%0 := 0
|
||||
for i=1 to in%0
|
||||
if i=1 | in%i~=ch | in%(i-1)~=ch
|
||||
$( out%0 := out%0 + 1
|
||||
out%(out%0) := in%i
|
||||
$)
|
||||
resultis out
|
||||
$)
|
||||
|
||||
// Print string with brackets and length
|
||||
let brackets(s) be
|
||||
writef("%N: <<<%S>>>*N", s%0, s)
|
||||
|
||||
// Print original and collapsed version
|
||||
let show(s, ch) be
|
||||
$( let v = vec 1+255/BYTESPERWORD
|
||||
writef("Character: '%C'*N", ch)
|
||||
brackets(s)
|
||||
brackets(squeeze(s, ch, v))
|
||||
wrch('*N')
|
||||
$)
|
||||
|
||||
let start() be
|
||||
$( let s1=""
|
||||
let s2="*"If I were two-faced, would I be wearing this one?*" --- Abraham Lincoln "
|
||||
let s3="..1111111111111111111111111111111111111111111111111111111111111117777888"
|
||||
let s4="I never give 'em hell, I just tell the truth, and they think it's hell. "
|
||||
let s5=" --- Harry S Truman "
|
||||
|
||||
show(s1, ' ')
|
||||
show(s2, '-')
|
||||
show(s3, '7')
|
||||
show(s4, '.')
|
||||
show(s5, ' ')
|
||||
show(s5, '-')
|
||||
show(s5, 'r')
|
||||
$)
|
||||
|
|
@ -0,0 +1,31 @@
|
|||
#include <algorithm>
|
||||
#include <string>
|
||||
#include <iostream>
|
||||
|
||||
template<typename char_type>
|
||||
std::basic_string<char_type> squeeze(std::basic_string<char_type> str, char_type ch) {
|
||||
auto i = std::unique(str.begin(), str.end(),
|
||||
[ch](char_type a, char_type b) { return a == ch && b == ch; });
|
||||
str.erase(i, str.end());
|
||||
return str;
|
||||
}
|
||||
|
||||
void test(const std::string& str, char ch) {
|
||||
std::cout << "character: '" << ch << "'\n";
|
||||
std::cout << "original: <<<" << str << ">>>, length: " << str.length() << '\n';
|
||||
std::string squeezed(squeeze(str, ch));
|
||||
std::cout << "result: <<<" << squeezed << ">>>, length: " << squeezed.length() << '\n';
|
||||
std::cout << '\n';
|
||||
}
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
test("", ' ');
|
||||
test("\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", '-');
|
||||
test("..1111111111111111111111111111111111111111111111111111111111111117777888", '7');
|
||||
test("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.');
|
||||
std::string truman(" --- Harry S Truman ");
|
||||
test(truman, ' ');
|
||||
test(truman, '-');
|
||||
test(truman, 'r');
|
||||
return 0;
|
||||
}
|
||||
|
|
@ -0,0 +1,27 @@
|
|||
using System;
|
||||
using static System.Linq.Enumerable;
|
||||
|
||||
public class Program
|
||||
{
|
||||
static void Main()
|
||||
{
|
||||
SqueezeAndPrint("", ' ');
|
||||
SqueezeAndPrint("\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", '-');
|
||||
SqueezeAndPrint("..1111111111111111111111111111111111111111111111111111111111111117777888", '7');
|
||||
SqueezeAndPrint("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.');
|
||||
string s = " --- Harry S Truman ";
|
||||
SqueezeAndPrint(s, ' ');
|
||||
SqueezeAndPrint(s, '-');
|
||||
SqueezeAndPrint(s, 'r');
|
||||
}
|
||||
|
||||
static void SqueezeAndPrint(string s, char c) {
|
||||
Console.WriteLine($"squeeze: '{c}'");
|
||||
Console.WriteLine($"old: {s.Length} «««{s}»»»");
|
||||
s = Squeeze(s, c);
|
||||
Console.WriteLine($"new: {s.Length} «««{s}»»»");
|
||||
}
|
||||
|
||||
static string Squeeze(string s, char c) => string.IsNullOrEmpty(s) ? "" :
|
||||
s[0] + new string(Range(1, s.Length - 1).Where(i => s[i] != c || s[i] != s[i - 1]).Select(i => s[i]).ToArray());
|
||||
}
|
||||
|
|
@ -0,0 +1,170 @@
|
|||
#include<string.h>
|
||||
#include<stdlib.h>
|
||||
#include<stdio.h>
|
||||
|
||||
#define COLLAPSE 0
|
||||
#define SQUEEZE 1
|
||||
|
||||
typedef struct charList{
|
||||
char c;
|
||||
struct charList *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.
|
||||
*/
|
||||
|
||||
int strcmpi(char str1[100],char str2[100]){
|
||||
int len1 = strlen(str1), len2 = strlen(str2), i;
|
||||
|
||||
if(len1!=len2){
|
||||
return 1;
|
||||
}
|
||||
|
||||
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]))
|
||||
return 1;
|
||||
else if((str2[i]>='A'&&str2[i]<='Z')&&(str1[i]>='a'&&str1[i]<='z')&&(str1[i]-65!=str2[i]))
|
||||
return 1;
|
||||
else if(str1[i]!=str2[i])
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
charList *strToCharList(char* str){
|
||||
int len = 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;
|
||||
}
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
char* charListToString(charList* list){
|
||||
charList* iterator = list;
|
||||
int count = 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';
|
||||
|
||||
return str;
|
||||
}
|
||||
|
||||
char* processString(char str[100],int operation, char squeezeChar){
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
return charListToString(strList);
|
||||
}
|
||||
|
||||
void printResults(char originalString[100], char finalString[100], int operation, char squeezeChar){
|
||||
if(operation==SQUEEZE){
|
||||
printf("Specified Operation : SQUEEZE\nTarget Character : %c",squeezeChar);
|
||||
}
|
||||
|
||||
else
|
||||
printf("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));
|
||||
}
|
||||
|
||||
int main(int argc, char** argv){
|
||||
int operation;
|
||||
char squeezeChar;
|
||||
|
||||
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]);
|
||||
return 0;
|
||||
}
|
||||
|
||||
if(strcmpi(argv[1],"SQUEEZE")==0 && argc!=4){
|
||||
scanf("Please enter characted to be squeezed : %c",&squeezeChar);
|
||||
operation = SQUEEZE;
|
||||
}
|
||||
|
||||
else if(argc==4){
|
||||
operation = SQUEEZE;
|
||||
squeezeChar = argv[3][0];
|
||||
}
|
||||
|
||||
else if(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);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
|
@ -0,0 +1,12 @@
|
|||
(defn squeeze [s c]
|
||||
(let [spans (partition-by #(= c %) s)
|
||||
span-out (fn [span]
|
||||
(if (= c (first span))
|
||||
(str c)
|
||||
(apply str span)))]
|
||||
(apply str (map span-out spans))))
|
||||
|
||||
(defn test-squeeze [s c]
|
||||
(let [out (squeeze s c)]
|
||||
(println (format "Input: <<<%s>>> (len %d)\n" s (count s))
|
||||
(format "becomes: <<<%s>>> (len %d)" out (count out)))))
|
||||
|
|
@ -0,0 +1,46 @@
|
|||
include "cowgol.coh";
|
||||
include "strings.coh";
|
||||
|
||||
sub squeeze(ch: uint8, str: [uint8], buf: [uint8]): (r: [uint8]) is
|
||||
r := buf;
|
||||
var prev: uint8 := 0;
|
||||
while [str] != 0 loop
|
||||
if prev != ch or [str] != ch then
|
||||
prev := [str];
|
||||
[buf] := prev;
|
||||
buf := @next buf;
|
||||
end if;
|
||||
str := @next str;
|
||||
end loop;
|
||||
[buf] := 0;
|
||||
end sub;
|
||||
|
||||
sub squeezeAndPrint(ch: uint8, str: [uint8]) is
|
||||
sub bracketLength(str: [uint8]) is
|
||||
print_i32(StrLen(str) as uint32);
|
||||
print(" <<<");
|
||||
print(str);
|
||||
print(">>>\n");
|
||||
end sub;
|
||||
|
||||
var buf: uint8[256];
|
||||
bracketLength(str);
|
||||
bracketLength(squeeze(ch, str, &buf[0]));
|
||||
print_nl();
|
||||
end sub;
|
||||
|
||||
var strs: [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 "
|
||||
};
|
||||
|
||||
squeezeAndPrint(' ', strs[0]);
|
||||
squeezeAndPrint('-', strs[1]);
|
||||
squeezeAndPrint('7', strs[2]);
|
||||
squeezeAndPrint('.', strs[3]);
|
||||
squeezeAndPrint(' ', strs[4]);
|
||||
squeezeAndPrint('-', strs[4]);
|
||||
squeezeAndPrint('r', strs[4]);
|
||||
|
|
@ -0,0 +1,32 @@
|
|||
import std.stdio;
|
||||
|
||||
void squeezable(string s, char rune) {
|
||||
writeln("squeeze: '", rune, "'");
|
||||
writeln("old: <<<", s, ">>>, length = ", s.length);
|
||||
|
||||
write("new: <<<");
|
||||
char last = '\0';
|
||||
int len = 0;
|
||||
foreach (c; s) {
|
||||
if (c != last || c != rune) {
|
||||
write(c);
|
||||
len++;
|
||||
}
|
||||
last = c;
|
||||
}
|
||||
writeln(">>>, length = ", len);
|
||||
|
||||
writeln;
|
||||
}
|
||||
|
||||
void main() {
|
||||
squeezable(``, ' ');
|
||||
squeezable(`"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln `, '-');
|
||||
squeezable(`..1111111111111111111111111111111111111111111111111111111111111117777888`, '7');
|
||||
squeezable(`I never give 'em hell, I just tell the truth, and they think it's hell. `, '.');
|
||||
|
||||
string s = ` --- Harry S Truman `;
|
||||
squeezable(s, ' ');
|
||||
squeezable(s, '-');
|
||||
squeezable(s, 'r');
|
||||
}
|
||||
|
|
@ -0,0 +1,43 @@
|
|||
program Determine_if_a_string_is_squeezable;
|
||||
|
||||
{$APPTYPE CONSOLE}
|
||||
|
||||
uses
|
||||
System.SysUtils;
|
||||
|
||||
var
|
||||
TestStrings: TArray<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 ',
|
||||
'122333444455555666666777777788888888999999999',
|
||||
'The better the 4-wheel drive, the further you''ll be from help when ya get stuck!',
|
||||
'headmistressship'];
|
||||
TestChar: TArray<string> = [' ', '-', '7', '.', ' -r', '5', 'e', 's'];
|
||||
|
||||
function squeeze(s: string; include: char): string;
|
||||
begin
|
||||
var sb := TStringBuilder.Create;
|
||||
for var i := 1 to s.Length do
|
||||
begin
|
||||
if (i = 1) or (s[i - 1] <> s[i]) or ((s[i - 1] = s[i]) and (s[i] <> include)) then
|
||||
sb.Append(s[i]
|
||||
end;
|
||||
Result := sb.ToString;
|
||||
sb.Free;
|
||||
end;
|
||||
|
||||
begin
|
||||
for var testNum := 0 to high(TestStrings) do
|
||||
begin
|
||||
var s := TestStrings[testNum];
|
||||
for var c in TestChar[testNum] do
|
||||
begin
|
||||
var result: string := squeeze(s, c);
|
||||
writeln(format('use: "%s"'#10'old: %2d <<<%s>>>'#10'new: %2d <<<%s>>>'#10, [c,
|
||||
s.Length, s, result.length, result]));
|
||||
end;
|
||||
end;
|
||||
readln;
|
||||
end.
|
||||
|
|
@ -0,0 +1,14 @@
|
|||
// Determine if a string is squeezable. Nigel Galloway: June 9th., 2020
|
||||
let squeeze n i=if String.length n=0 then None else
|
||||
let fN=let mutable g=n.[0] in (fun n->if n=i && n=g then false else g<-n; true)
|
||||
let fG=n.[0..0]+System.String(n.[1..].ToCharArray()|>Array.filter fN)
|
||||
if fG.Length=n.Length then None else Some fG
|
||||
let isSqueezable n g=match squeeze n g with
|
||||
Some i->printfn "%A squeezes <<<%s>>> (length %d) to <<<%s>>> (length %d)" g n n.Length i i.Length
|
||||
|_->printfn "%A does not squeeze <<<%s>>> (length %d)" g n n.Length
|
||||
|
||||
isSqueezable "" ' '
|
||||
isSqueezable "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln " '-'
|
||||
isSqueezable "..1111111111111111111111111111111111111111111111111111111111111117777888" '7'
|
||||
isSqueezable "I never give 'em hell, I just tell the truth, and they think it's hell. " '.'
|
||||
let fN=isSqueezable " --- Harry S Truman " in fN ' '; fN '-'; fN 'r'
|
||||
|
|
@ -0,0 +1,31 @@
|
|||
USING: formatting fry io kernel math sbufs sequences strings ;
|
||||
IN: rosetta-code.squeeze
|
||||
|
||||
: (squeeze) ( str c -- new-str )
|
||||
[ unclip-slice 1string >sbuf ] dip
|
||||
'[ over last over [ _ = ] both? [ drop ] [ suffix! ] if ]
|
||||
reduce >string ;
|
||||
|
||||
: squeeze ( str c -- new-str )
|
||||
over empty? [ 2drop "" ] [ (squeeze) ] if ;
|
||||
|
||||
: .str ( str -- ) dup length "«««%s»»» (length %d)\n" printf ;
|
||||
|
||||
: show-squeeze ( str c -- )
|
||||
dup "Specified character: '%c'\n" printf
|
||||
[ "Before squeeze: " write drop .str ]
|
||||
[ "After squeeze: " write squeeze .str ] 2bi nl ;
|
||||
|
||||
: squeeze-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. "
|
||||
} "\0-7." [ show-squeeze ] 2each
|
||||
|
||||
" --- Harry S Truman "
|
||||
[ CHAR: space ] [ CHAR: - ] [ CHAR: r ] tri
|
||||
[ show-squeeze ] 2tri@ ;
|
||||
|
||||
MAIN: squeeze-demo
|
||||
|
|
@ -0,0 +1,56 @@
|
|||
program main
|
||||
implicit none
|
||||
character(len=:),allocatable :: strings(:)
|
||||
|
||||
strings=[ character(len=72) :: &
|
||||
'', &
|
||||
'"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' &
|
||||
]
|
||||
|
||||
call printme( trim(strings(1)), ' ' )
|
||||
call printme( strings(2:4), ['-','7','.'] )
|
||||
call printme( strings(5), [' ','-','r'] )
|
||||
|
||||
contains
|
||||
|
||||
impure elemental subroutine printme(str,chr)
|
||||
character(len=*),intent(in) :: str
|
||||
character(len=1),intent(in) :: chr
|
||||
character(len=:),allocatable :: answer
|
||||
write(*,'(a)')repeat('=',9)
|
||||
write(*,'("IN: <<<",g0,">>>")')str
|
||||
answer=compact(str,chr)
|
||||
write(*,'("OUT: <<<",g0,">>>")')answer
|
||||
write(*,'("LENS: ",*(g0,1x))')"from",len(str),"to",len(answer),"for a change of",len(str)-len(answer)
|
||||
write(*,'("CHAR: ",g0)')chr
|
||||
end subroutine printme
|
||||
|
||||
elemental function compact(str,charp) result (outstr)
|
||||
|
||||
character(len=*),intent(in) :: str
|
||||
character(len=1),intent(in) :: charp
|
||||
character(len=:),allocatable :: outstr
|
||||
character(len=1) :: ch, last_one
|
||||
integer :: i, pio ! position in output
|
||||
|
||||
outstr=repeat(' ',len(str)) ! start with a string big enough to hold any output
|
||||
if(len(outstr)==0)return ! handle edge condition
|
||||
last_one=str(1:1) ! since at least this long start output with first character
|
||||
outstr(1:1)=last_one
|
||||
pio=1
|
||||
|
||||
do i=2,len(str)
|
||||
ch=str(i:i)
|
||||
pio=pio+merge(0,1, ch.eq.last_one.and.ch.eq.charp) ! decide whether to advance before saving
|
||||
outstr(pio:pio)=ch ! store new one or overlay the duplcation
|
||||
last_one=ch
|
||||
enddo
|
||||
|
||||
outstr=outstr(:pio) ! trim the output string to just what was set
|
||||
end function compact
|
||||
|
||||
end program main
|
||||
}
|
||||
|
|
@ -0,0 +1,58 @@
|
|||
function squeeze(byval s as string,target as string) as string
|
||||
dim as string g
|
||||
dim as long n
|
||||
for n =0 to len(s)-2
|
||||
if s[n]=asc(target) then
|
||||
if s[n]<>s[n+1] then g+=chr(s[n])
|
||||
else
|
||||
g+=chr(s[n])
|
||||
end if
|
||||
next n
|
||||
if len(s) then g+=chr(s[n])
|
||||
return g
|
||||
end function
|
||||
|
||||
dim as string z,o
|
||||
print "character "" """
|
||||
o=""
|
||||
print "original ";o;tab(90);"(";len(o);")"
|
||||
z=Squeeze("", " ")
|
||||
print "squeeze "; z;tab(90);"(";len(z);")"
|
||||
print
|
||||
print "character ""-"""
|
||||
o= """If I were two-faced, would I be wearing this one?"" --- Abraham Lincoln "
|
||||
print "original ";o;tab(90);"(";len(o);")"
|
||||
z=Squeeze(o,"-")
|
||||
print "squeeze "; z;tab(90);"(";len(z);")"
|
||||
print
|
||||
print "character ""7"""
|
||||
o="..1111111111111111111111111111111111111111111111111111111111111117777888"
|
||||
print "original ";o;tab(90);"(";len(o);")"
|
||||
z=Squeeze(o,"7")
|
||||
print "squeeze "; z;tab(90);"(";len(z);")"
|
||||
print
|
||||
print "character ""."""
|
||||
o="I never give 'em hell, I just tell the truth, and they think it's hell. "
|
||||
print "original ";o;tab(90);"(";len(o);")"
|
||||
z=Squeeze(o,".")
|
||||
print "squeeze ";z ;tab(90);"(";len(z);")"
|
||||
print
|
||||
dim as string s = " --- Harry S Truman "
|
||||
print "character "" """
|
||||
o=" --- Harry S Truman "
|
||||
print "original ";o;tab(90);"(";len(o);")"
|
||||
z=Squeeze(s, " ")
|
||||
print "squeeze ";z ;tab(90);"(";len(z);")"
|
||||
print
|
||||
print "character ""-"""
|
||||
o=" --- Harry S Truman "
|
||||
print "original ";o;tab(90);"(";len(o);")"
|
||||
z=Squeeze(s, "-")
|
||||
print "squeeze "; z;tab(90);"(";len(z);")"
|
||||
print
|
||||
print "character ""r"""
|
||||
o=" --- Harry S Truman "
|
||||
print "original ";o;tab(90);"(";len(o);")"
|
||||
z=Squeeze(s, "r")
|
||||
print "squeeze "; z;tab(90);"(";len(z);")"
|
||||
sleep
|
||||
|
|
@ -0,0 +1,17 @@
|
|||
squeeze[str, ch] :=
|
||||
{
|
||||
println["Use: '$ch'"]
|
||||
println["old: " + length[str] + " <<<$str>>>"]
|
||||
str =~ subst["($ch)\\1+", "$$1", "g"]
|
||||
println["new: " + length[str] + " <<<$str>>>"]
|
||||
}
|
||||
|
||||
lines = [["", [""]],
|
||||
[""""If I were two-faced, would I be wearing this one?" --- Abraham Lincoln """, ["-"]],
|
||||
["..1111111111111111111111111111111111111111111111111111111111111117777888", ["7"]],
|
||||
["I never give 'em hell, I just tell the truth, and they think it's hell. ", ["."]],
|
||||
[" --- Harry S Truman ",[" ", "-", "r"]]]
|
||||
|
||||
for [line, chars] = lines
|
||||
for char = chars
|
||||
println[squeeze[line, char]]
|
||||
|
|
@ -0,0 +1,45 @@
|
|||
package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
// Returns squeezed string, original and new lengths in
|
||||
// unicode code points (not normalized).
|
||||
func squeeze(s string, c rune) (string, int, int) {
|
||||
r := []rune(s)
|
||||
le, del := len(r), 0
|
||||
for i := le - 2; i >= 0; i-- {
|
||||
if r[i] == c && r[i] == r[i+1] {
|
||||
copy(r[i:], r[i+1:])
|
||||
del++
|
||||
}
|
||||
}
|
||||
if del == 0 {
|
||||
return s, le, le
|
||||
}
|
||||
r = r[:le-del]
|
||||
return string(r), le, len(r)
|
||||
}
|
||||
|
||||
func main() {
|
||||
strings := []string{
|
||||
"",
|
||||
`"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln `,
|
||||
"..1111111111111111111111111111111111111111111111111111111111111117777888",
|
||||
"I never give 'em hell, I just tell the truth, and they think it's hell. ",
|
||||
" --- Harry S Truman ",
|
||||
"The better the 4-wheel drive, the further you'll be from help when ya get stuck!",
|
||||
"headmistressship",
|
||||
"aardvark",
|
||||
"😍😀🙌💃😍😍😍🙌",
|
||||
}
|
||||
chars := [][]rune{{' '}, {'-'}, {'7'}, {'.'}, {' ', '-', 'r'}, {'e'}, {'s'}, {'a'}, {'😍'}}
|
||||
|
||||
for i, s := range strings {
|
||||
for _, c := range chars[i] {
|
||||
ss, olen, slen := squeeze(s, c)
|
||||
fmt.Printf("specified character = %q\n", c)
|
||||
fmt.Printf("original : length = %2d, string = «««%s»»»\n", olen, s)
|
||||
fmt.Printf("squeezed : length = %2d, string = «««%s»»»\n\n", slen, ss)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,33 @@
|
|||
class StringSqueezable {
|
||||
static void main(String[] args) {
|
||||
String[] testStrings = [
|
||||
"",
|
||||
"\"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"
|
||||
]
|
||||
|
||||
String[] testChar = [" ", "-", "7", ".", " -r", "5", "e", "s"]
|
||||
for (int testNum = 0; testNum < testStrings.length; testNum++) {
|
||||
String s = testStrings[testNum]
|
||||
for (char c : testChar[testNum].toCharArray()) {
|
||||
String result = squeeze(s, c)
|
||||
System.out.printf("use: '%c'%nold: %2d <<<%s>>>%nnew: %2d <<<%s>>>%n%n", c, s.length(), s, result.length(), result)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static String squeeze(String input, char include) {
|
||||
StringBuilder sb = new StringBuilder()
|
||||
for (int i = 0; i < input.length(); i++) {
|
||||
if (i == 0 || input.charAt(i - 1) != input.charAt(i) || (input.charAt(i - 1) == input.charAt(i) && input.charAt(i) != include)) {
|
||||
sb.append(input.charAt(i))
|
||||
}
|
||||
}
|
||||
return sb.toString()
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,26 @@
|
|||
import Text.Printf (printf)
|
||||
|
||||
input :: [(String, Char)]
|
||||
input = [ ("", ' ')
|
||||
, ("The better the 4-wheel drive, the further you'll be from help when ya get stuck!", 'e')
|
||||
, ("headmistressship", 's')
|
||||
, ("\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", '-')
|
||||
, ("..1111111111111111111111111111111111111111111111111111111111111117777888", '7')
|
||||
, ("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.')
|
||||
, (" --- Harry S Truman ", 'r')
|
||||
, ("aardvark", 'a')
|
||||
, ("😍😀🙌💃😍😍😍🙌", '😍')
|
||||
]
|
||||
|
||||
collapse :: Eq a => [a] -> a -> [a]
|
||||
collapse s c = go s
|
||||
where go [] = []
|
||||
go (x:y:xs)
|
||||
| x == y && x == c = go (y:xs)
|
||||
| otherwise = x : go (y:xs)
|
||||
go xs = xs
|
||||
|
||||
main :: IO ()
|
||||
main =
|
||||
mapM_ (\(a, b, c) -> printf "squeeze: '%c'\nold: %3d «««%s»»»\nnew: %3d «««%s»»»\n\n" c (length a) a (length b) b)
|
||||
$ (\(s, c) -> (s, collapse s c, c)) <$> input
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
dlb
|
||||
}.~ (=&' ' (i.) 0:)
|
||||
dtb
|
||||
#~ ([: +./\. ' '&~:)
|
||||
deb
|
||||
#~ ((+.) (1: |. (> </\)))@(' '&~:)
|
||||
|
|
@ -0,0 +1,34 @@
|
|||
'x' squeeze 'xabxxcxdxxx' NB. example
|
||||
xabxcxdx
|
||||
|
||||
|
||||
,.' -7. -r' main&.> <;._2 to_be_squished
|
||||
┌──────────────────────────────────────────────────────────────────────────────┐
|
||||
│squeeze ' ' reduces the length from 0 to 0 │
|
||||
│<<<>>> │
|
||||
│<<<>>> │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│squeeze '-' reduces the length from 71 to 69 │
|
||||
│<<<"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>>> │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│squeeze '7' reduces the length from 72 to 69 │
|
||||
│<<<..1111111111111111111111111111111111111111111111111111111111111117777888>>>│
|
||||
│<<<..1111111111111111111111111111111111111111111111111111111111111117888>>> │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│squeeze '.' reduces the length from 71 to 71 │
|
||||
│<<<I never give 'em hell, I just tell the truth, and they think it's hell.>>> │
|
||||
│<<<I never give 'em hell, I just tell the truth, and they think it's hell.>>> │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│squeeze ' ' reduces the length from 70 to 19 │
|
||||
│<<< --- Harry S Truman>>> │
|
||||
│<<< --- Harry S Truman>>> │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│squeeze '-' reduces the length from 70 to 68 │
|
||||
│<<< --- Harry S Truman>>> │
|
||||
│<<< - Harry S Truman>>> │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│squeeze 'r' reduces the length from 70 to 69 │
|
||||
│<<< --- Harry S Truman>>> │
|
||||
│<<< --- Hary S Truman>>> │
|
||||
└──────────────────────────────────────────────────────────────────────────────┘
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
NB. Note |.!.1 here instead of the APL version's 1 , }. to more elegantly handle the null case in J
|
||||
sq =: ] #~ ~: +. _1 |.!.1 ] ~: 1 |. ]
|
||||
|
|
@ -0,0 +1,10 @@
|
|||
require'format/printf' NB. For formatting the output
|
||||
'C I' =: <"1 |: P =: ; ;"0 1^:(0<#@[)&.>/"1 (({.~ ; (}.~>:)) i.&'|')&> LF cut noun define
|
||||
|
|
||||
-|"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln
|
||||
7|..1111111111111111111111111111111111111111111111111111111111111117777888
|
||||
.|I never give 'em hell, I just tell the truth, and they think it's hell.
|
||||
-r| --- Harry S Truman
|
||||
)
|
||||
S =: sq&.>/"1 P
|
||||
smoutput 'chr: ''%s''\nin: %d «««%s»»»\nout: %d «««%s»»»\n' sprintf C ,. (#&.>I),.I ,. (#&.>S),.S
|
||||
|
|
@ -0,0 +1,44 @@
|
|||
// Title: Determine if a string is squeezable
|
||||
|
||||
public class StringSqueezable {
|
||||
|
||||
public static void main(String[] args) {
|
||||
String[] testStrings = new 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 ",
|
||||
"122333444455555666666777777788888888999999999",
|
||||
"The better the 4-wheel drive, the further you'll be from help when ya get stuck!",
|
||||
"headmistressship"};
|
||||
|
||||
String[] testChar = new String[] {
|
||||
" ",
|
||||
"-",
|
||||
"7",
|
||||
".",
|
||||
" -r",
|
||||
"5",
|
||||
"e",
|
||||
"s"};
|
||||
for ( int testNum = 0 ; testNum < testStrings.length ; testNum++ ) {
|
||||
String s = testStrings[testNum];
|
||||
for ( char c : testChar[testNum].toCharArray() ) {
|
||||
String result = squeeze(s, c);
|
||||
System.out.printf("use: '%c'%nold: %2d <<<%s>>>%nnew: %2d <<<%s>>>%n%n", c, s.length(), s, result.length(), result);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static String squeeze(String in, char include) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for ( int i = 0 ; i < in.length() ; i++ ) {
|
||||
if ( i == 0 || in.charAt(i-1) != in.charAt(i) || (in.charAt(i-1) == in.charAt(i) && in.charAt(i) != include)) {
|
||||
sb.append(in.charAt(i));
|
||||
}
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,10 @@
|
|||
# Assume $c is specified as a single character correctly
|
||||
def squeeze($c): gsub("[\($c)]+"; $c);
|
||||
|
||||
def Guillemets: "«««\(.)»»»";
|
||||
|
||||
def Squeeze(s; $c):
|
||||
"Squeeze character: \($c)",
|
||||
(s | "Original: \(Guillemets) has length \(length)",
|
||||
(squeeze($c) | "result is \(Guillemets) with length \(length)")),
|
||||
"";
|
||||
|
|
@ -0,0 +1,8 @@
|
|||
Squeeze("\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln "; "-"),
|
||||
Squeeze ("..1111111111111111111111111111111111111111111111111111111111111117777888"; "7"),
|
||||
Squeeze ("I never give 'em hell, I just tell the truth, and they think it's hell. "; "."),
|
||||
Squeeze (" --- Harry S Truman "; " "),
|
||||
Squeeze (" --- Harry S Truman "; "-"),
|
||||
Squeeze (" --- Harry S Truman "; "r"),
|
||||
|
||||
Squeeze("SabcSS:SSdefSSSghSS";"S")
|
||||
|
|
@ -0,0 +1,27 @@
|
|||
Squeeze character: -
|
||||
Original: «««"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln »»» has length 72
|
||||
result is «««"If I were two-faced, would I be wearing this one?" - Abraham Lincoln »»» with length 70
|
||||
|
||||
Squeeze character: 7
|
||||
Original: «««..1111111111111111111111111111111111111111111111111111111111111117777888»»» has length 72
|
||||
result is «««..1111111111111111111111111111111111111111111111111111111111111117888»»» with length 69
|
||||
|
||||
Squeeze character: .
|
||||
Original: «««I never give 'em hell, I just tell the truth, and they think it's hell. »»» has length 72
|
||||
result is «««.»»» with length 1
|
||||
|
||||
Squeeze character:
|
||||
Original: ««« --- Harry S Truman »»» has length 72
|
||||
result is ««« --- Harry S Truman »»» with length 20
|
||||
|
||||
Squeeze character: -
|
||||
Original: ««« --- Harry S Truman »»» has length 72
|
||||
result is ««« - Harry S Truman »»» with length 70
|
||||
|
||||
Squeeze character: r
|
||||
Original: ««« --- Harry S Truman »»» has length 72
|
||||
result is ««« --- Hary S Truman »»» with length 71
|
||||
|
||||
Squeeze character: S
|
||||
Original: «««SabcSS:SSdefSSSghSS»»» has length 19
|
||||
result is «««SabcS:SdefSghS»»» with length 14
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
const teststringpairs = [
|
||||
("", ' '),
|
||||
(""""If I were two-faced, would I be wearing this one?" --- Abraham Lincoln """, '-'),
|
||||
("..1111111111111111111111111111111111111111111111111111111111111117777888", '7'),
|
||||
("""I never give 'em hell, I just tell the truth, and they think it's hell. """, '.'),
|
||||
(" --- Harry S Truman ", ' '),
|
||||
(" --- Harry S Truman ", '-'),
|
||||
(" --- Harry S Truman ", 'r')]
|
||||
|
||||
function squeezed(s, c)
|
||||
t = isempty(s) ? "" : s[1:1]
|
||||
for x in s[2:end]
|
||||
if x != t[end] || x != c
|
||||
t *= x
|
||||
end
|
||||
end
|
||||
t
|
||||
end
|
||||
|
||||
for (s, c) in teststringpairs
|
||||
n, t = length(s), squeezed(s, c)
|
||||
println("«««$s»»» (length $n)\n",
|
||||
s == t ? "is not squeezed, so remains" : "squeezes to",
|
||||
":\n«««$t»»» (length $(length(t))).\n")
|
||||
end
|
||||
|
|
@ -0,0 +1,37 @@
|
|||
fun main() {
|
||||
val testStrings = 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 ",
|
||||
"122333444455555666666777777788888888999999999",
|
||||
"The better the 4-wheel drive, the further you'll be from help when ya get stuck!",
|
||||
"headmistressship")
|
||||
val testChar = arrayOf(
|
||||
" ",
|
||||
"-",
|
||||
"7",
|
||||
".",
|
||||
" -r",
|
||||
"5",
|
||||
"e",
|
||||
"s")
|
||||
for (testNum in testStrings.indices) {
|
||||
val s = testStrings[testNum]
|
||||
for (c in testChar[testNum].toCharArray()) {
|
||||
val result = squeeze(s, c)
|
||||
System.out.printf("use: '%c'%nold: %2d >>>%s<<<%nnew: %2d >>>%s<<<%n%n", c, s.length, s, result.length, result)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun squeeze(input: String, include: Char): String {
|
||||
val sb = StringBuilder()
|
||||
for (i in input.indices) {
|
||||
if (i == 0 || input[i - 1] != input[i] || input[i - 1] == input[i] && input[i] != include) {
|
||||
sb.append(input[i])
|
||||
}
|
||||
}
|
||||
return sb.toString()
|
||||
}
|
||||
|
|
@ -0,0 +1,32 @@
|
|||
function squeezable(s, rune)
|
||||
print("squeeze: `" .. rune .. "`")
|
||||
print("old: <<<" .. s .. ">>>, length = " .. string.len(s))
|
||||
|
||||
local last = nil
|
||||
local le = 0
|
||||
io.write("new: <<<")
|
||||
for c in s:gmatch"." do
|
||||
if c ~= last or c ~= rune then
|
||||
io.write(c)
|
||||
le = le + 1
|
||||
end
|
||||
last = c
|
||||
end
|
||||
print(">>>, length = " .. le)
|
||||
|
||||
print()
|
||||
end
|
||||
|
||||
function main()
|
||||
squeezable("", ' ');
|
||||
squeezable("\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", '-')
|
||||
squeezable("..1111111111111111111111111111111111111111111111111111111111111117777888", '7')
|
||||
squeezable("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.')
|
||||
|
||||
local s = " --- Harry S Truman "
|
||||
squeezable(s, ' ')
|
||||
squeezable(s, '-')
|
||||
squeezable(s, 'r')
|
||||
end
|
||||
|
||||
main()
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
function r = squeezee(s,c)
|
||||
ix = [];
|
||||
c = unique(c);
|
||||
for k=1:length(c)
|
||||
ix=[ix; find((s(1:end-1)==s(2:end)) & (s(1:end-1)==c(k)))+1];
|
||||
end
|
||||
r=s;
|
||||
r(ix)=[];
|
||||
|
||||
fprintf(1,'Character to be squeezed: "%s"\n',c);
|
||||
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);
|
||||
|
||||
end
|
||||
|
||||
|
||||
squeezee('', ' ')
|
||||
squeezee('║╚═══════════════════════════════════════════════════════════════════════╗', '-')
|
||||
squeezee('║"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ║', '7')
|
||||
squeezee('║..1111111111111111111111111111111111111111111111111111111111111117777888║', '.')
|
||||
squeezee('║I never give ''em hell, I just tell the truth, and they think it''s hell. ║', '.')
|
||||
squeezee('║ --- Harry S Truman ║', '.')
|
||||
squeezee('║ --- Harry S Truman ║', '-')
|
||||
squeezee('║ --- Harry S Truman ║', 'r')
|
||||
|
|
@ -0,0 +1,16 @@
|
|||
ClearAll[Squeeze]
|
||||
Squeeze[s_String,sq_String]:=StringReplace[s,x:(sq..):>sq]
|
||||
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 "
|
||||
};
|
||||
Squeeze[s[[1]],""]
|
||||
Squeeze[s[[2]],"-"]
|
||||
Squeeze[s[[3]],"7"]
|
||||
Squeeze[s[[4]],"."]
|
||||
Squeeze[s[[5]]," "]
|
||||
Squeeze[s[[5]],"-"]
|
||||
Squeeze[s[[5]],"r"]
|
||||
|
|
@ -0,0 +1,50 @@
|
|||
to-report split [ string ]
|
||||
;; utility reporter to split a string into a list
|
||||
report n-values length string [ [ n ] -> item n string ]
|
||||
end
|
||||
|
||||
to-report squeeze [ character string ]
|
||||
;; reporter that actually does the squeeze function
|
||||
;; remote immeadiately repeating instances of character from string
|
||||
ifelse ( string = "" )
|
||||
[ report "" ] ;; empty input, report empty output
|
||||
[ report
|
||||
reduce
|
||||
[ [ a b ] ->
|
||||
( word a
|
||||
ifelse-value b = character and b = last a
|
||||
[ "" ]
|
||||
[ b ]
|
||||
)
|
||||
]
|
||||
split string
|
||||
]
|
||||
end
|
||||
|
||||
to-report bracket [ string ]
|
||||
;; utility reporter to enclose a string in brackets
|
||||
report ( word "<<<" string ">>>" )
|
||||
end
|
||||
|
||||
to-report format [ string ]
|
||||
;; utility reporter to format the output as required
|
||||
report ( word bracket string " " length string )
|
||||
end
|
||||
|
||||
to demo-squeeze [ character string ]
|
||||
;; procedure to display the required output
|
||||
output-print bracket character
|
||||
output-print format string
|
||||
output-print format squeeze character string
|
||||
end
|
||||
|
||||
to demo
|
||||
;; procedure to perform the test cases
|
||||
demo-squeeze " " ""
|
||||
demo-squeeze "-" "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln "
|
||||
demo-squeeze "7" "..1111111111111111111111111111111111111111111111111111111111111117777888"
|
||||
demo-squeeze "." "I never give 'em hell, I just tell the truth, and they think it's hell. "
|
||||
demo-squeeze " " " --- Harry S Truman "
|
||||
demo-squeeze "-" " --- Harry S Truman "
|
||||
demo-squeeze "r" " --- Harry S Truman "
|
||||
end
|
||||
|
|
@ -0,0 +1,36 @@
|
|||
import unicode, strformat
|
||||
|
||||
proc squeeze(s: string; ch: Rune) =
|
||||
echo fmt"Specified character: '{ch}'"
|
||||
let original = s.toRunes
|
||||
echo fmt"Original: length = {original.len}, string = «««{s}»»»"
|
||||
var previous = Rune(0)
|
||||
var squeezed: seq[Rune]
|
||||
for rune in original:
|
||||
if rune != previous:
|
||||
squeezed.add(rune)
|
||||
previous = rune
|
||||
elif rune != ch:
|
||||
squeezed.add(rune)
|
||||
echo fmt"Squeezed: length = {squeezed.len}, string = «««{squeezed}»»»"
|
||||
echo ""
|
||||
|
||||
|
||||
const 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",
|
||||
"😍😀🙌💃😍😍😍🙌",]
|
||||
|
||||
const Chars = [@[Rune(' ')], @[Rune('-')], @[Rune('7')], @[Rune('.')],
|
||||
@[Rune(' '), Rune('-'), Rune('r')],
|
||||
@[Rune('e')], @[Rune('s')], @[Rune('a')], "😍".toRunes]
|
||||
|
||||
|
||||
for i, s in Strings:
|
||||
for ch in Chars[i]:
|
||||
s.squeeze(ch)
|
||||
|
|
@ -0,0 +1,39 @@
|
|||
<?php
|
||||
|
||||
function squeezeString($string, $squeezeChar) {
|
||||
$previousChar = null;
|
||||
$squeeze = '';
|
||||
$charArray = preg_split('//u', $string, -1, PREG_SPLIT_NO_EMPTY);
|
||||
for ($i = 0 ; $i < count($charArray) ; $i++) {
|
||||
$currentChar = $charArray[$i];
|
||||
if ($previousChar !== $currentChar || $currentChar !== $squeezeChar) {
|
||||
$squeeze .= $charArray[$i];
|
||||
}
|
||||
$previousChar = $currentChar;
|
||||
}
|
||||
return $squeeze;
|
||||
}
|
||||
|
||||
function isSqueezable($string, $squeezeChar) {
|
||||
return ($string !== squeezeString($string, $squeezeChar));
|
||||
}
|
||||
|
||||
$strings = array(
|
||||
['-', '"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln '],
|
||||
['1', '..1111111111111111111111111111111111111111111111111111111111111117777888'],
|
||||
['l', "I never give 'em hell, I just tell the truth, and they think it's hell. "],
|
||||
[' ', ' --- Harry S Truman '],
|
||||
['9', '0112223333444445555556666666777777778888888889999999999'],
|
||||
['e', "The better the 4-wheel drive, the further you'll be from help when ya get stuck!"],
|
||||
['k', "The better the 4-wheel drive, the further you'll be from help when ya get stuck!"],
|
||||
);
|
||||
foreach ($strings as $params) {
|
||||
list($char, $original) = $params;
|
||||
echo 'Original : <<<', $original, '>>> (len=', mb_strlen($original), ')', PHP_EOL;
|
||||
if (isSqueezable($original, $char)) {
|
||||
$squeeze = squeezeString($original, $char);
|
||||
echo 'Squeeze(', $char, ') : <<<', $squeeze, '>>> (len=', mb_strlen($squeeze), ')', PHP_EOL, PHP_EOL;
|
||||
} else {
|
||||
echo 'Squeeze(', $char, ') : string is not squeezable (char=', $char, ')...', PHP_EOL, PHP_EOL;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,21 @@
|
|||
use strict;
|
||||
use warnings;
|
||||
use Unicode::UCD 'charinfo';
|
||||
|
||||
for (
|
||||
['', ' '],
|
||||
['"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ', '-'],
|
||||
['..1111111111111111111111111111111111111111111111111111111111111117777888', '7'],
|
||||
["I never give 'em hell, I just tell the truth, and they think it's hell. ", '.'],
|
||||
[' --- Harry S Truman ', ' '],
|
||||
[' --- Harry S Truman ', '-'],
|
||||
[' --- Harry S Truman ', 'r']
|
||||
) {
|
||||
my($phrase,$char) = @$_;
|
||||
(my $squeeze = $phrase) =~ s/([$char])\1+/$1/g;
|
||||
printf "\nOriginal length: %d <<<%s>>>\nSqueezable on \"%s\": %s\nSqueezed length: %d <<<%s>>>\n",
|
||||
length($phrase), $phrase,
|
||||
charinfo(ord $char)->{'name'},
|
||||
$phrase ne $squeeze ? 'True' : 'False',
|
||||
length($squeeze), $squeeze
|
||||
}
|
||||
|
|
@ -0,0 +1,35 @@
|
|||
(phixonline)-->
|
||||
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
|
||||
<span style="color: #008080;">constant</span> <span style="color: #000000;">tests</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #008000;">""</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">" "</span><span style="color: #0000FF;">,</span>
|
||||
<span style="color: #008000;">`"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln `</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"-"</span><span style="color: #0000FF;">,</span>
|
||||
<span style="color: #008000;">"..1111111111111111111111111111111111111111111111111111111111111117777888"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"7"</span><span style="color: #0000FF;">,</span>
|
||||
<span style="color: #008000;">"I never give 'em hell, I just tell the truth, and they think it's hell. "</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"."</span><span style="color: #0000FF;">,</span>
|
||||
<span style="color: #008000;">" --- Harry S Truman "</span><span style="color: #0000FF;">,</span><span style="color: #008000;">" -r"</span><span style="color: #0000FF;">},</span>
|
||||
<span style="color: #000000;">fmt</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"""
|
||||
length %2d input: <<<%s>>>
|
||||
length %2d squeeze(%c): <<<%s>>>
|
||||
"""</span>
|
||||
<span style="color: #008080;">function</span> <span style="color: #000000;">squeeze</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">ch</span><span style="color: #0000FF;">)</span>
|
||||
<span style="color: #008080;">if</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)></span><span style="color: #000000;">1</span> <span style="color: #008080;">then</span>
|
||||
<span style="color: #004080;">integer</span> <span style="color: #000000;">outdx</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span>
|
||||
<span style="color: #004080;">object</span> <span style="color: #000000;">prev</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span>
|
||||
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">2</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
|
||||
<span style="color: #008080;">if</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]!=</span><span style="color: #000000;">prev</span> <span style="color: #008080;">or</span> <span style="color: #000000;">prev</span><span style="color: #0000FF;">!=</span><span style="color: #000000;">ch</span> <span style="color: #008080;">then</span>
|
||||
<span style="color: #000000;">prev</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span>
|
||||
<span style="color: #000000;">outdx</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
|
||||
<span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">outdx</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">prev</span>
|
||||
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
|
||||
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
|
||||
<span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">..</span><span style="color: #000000;">outdx</span><span style="color: #0000FF;">]</span>
|
||||
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
|
||||
<span style="color: #008080;">return</span> <span style="color: #000000;">s</span>
|
||||
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
|
||||
|
||||
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">tests</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">by</span> <span style="color: #000000;">2</span> <span style="color: #008080;">do</span>
|
||||
<span style="color: #004080;">string</span> <span style="color: #000000;">ti</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">tests</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">],</span> <span style="color: #000000;">chars</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">tests</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span>
|
||||
<span style="color: #008080;">for</span> <span style="color: #000000;">j</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">chars</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
|
||||
<span style="color: #004080;">string</span> <span style="color: #000000;">si</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">squeeze</span><span style="color: #0000FF;">(</span><span style="color: #000000;">ti</span><span style="color: #0000FF;">,</span><span style="color: #000000;">chars</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">])</span>
|
||||
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">fmt</span><span style="color: #0000FF;">,{</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">ti</span><span style="color: #0000FF;">),</span><span style="color: #000000;">ti</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">si</span><span style="color: #0000FF;">),</span><span style="color: #000000;">chars</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">],</span><span style="color: #000000;">si</span><span style="color: #0000FF;">})</span>
|
||||
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
|
||||
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
|
||||
<!--
|
||||
|
|
@ -0,0 +1,10 @@
|
|||
squeeze_( [], _, [] ).
|
||||
squeeze_( [A], _, [A] ).
|
||||
squeeze_( [A,A|T], A, R ) :- squeeze_( [A|T], A, R ).
|
||||
squeeze_( [A,A|T], B, [A|R] ) :- dif( A, B ), squeeze_( [A|T], B, R ).
|
||||
squeeze_( [A,B|T], S, [A|R] ) :- dif( A, B ), squeeze_( [B|T], S, R ).
|
||||
|
||||
squeeze( Str, SqueezeChar, Collapsed ) :-
|
||||
string_chars( Str, Chars ),
|
||||
squeeze_( Chars, SqueezeChar, Result ),
|
||||
string_chars( Collapsed, Result ).
|
||||
|
|
@ -0,0 +1,26 @@
|
|||
from itertools import groupby
|
||||
|
||||
def squeezer(s, txt):
|
||||
return ''.join(item if item == s else ''.join(grp)
|
||||
for item, grp in groupby(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",
|
||||
"😍😀🙌💃😍😍😍🙌",
|
||||
]
|
||||
squeezers = ' ,-,7,., -r,e,s,a,😍'.split(',')
|
||||
for txt, chars in zip(strings, squeezers):
|
||||
this = "Original"
|
||||
print(f"\n{this:14} Size: {len(txt)} «««{txt}»»»" )
|
||||
for ch in chars:
|
||||
this = f"Squeezer '{ch}'"
|
||||
sqz = squeezer(ch, txt)
|
||||
print(f"{this:>14} Size: {len(sqz)} «««{sqz}»»»" )
|
||||
|
|
@ -0,0 +1,37 @@
|
|||
squeeze_string <- function(string, character){
|
||||
|
||||
str_iterable <- strsplit(string, "")[[1]]
|
||||
|
||||
message(paste0("Original String: ", "<<<", string, ">>>\n",
|
||||
"Length: ", length(str_iterable), "\n",
|
||||
"Character: ", character))
|
||||
|
||||
detect <- rep(TRUE, length(str_iterable))
|
||||
|
||||
|
||||
for(i in 2:length(str_iterable)){
|
||||
|
||||
if(length(str_iterable) == 0) break
|
||||
if(str_iterable[i] != character) next
|
||||
|
||||
if(str_iterable[i] == str_iterable[i-1])
|
||||
|
||||
detect[i] <- FALSE
|
||||
}
|
||||
|
||||
squeezed_string <- paste(str_iterable[detect], collapse = "")
|
||||
|
||||
message(paste0("squeezed string: ", "<<<",squeezed_string, ">>>\n",
|
||||
"Length: ", length(str_iterable[detect])), "\n")
|
||||
|
||||
}
|
||||
|
||||
|
||||
squeeze_string("", " ")
|
||||
squeeze_string("'If I were two-faced, would I be wearing this one?' --- Abraham Lincoln ", "-")
|
||||
squeeze_string("..1111111111111111111111111111111111111111111111111111111111111117777888", "7")
|
||||
squeeze_string("I never give 'em hell, I just tell the truth, and they think it's hell. ", ".")
|
||||
squeeze_string(" --- Harry S Truman ", " ")
|
||||
squeeze_string(" --- Harry S Truman ", "-")
|
||||
squeeze_string(" --- Harry S Truman ", "r")
|
||||
squeeze_string(" Ciao Mamma, guarda come mi diverto!!! ", "!")
|
||||
|
|
@ -0,0 +1,30 @@
|
|||
/*REXX program "squeezes" all immediately repeated characters in a string (or strings). */
|
||||
@.= /*define a default for the @. array. */
|
||||
#.1= ' '; @.1=
|
||||
#.2= '-'; @.2= '"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln '
|
||||
#.3= '7'; @.3= ..1111111111111111111111111111111111111111111111111111111111111117777888
|
||||
#.4= . ; @.4= "I never give 'em hell, I just tell the truth, and they think it's hell. "
|
||||
#.5= ' '; @.5= ' --- Harry S Truman '
|
||||
#.6= '-'; @.6= @.5
|
||||
#.7= 'r'; @.7= @.5
|
||||
|
||||
do j=1; L= length(@.j) /*obtain the length of an array element*/
|
||||
say copies('═', 105) /*show a separator line between outputs*/
|
||||
if j>1 & L==0 then leave /*if arg is null and J>1, then leave. */
|
||||
say ' specified immediate repeatable character=' #.j " ('"c2x(#.j)"'x)"
|
||||
say ' length='right(L, 3) " input=«««" || @.j || '»»»'
|
||||
new= squeeze(@.j, #.j)
|
||||
w= length(new)
|
||||
say ' length='right(w, 3) " output=«««" || new || '»»»'
|
||||
end /*j*/
|
||||
exit /*stick a fork in it, we're all done. */
|
||||
/*──────────────────────────────────────────────────────────────────────────────────────*/
|
||||
squeeze: procedure; parse arg y 1 $ 2,z /*get string; get immed. repeated char.*/
|
||||
if pos(z || z, y)==0 then return y /*No repeated immediate char? Return Y*/
|
||||
/* [↑] Not really needed; a speed─up.*/
|
||||
do k=2 to length(y) /*traipse through almost all the chars.*/
|
||||
_= substr(y, k, 1) /*pick a character from Y */
|
||||
if _==right($, 1) & _==z then iterate /*Same character? Skip it.*/
|
||||
$= $ || _ /*append char., it's diff. */
|
||||
end /*j*/
|
||||
return $
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
#lang racket/base
|
||||
|
||||
(define (squeeze-string s c)
|
||||
(let loop ((cs (string->list s)) (squeezing? #f) (l 0) (acc null))
|
||||
(cond [(null? cs) (values l (list->string (reverse acc)))]
|
||||
[(and squeezing? (char=? (car cs) c)) (loop (cdr cs) #t l acc)]
|
||||
[else (loop (cdr cs) (char=? (car cs) c) (add1 l) (cons (car cs) acc))])))
|
||||
|
||||
(define (report-squeeze s c)
|
||||
(define-values (l′ s′) (squeeze-string s c))
|
||||
(printf "Squeezing ~s in «««~a»»» (length ~a)~%" c s (string-length s))
|
||||
(printf "Result: «««~a»»» (length ~a)~%~%" s′ l′))
|
||||
|
||||
(define (Determine-if-a-string-is-squeezeable)
|
||||
(report-squeeze "" #\space)
|
||||
(report-squeeze "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln " #\-)
|
||||
(report-squeeze "..1111111111111111111111111111111111111111111111111111111111111117777888" #\7)
|
||||
(report-squeeze "I never give 'em hell, I just tell the truth, and they think it's hell. " #\.)
|
||||
(define truman-sig " --- Harry S Truman ")
|
||||
(report-squeeze truman-sig #\space)
|
||||
(report-squeeze truman-sig #\-)
|
||||
(report-squeeze truman-sig #\r))
|
||||
|
||||
(module+ main
|
||||
(Determine-if-a-string-is-squeezeable))
|
||||
|
|
@ -0,0 +1,14 @@
|
|||
map {
|
||||
my $squeeze = $^phrase;
|
||||
sink $^reg;
|
||||
$squeeze ~~ s:g/($reg)$0+/$0/;
|
||||
printf "\nOriginal length: %d <<<%s>>>\nSqueezable on \"%s\": %s\nSqueezed length: %d <<<%s>>>\n",
|
||||
$phrase.chars, $phrase, $reg.uniname, $phrase ne $squeeze, $squeeze.chars, $squeeze
|
||||
},
|
||||
'', ' ',
|
||||
'"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ', '-',
|
||||
'..1111111111111111111111111111111111111111111111111111111111111117777888', '7',
|
||||
"I never give 'em hell, I just tell the truth, and they think it's hell. ", '.',
|
||||
' --- Harry S Truman ', ' ',
|
||||
' --- Harry S Truman ', '-',
|
||||
' --- Harry S Truman ', 'r'
|
||||
|
|
@ -0,0 +1,16 @@
|
|||
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 ",
|
||||
"😍😀🙌💃😍😍😍🙌",]
|
||||
squeeze_these = ["", "-", "7", ".", " -r", "😍"]
|
||||
|
||||
strings.zip(squeeze_these).each do |str, st|
|
||||
puts "original: «««#{str}»»» (size #{str.size})"
|
||||
st.chars.each do |c|
|
||||
ssq = str.squeeze(c)
|
||||
puts "#{c.inspect}-squeezed: «««#{ssq}»»» (size #{ssq.size})"
|
||||
end
|
||||
puts
|
||||
end
|
||||
|
|
@ -0,0 +1,38 @@
|
|||
fn squeezable_string<'a>(s: &'a str, squeezable: char) -> impl Iterator<Item = char> + 'a {
|
||||
let mut previous = None;
|
||||
|
||||
s.chars().filter(move |c| match previous {
|
||||
Some(p) if p == squeezable && p == *c => false,
|
||||
_ => {
|
||||
previous = Some(*c);
|
||||
true
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn main() {
|
||||
fn show(input: &str, c: char) {
|
||||
println!("Squeeze: '{}'", c);
|
||||
println!("Input ({} chars): \t{}", input.chars().count(), input);
|
||||
let output: String = squeezable_string(input, c).collect();
|
||||
println!("Output ({} chars): \t{}", output.chars().count(), output);
|
||||
println!();
|
||||
}
|
||||
|
||||
let harry = r#"I never give 'em hell, I just tell the truth, and they think it's hell.
|
||||
--- Harry S Truman"#;
|
||||
|
||||
#[rustfmt::skip]
|
||||
let inputs = [
|
||||
("", ' '),
|
||||
(r#""If I were two-faced, would I be wearing this one?" --- Abraham Lincoln "#, '-'),
|
||||
("..1111111111111111111111111111111111111111111111111111111111111117777888", '7'),
|
||||
(harry, ' '),
|
||||
(harry, '-'),
|
||||
(harry, 'r'),
|
||||
("The better the 4-wheel drive, the further you'll be from help when ya get stuck!", 'e'),
|
||||
("headmistressship", 's'),
|
||||
];
|
||||
|
||||
inputs.iter().for_each(|(input, c)| show(input, *c));
|
||||
}
|
||||
|
|
@ -0,0 +1,21 @@
|
|||
func squeeze(str, c) {
|
||||
str.gsub(Regex("(" + c.escape + ")" + '\1+'), {|s1| s1 })
|
||||
}
|
||||
|
||||
var 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 ",
|
||||
"😍😀🙌💃😍😍😍🙌"]
|
||||
|
||||
var squeeze_these = ["", "-", "7", ".", " -r", "😍"]
|
||||
|
||||
[strings, squeeze_these].zip {|str,st|
|
||||
say " original: «««#{str}»»» (length: #{str.len})"
|
||||
st.each {|c|
|
||||
var ssq = squeeze(str, c)
|
||||
say "'#{c}'-squeezed: «««#{ssq}»»» (length: #{ssq.len})"
|
||||
}
|
||||
say ''
|
||||
}
|
||||
|
|
@ -0,0 +1,27 @@
|
|||
# Set test data as a list pairing even and odd values
|
||||
# as test string and squeeze character(s) respectively.
|
||||
set test {
|
||||
{} {" "}
|
||||
{"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln } {"-"}
|
||||
{..1111111111111111111111111111111111111111111111111111111111111117777888} {"7"}
|
||||
{I never give 'em hell, I just tell the truth, and they think it's hell. } {"."} ;# '
|
||||
{ --- Harry S Truman } {" " "-" "r"}
|
||||
{The better the 4-wheel drive, the further you'll be from help when ya get stuck!} {"e"} ;# '
|
||||
{headmistressship} {"s"}
|
||||
}
|
||||
|
||||
foreach {str chrs} $test {
|
||||
foreach c $chrs {
|
||||
# Escape non-word replacement characters (such as .)
|
||||
set c [regsub -all {\W} $c {\\&}]
|
||||
|
||||
# Uses regexp lookbehind to detect repeated characters
|
||||
set re [subst -noback {($c)(\1+)}] ;# build expression
|
||||
set sub [regsub -all $re $str {\1}]
|
||||
|
||||
# Output
|
||||
puts [format "Original (length %3d): %s" [string length $str] $str]
|
||||
puts [format "Subbed (length %3d): %s" [string length $sub] $sub]
|
||||
puts ----------------------
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,42 @@
|
|||
// Returns squeezed string, original and new lengths in
|
||||
// unicode code points (not normalized).
|
||||
fn squeeze(s string, c string) (string, int, int) {
|
||||
mut r := s.runes()
|
||||
mut t := c.runes()[0]
|
||||
le, mut del := r.len, 0
|
||||
for i := le - 2; i >= 0; i-- {
|
||||
if r[i] == t && 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",
|
||||
"😍😀🙌💃😍😍😍🙌",
|
||||
]
|
||||
chars := [[' '], ['-'], ['7'], ['.'], [' ', '-', 'r'], ['e'], ['s'], ['a'], ['😍']]
|
||||
|
||||
for i, s in strings {
|
||||
for c in chars[i] {
|
||||
ss, olen, slen := squeeze(s, c)
|
||||
println("specified character = $c")
|
||||
println("original : length = ${olen:2}, string = «««$s»»»")
|
||||
println("squeezed : length = ${slen:2}, string = «««$ss»»»\n")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,33 @@
|
|||
Imports System.Linq.Enumerable
|
||||
|
||||
Module Module1
|
||||
|
||||
Function Squeeze(s As String, c As Char) As String
|
||||
If String.IsNullOrEmpty(s) Then
|
||||
Return ""
|
||||
End If
|
||||
Return s(0) + New String(Range(1, s.Length - 1).Where(Function(i) s(i) <> c OrElse s(i) <> s(i - 1)).Select(Function(i) s(i)).ToArray())
|
||||
End Function
|
||||
|
||||
Sub SqueezeAndPrint(s As String, c As Char)
|
||||
Console.WriteLine("squeeze: '{0}'", c)
|
||||
Console.WriteLine("old: {0} «««{1}»»»", s.Length, s)
|
||||
s = Squeeze(s, c)
|
||||
Console.WriteLine("new: {0} «««{1}»»»", s.Length, s)
|
||||
End Sub
|
||||
|
||||
Sub Main()
|
||||
Const QUOTE = """"
|
||||
|
||||
SqueezeAndPrint("", " ")
|
||||
SqueezeAndPrint(QUOTE & "If I were two-faced, would I be wearing this one?" & QUOTE & " --- Abraham Lincoln ", "-")
|
||||
SqueezeAndPrint("..1111111111111111111111111111111111111111111111111111111111111117777888", "7")
|
||||
SqueezeAndPrint("I never give 'em hell, I just tell the truth, and they think it's hell. ", ".")
|
||||
|
||||
Dim s = " --- Harry S Truman "
|
||||
SqueezeAndPrint(s, " ")
|
||||
SqueezeAndPrint(s, "-")
|
||||
SqueezeAndPrint(s, "r")
|
||||
End Sub
|
||||
|
||||
End Module
|
||||
|
|
@ -0,0 +1,39 @@
|
|||
import "/fmt" for Fmt
|
||||
|
||||
// Returns squeezed string, original and new lengths in
|
||||
// unicode code points (not normalized).
|
||||
var squeeze = Fn.new { |s, ch|
|
||||
var c = s.codePoints.toList
|
||||
var le = c.count
|
||||
if (le < 2) return [s, le, le]
|
||||
for (i in le-2..0) {
|
||||
if (c[i] == ch.codePoints[0] && c[i] == c[i+1]) c.removeAt(i)
|
||||
}
|
||||
var cc = c.reduce("") { |acc, cp| acc + String.fromCodePoint(cp) }
|
||||
return [cc, le, cc.count]
|
||||
}
|
||||
|
||||
var 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",
|
||||
"😍😀🙌💃😍😍😍🙌"
|
||||
]
|
||||
|
||||
var chars = [ [" "], ["-"], ["7"], ["."], [" ", "-", "r"], ["e"], ["s"], ["a"], ["😍"] ]
|
||||
|
||||
var i = 0
|
||||
for (s in strings) {
|
||||
for (ch in chars[i]) {
|
||||
var r = squeeze.call(s, ch)
|
||||
System.print("Specified character = '%(ch)'")
|
||||
System.print("original : length = %(Fmt.d(2, r[1])), string = «««%(s)»»»")
|
||||
System.print("squeezed : length = %(Fmt.d(2, r[2])), string = «««%(r[0])»»»\n")
|
||||
}
|
||||
i = i + 1
|
||||
}
|
||||
|
|
@ -0,0 +1,32 @@
|
|||
string 0;
|
||||
char C, I, J, Last;
|
||||
|
||||
proc Squeeze(Char, S); \Eliminate specified repeated characters from string
|
||||
char Char, S;
|
||||
[I:= 0; J:= 0; Last:= -1;
|
||||
loop [if S(I) # Last or Char # Last then
|
||||
[C(J):= S(I);
|
||||
if S(I) = 0 then quit;
|
||||
J:= J+1;
|
||||
];
|
||||
Last:= S(I);
|
||||
I:= I+1;
|
||||
];
|
||||
];
|
||||
|
||||
int String, K, Char;
|
||||
[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 "];
|
||||
Char:= [0, ^-, ^1, ^l, ^ , ^-, ^r];
|
||||
C:= Reserve(79+1); \space for collapsed string
|
||||
for K:= 0 to 4+2 do
|
||||
[Squeeze(Char(K), String(if K>4 then 4 else K));
|
||||
Text(0, "<<<"); Text(0, String(if K>4 then 4 else K)); Text(0, ">>> ");
|
||||
IntOut(0, I); CrLf(0);
|
||||
Text(0, "<<<"); Text(0, C); Text(0, ">>> "); IntOut(0, J); CrLf(0);
|
||||
];
|
||||
]
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
fcn squeeze(c,str){ // Works with UTF-8
|
||||
s,cc,sz,n := Data(Void,str), String(c,c), c.len(), 0; // byte buffer in case of LOTs of deletes
|
||||
while(Void != (n=s.find(cc,n))){ str=s.del(n,sz) } // and searching is faster for big strings
|
||||
s.text
|
||||
}
|
||||
|
|
@ -0,0 +1,19 @@
|
|||
strings:=T(
|
||||
T("",""),
|
||||
T("-","\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln "),
|
||||
T("7","..1111111111111111111111111111111111111111111111111111111111111117777888"),
|
||||
T(" ","I never give 'em hell, I just tell the truth, and they think it's hell. "),
|
||||
T(" "," --- Harry S Truman "),
|
||||
T("-"," --- Harry S Truman "),
|
||||
T("r"," --- Harry S Truman "),
|
||||
T("e","The better the 4-wheel drive, the further you'll be from help when ya get stuck!"),
|
||||
T("s","headmistressship"),
|
||||
T("\Ubd;","\Ubc;\Ubd;\Ubd;\Ube;"),
|
||||
);
|
||||
|
||||
foreach c,s in (strings){
|
||||
println("Squeeze: \"",c,"\"");
|
||||
println("Before: %2d <<<%s>>>".fmt(s.len(-8),s));
|
||||
sstr:=squeeze(c,s);
|
||||
println("After: %2d <<<%s>>>\n".fmt(sstr.len(-8),sstr));
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue