Forum > Beginners
FreePascal: find all 3-symbol unique substring in string
winni:
Hi!
Keep it short and simple:
--- Code: Pascal [+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i < x.length; i++) { x[i].style.maxHeight='none'; x[i].style.height = Math.min(x[i].clientHeight+15,306)+'px'; x[i].style.resize = "vertical";}};} ---program CountPattern; {$mode objfpc}{$H+} uses Classes; var sl: TStringList; s, pattern : string; i : integer;beginsl := TStringList.create;sl.Sorted:= true;sl.Duplicates:= dupIgnore; write('String: ');readln(s); for i:=1 to length(s)-2 do begin pattern:=copy (s,i,3); sl.add(pattern); end; writeln (sl.count,' unique patterns'); sl.free;end. Winni
PS.: DupIgnore does not work without Sorted.
If it is not a bug then it is strange.
Yes I know - another Delphi compatible bastard .....
Thaddy:
Well, it would be implementable, but it would be really slow. I guess that is the reason.
Thaddy:
Alternative that has just minor changes to your original code:
Use of THashSet - or if order is important TSortedSet - , For instead of foreach and the addition uses THashSet.add.
--- Code: Pascal [+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i < x.length; i++) { x[i].style.maxHeight='none'; x[i].style.height = Math.min(x[i].clientHeight+15,306)+'px'; x[i].style.resize = "vertical";}};} ---{$mode delphi}uses generics.collections;type Mnoj=THashSet<string>; // or TSortedSetvar S: string; i: integer; Mn3: Mnoj;begin Mn3 := Mnoj.Create; // or TSortedSet.Create write('String: '); readln(S); for i:=1 to length(S)-2 do Mn3.Add(S[i]+S[i+1]+S[i+2]); i:=0; writeln('Substring: '); for S in Mn3 do begin Write(S,' '); i:=i+1; end; writeln; writeln('Sum=',i); Mn3.free;end.Voila. Works like a charm.
BobDog:
This is about as short as I can do this:
--- Code: Pascal [+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i < x.length; i++) { x[i].style.maxHeight='none'; x[i].style.height = Math.min(x[i].clientHeight+15,306)+'px'; x[i].style.resize = "vertical";}};} --- program threes;vars:ansistring;i:int32; beginwhile(s<>'q') do begin write('Enter string (or q to quit): '); read(s); for i:=1 to length(s)-2 do if (pos((s[i..i+2]),s)=i) then writeln(i,' ',s[i..i+2]); readln; end;end.
Navigation
[0] Message Index
[*] Previous page