Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Re: goto HACK

by Eily (Monsignor)
on Sep 25, 2018 at 08:29 UTC ( [id://1222952]=note: print w/replies, xml ) Need Help??


in reply to goto HACK

I need to build a hash with unixtime keys and eliminate duplicates without losing entries
why do you need to remove duplicates in the first place? Is this so that you can use them as a hash key? One simple way to do that is to append a number in the key to make them unique:
use Data::Dump qw(pp); my @array = qw<1000 1000 1000 1010 1010 1010 1020 1022 1023>; my %out; while (my ($pos, $val) = each @array) { $out{$val.':'.$pos} = { One => 1, Two => 1 }; } pp \%out; __END__ { "1000:0" => { One => 1, Two => 1 }, "1000:1" => { One => 1, Two => 1 }, "1000:2" => { One => 1, Two => 1 }, "1010:3" => { One => 1, Two => 1 }, "1010:4" => { One => 1, Two => 1 }, "1010:5" => { One => 1, Two => 1 }, "1020:6" => { One => 1, Two => 1 }, "1022:7" => { One => 1, Two => 1 }, "1023:8" => { One => 1, Two => 1 }, }
You can still access the timestamp by splitting the keys.

Here's another method, where you remove precision from the timestamp to replace it with an index (in my example below, with a precision of 10, I remove the last digit to replace it with a value between 0 and 9).

my %out; my %index; my $precision = 10; for my $val (@array) { my $rounded = $precision*(int($val/$precision)); die "Too many duplicates" if exists $index{$rounded} and $index{$rou +nded} == $precision; my $timestamp = $rounded + $index{$rounded}++; $out{$timestamp} = { One => 1, Two => 1 }; } pp \%out; __END__ { 1000 => { One => 1, Two => 1 }, 1001 => { One => 1, Two => 1 }, 1002 => { One => 1, Two => 1 }, 1010 => { One => 1, Two => 1 }, 1011 => { One => 1, Two => 1 }, 1012 => { One => 1, Two => 1 }, 1020 => { One => 1, Two => 1 }, 1021 => { One => 1, Two => 1 }, 1022 => { One => 1, Two => 1 }, }
It won't work when there are too many timestamps that round down to the same value though (eg, if you remove the last two digits, you can't have 100 times the same value) and will change a value even if it was already new (1022 and 1023 became 1021 and 1022). On the other hand it's a single loop rather than two nested loops.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1222952]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (7)
As of 2024-04-19 08:28 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found