Friday, January 18, 2013

Generic array slice

Not sure if anyone created(in delphi) something similar yet, which should indicate that it's usage is very limited, but here it goes...

Ever played with huge arrays and you always have to copy chunks into smaller arrays which then you want to feed to some algorithm(or pass a bunch of indexes)? if yes, then you should know by now that a "slice of TYPE" functionality kinda', shoulda' be available by now in Delphi's compiler... anyhu' with the introduction of generics, we got the options to shoot ourselves in the foot or come up with good ideas, depending on your POV.

So, what is an array slice? Well, wiki says that it grabs a slice of an array and puts it into another array, cool, but that's a bit expensive because I have to copy a block of memory into another, we can surely do better than that, right? well, with generics we can:

procedure TestSlice;
var
  LIntList: TArray<Integer>;
  LSlice: TArraySlice<Integer>;
  Index: Integer;
begin
   ///
   /// fill LIntList
   ///
   SetLength(LIntList, 10);
   for Index := Low(LIntList) to High(LIntList) do
     LIntList[Index] := Index;
   ///
   /// "grab" a slice of LIntList
   ///
   LSlice.SliceArray(LIntList, 0, 5);
   for Index := LSlice.Low to LSlice.High do
     WriteLn(LSlice[Index]);
end;

So, what are we doing in the code above? well, we're creating an array of 10 elements and we set the value of each element to be it's index in the array(I am lazy), next, we grab the first 5 elements from array as a slice and then we walk over the slice and print the elements, the output should be:
0
1
2
3
4

Pretty cool, huh? in case you're wondering, TArraySlice is a generic record, therefore initialization and finalization is done by compiler and it holds very little information(reference to "mother|main array", it's offset, count and original array size).

Here's the whole code of TArraySlice, very simple and yet powerful and incomplete (:

Not feeling like writing too much about it, after all it's a very simple thing so I'll let you have fun with it and if you find something useful to add and would like to share, feel free to comment.

Tuesday, September 18, 2012

For romanians

Salutare, am un card cadou(transmisibil) de la emag in urma unei achizitii, valoarea cardului este de RON 103, daca cineva este interesat/a sa achizitioneze un produs din categoriile enumerate mai jos pana in data de 23 septembrie(adica duminica asta), lasati e-mail-ul intr-un comment si va voi trimite codul, e-mail-ul nu va fi facut public.
Eu nu pot sa-l folosesc deoarece nu am nevoie de nimic din aceste categorii.
Masini de spalat rufe
Masini de spalat vase
Cuptoare cu microunde
Plite incorporabile
Aparate frigorifice incorporabile
Masini de spalat vase incorporabile
Masini de spalat rufe incorporabile
Espressoare incorporabile
Laptop/notebook
Televizoare


Primu' venit, primu' servit!

Blogroll(General programming and Delphi feeds)