[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: finding keys in a table
- From: Romulo <romulo@...>
- Date: Thu, 21 Feb 2008 17:05:24 -0300
For performance I'd just intialize all characters to zero:
local count = {}
for i = 0, 255 do
count[ string.char( i ) ] = 0
end
for c in string.gmatch( io.read( "*a" ), "." ) do
count[ c ] = count[ c ] + 1
end
-- And to iterate over them:
for i = 0, 255 do
local c = string.char( i )
if count[ c ] > 0 then
print( c, count[ c ] )
end
end
-- Or just remove the zeroes
for i = 255, 0, -1 do
local c = string.char( i )
if count[ c ] == 0 then
count[ c ] = nil
end
end
table.foreach( count, print )
*not tested* ;)
--rb
On Thu, Feb 21, 2008 at 11:24 AM, Jelle Huisman <jelle@jhnet.nl> wrote:
> Hello,
>
> I need a frequency list of all characters in a text file and I try to
> use a table for this but I'm not totally sure if this is the best way to
> solve my problem. Anyway I setup a table "count" with the characters as
> key and a counter as value. When I iterate over my data I want to:
> (1) lookup if the current character already exists as a key in the table.
> (2a) If it does exist I increment the value for key currentchar with 1
> (2b) else I add a new entry: currentchar=1
> (3) Later I sort the table and print my freq.list.
>
> The two questions I have are: is this the best/most efficient/fastest
> way to do this?
> Second: How do I check if a key exists? (I don't think I can use an
> inverted table because I'll end up with duplicate keys, or not?)
>
> Thanks for some advice,
>
> Jelle
>
>