Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Re: Randomly choosing from a set of alternatives with varying popularity

by siberia-man (Friar)
on Mar 29, 2022 at 09:13 UTC ( [id://11142490]=note: print w/replies, xml ) Need Help??


in reply to Randomly choosing from a set of alternatives with varying popularity

This question reminded me my old note I kept for case. It doesn't cover the actual topic but can be (or cannot be) considered as some hint.
#!/usr/bin/env perl use strict; use warnings; use List::Util qw(max); # Lower weight means higher precedence my %weight_map = ( alligator => 100, bear => 90, cat => 80, jellyfish => 10, zebra => 1, ); my $weight_lowest = max(values %weight_map) + 1; my @z0 = qw/ bear wolf jellyfish zebra dog fox cat /; my @z1 = sort { $a cmp $b } @z0; my @z2 = sort { ( $weight_map{$a} // $weight_lowest ) <=> ( $weight_map{$b} // $weight_lowest ) or $a cmp $b; } @z0; print <<RESULT; unsorted : [@z0] sorted : [@z1] weighted : [@z2] RESULT
And the execution results to:
unsorted : [bear wolf jellyfish zebra dog fox cat] sorted : [bear cat dog fox jellyfish wolf zebra] weighted : [zebra jellyfish cat bear dog fox wolf]

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others browsing the Monastery: (8)
As of 2024-03-28 23:59 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found