Recent

Author Topic: "Compressing" a list of numbers  (Read 1167 times)

winni

  • Hero Member
  • *****
  • Posts: 720
Re: "Compressing" a list of numbers
« Reply #15 on: December 05, 2019, 04:26:39 pm »
Thanx wp!

winni

  • Hero Member
  • *****
  • Posts: 720
Re: "Compressing" a list of numbers
« Reply #16 on: December 05, 2019, 05:08:56 pm »
Hi!

Changes to your needs:


Code: Pascal  [Select]
  1. function SpecialCompress(ar : array of String) : TStringList;
  2. var st: TStringList;
  3.  i,hi,lo: Integer;
  4.  
  5.  procedure DoAdd (i,lo,hi : Integer);
  6.  begin
  7.  if lo = hi then result.add (IntToStr(lo)+ ','+st[i-1]) else
  8.          result.add (IntToStr(lo)+'-'+IntToStr(hi)+','+st[i-1]);
  9.  end;
  10.  
  11. begin
  12. st := TStringList.create;
  13. result := TStringList.create;
  14. for i := low (ar) to high(ar) do st.add(ar[i]);
  15.  
  16. hi := -1 ; lo := 0;
  17. for i := low (ar)+1 to high(ar) do
  18.      begin
  19.      if (st[i] <> st[i-1]) then
  20.          begin
  21.          DoAdd(i,lo,hi);
  22.          lo := i; hi := i;
  23.          end else hi := i ;
  24.      end; // i
  25. DoAdd(st.count-1, lo,hi);
  26. showMessage (Result.text);
  27. st.free;
  28. end;
  29.  
  30.  

Call it with
Code: Pascal  [Select]
  1. MyStringList := SpecialCompress(['2', '2', '2', '2', '3', '4', '2', '2', '4', '4', '3']);
  2.  


Winni

maurobio

  • Full Member
  • ***
  • Posts: 110
Re: "Compressing" a list of numbers
« Reply #17 on: December 05, 2019, 07:08:25 pm »
@winni,

As @wp pointed out, improving your original simple code would provide a (no doubt delightful) 'exercise in logical thinkining'. I never said I would not do it but I surely have no complaints if you did it first!  ;)

BTW, both solutions (yours and @howardpc's) work very well, they are just different implementations.

Thank you!

Best regards,
UCSD Pascal / Burroughs 6700 / Master Control Program
Lazarus 1.9.3/2.0.4 - FPC 3.0.4 on GNU/Linux Mint 19 ("Tessa"), Windows XP SP3, Windows 7 Professional, Windows 10 Home