Determine if a string is collapsible: Difference between revisions

Content deleted Content added
Hout (talk | contribs)
m →‎{{header|Python}}: Added predicate test output.
Line 576: Line 576:
<lang fsharp>
<lang fsharp>
// Collapse a String. Nigel Galloway: June 9th., 2020
// 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 thesame.
let collapse n=if String.length n=0 then None else
let isCollapsible n=n|>Seq.pairwise|>Seq.tryFind(fun(n,g)->n=g)
let fN=let mutable g=n.[0] in (fun n->if n=g then false else g<-n; true)
//As per the task description a function which 'if the string is collapsable And if so, collapses the string (by removing immediately repeated characters).
let fG=n.[0..0]+System.String(n.[1..].ToCharArray()|>Array.filter fN)
let collapse n=match isCollapsible n with
if fG.Length=n.Length then None else Some fG
Some _->let i=Seq.head n
let fN=let mutable g=i in (fun n->if n=g then false else g<-n; true)
let g=System.String([|yield i;yield! Seq.tail n|>Seq.filter fN|])
printfn "<<<%s>>> (length %d) colapses to <<<%s>>> (length %d)" n n.Length g g.Length
| _->printfn "<<<%s>>> (length %d) does not colapse" n n.Length


collapse ""
let isCollapsible n=match colapse n with
collapse "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln "
Some g->printfn "<<<%s>>> (length %d) collapses to <<<%s>>> (length %d)" n n.Length g g.Length
collapse "..1111111111111111111111111111111111111111111111111111111111111117777888"
|_->printfn "<<<%s>>> (length %d) does not collapse" n n.Length
collapse "I never give 'em hell, I just tell the truth, and they think it's hell. "

collapse " --- Harry S Truman "
isCollapsible ""
collapse "withoutConsecutivelyRepeatedCharacters"
isCollapsible "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln "
isCollapsible "..1111111111111111111111111111111111111111111111111111111111111117777888"
isCollapsible "I never give 'em hell, I just tell the truth, and they think it's hell. "
isCollapsible " --- Harry S Truman "
isCollapsible "withoutConsecutivelyRepeatedCharacters"
</lang>
</lang>
{{out}}
{{out}}
Line 601: Line 602:
<<<withoutConsecutivelyRepeatedCharacters>>> (length 38) does not collapse
<<<withoutConsecutivelyRepeatedCharacters>>> (length 38) does not collapse
</pre>
</pre>

=={{header|Factor}}==
=={{header|Factor}}==
<lang factor>USING: formatting io kernel sbufs sequences strings ;
<lang factor>USING: formatting io kernel sbufs sequences strings ;