{"id":2193,"date":"2011-03-15T19:10:46","date_gmt":"2011-03-15T23:10:46","guid":{"rendered":"http:\/\/www.gubatron.com\/blog\/?p=2193"},"modified":"2011-03-15T19:10:46","modified_gmt":"2011-03-15T23:10:46","slug":"get-a-randomly-weighted-key-in-a-mapdictionaryassociative-array","status":"publish","type":"post","link":"https:\/\/www.gubatron.com\/blog\/get-a-randomly-weighted-key-in-a-mapdictionaryassociative-array\/","title":{"rendered":"Get a randomly weighted key in a Map\/Dictionary\/Associative Array"},"content":{"rendered":"<p>Here&#8217;s a very useful function to retrieve a randomly weighted key from an associative array in PHP.<\/p>\n<p>Sometimes you need to fetch random elements from a collection but you need some elements to have a little more chance than others to be fetched (business rules or whatever&#8230;)<\/p>\n<p>[php]<br \/>\nsrand(time()); \/\/dont call this inside the function or you&#8217;ll get same result always<br \/>\nfunction getRandomWeightedKey($weighted_elements, $default_key) {<br \/>\n  $weighted_ranges = array();<br \/>\n  $weight_offset = 0;<\/p>\n<p>  \/\/if you know weights are not gonna change you could<br \/>\n  \/\/move this part of the code to another place and cache it<br \/>\n  \/\/for better performance. Specially if you have a lot of weighted elements<br \/>\n  foreach ($weighted_elements as $key =&gt; $weight) {<br \/>\n    $weighted_ranges[]=array(&#8216;key&#8217;=&gt;$key,<br \/>\n                             &#8216;range&#8217;=&gt;array(intval($weight_offset),intval($weight_offset+$weight)));<br \/>\n    $weight_offset += $weight;<br \/>\n  }<\/p>\n<p>  \/\/get a random number between the 0 and the maximum<br \/>\n  $r = rand(0,$weight_offset);<\/p>\n<p>  foreach ($weighted_ranges as $range) {<br \/>\n    if ($r &gt;= $range[&#8216;range&#8217;][0] &amp;&amp; $r &lt; $range[&#8216;range&#8217;][1]) {<br \/>\n      return $range[&#8216;key&#8217;];<br \/>\n    }<br \/>\n  }<\/p>\n<p>  \/\/this shouldn&#8217;t happen but Mr. Justin Case.<br \/>\n  return $default_key;<br \/>\n}<\/p>\n<p>\/\/how to use it. (weights don&#8217;t necessarily need to add to 100,<br \/>\n\/\/but it helps me to visualize things basing weights on 100<br \/>\n$weights = array(&quot;a&quot; =&gt; 25, &quot;b&quot; =&gt; 25, &quot;c&quot; =&gt; 50);<\/p>\n<p>$randomKey = getRandomWeightedKey($weights, &quot;c&quot;);<br \/>\n[\/php]<\/p>\n<p>It should be trivial porting this code to the language of your choice. Enjoy.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Here&#8217;s a very useful function to retrieve a randomly weighted key from an associative array in PHP. Sometimes you need to fetch random elements from a collection but you need some elements to have a little more chance than others to be fetched (business rules or whatever&#8230;) [php] srand(time()); \/\/dont call this inside the function [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_publicize_message":"","jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":false,"jetpack_social_options":{"image_generator_settings":{"template":"highway","default_image_id":0,"font":"","enabled":false},"version":2}},"categories":[15],"tags":[],"class_list":["post-2193","post","type-post","status-publish","format-standard","hentry","category-code"],"jetpack_publicize_connections":[],"jetpack_featured_media_url":"","jetpack_sharing_enabled":true,"jetpack_shortlink":"https:\/\/wp.me\/p5Unzf-zn","jetpack-related-posts":[{"id":574,"url":"https:\/\/www.gubatron.com\/blog\/facebook-php-source-code\/","url_meta":{"origin":2193,"position":0},"title":"Facebook PHP Source Code","author":"gubatron","date":"August 14, 2007","format":false,"excerpt":"Ok, so one guy got to see Facebook's source code on his screen, probably due to some bad upgrade, lord knows why, the code appeared on his screen, he then copied and pasted it to some forums, and then Facebook lawyers were threatening him. Too late!, it's all over the\u2026","rel":"","context":"In &quot;Code&quot;","block_context":{"text":"Code","link":"https:\/\/www.gubatron.com\/blog\/category\/code\/"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":2851,"url":"https:\/\/www.gubatron.com\/blog\/how-to-process-thousands-of-wordpress-posts-without-hitting-or-raising-memory-limits\/","url_meta":{"origin":2193,"position":1},"title":"How to process thousands of WordPress posts without hitting or raising memory limits.","author":"gubatron","date":"November 13, 2012","format":false,"excerpt":"So you need to write a script that processes all the posts in your wordpress database, you don't need to use the stupid wordpress loop because you're not writing web facing code, you might just need to fix some metadata on each one of the posts, but every time you\u2026","rel":"","context":"In &quot;Code&quot;","block_context":{"text":"Code","link":"https:\/\/www.gubatron.com\/blog\/category\/code\/"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":4101,"url":"https:\/\/www.gubatron.com\/blog\/top-5-weighted-exercises-for-climbers\/","url_meta":{"origin":2193,"position":2},"title":"Top 5 Weighted Exercises for Climbers","author":"gubatron","date":"June 10, 2024","format":false,"excerpt":"I try doing these AFTER my climbing sessions or on rest days.\u00a0 Climbers need more than just time on the wall to excel. Incorporating specific weight exercises into your routine can significantly enhance your climbing strength and endurance. Here's a guide to the top five weight exercises that provide maximum\u2026","rel":"","context":"In &quot;Fitness&quot;","block_context":{"text":"Fitness","link":"https:\/\/www.gubatron.com\/blog\/category\/fitness\/"},"img":{"alt_text":"","src":"https:\/\/i0.wp.com\/www.gubatron.com\/blog\/wp-content\/uploads\/2024\/06\/gubatron_Climbers_need_more_than_just_time_on_the_wall_to_exc_355acba5-2f39-4c11-a8b9-6fa36c8ca796_0.jpg?fit=1024%2C1024&ssl=1&resize=350%2C200","width":350,"height":200,"srcset":"https:\/\/i0.wp.com\/www.gubatron.com\/blog\/wp-content\/uploads\/2024\/06\/gubatron_Climbers_need_more_than_just_time_on_the_wall_to_exc_355acba5-2f39-4c11-a8b9-6fa36c8ca796_0.jpg?fit=1024%2C1024&ssl=1&resize=350%2C200 1x, https:\/\/i0.wp.com\/www.gubatron.com\/blog\/wp-content\/uploads\/2024\/06\/gubatron_Climbers_need_more_than_just_time_on_the_wall_to_exc_355acba5-2f39-4c11-a8b9-6fa36c8ca796_0.jpg?fit=1024%2C1024&ssl=1&resize=525%2C300 1.5x, https:\/\/i0.wp.com\/www.gubatron.com\/blog\/wp-content\/uploads\/2024\/06\/gubatron_Climbers_need_more_than_just_time_on_the_wall_to_exc_355acba5-2f39-4c11-a8b9-6fa36c8ca796_0.jpg?fit=1024%2C1024&ssl=1&resize=700%2C400 2x"},"classes":[]},{"id":3996,"url":"https:\/\/www.gubatron.com\/blog\/the-difference-between-a-slice-and-an-array-in-rust\/","url_meta":{"origin":2193,"position":3},"title":"The difference between a Slice and an Array in Rust","author":"gubatron","date":"December 21, 2022","format":false,"excerpt":"In Rust, a slice is a reference to a contiguous section of a larger data structure, such as an array or a vector. It is represented using the syntax &[T], where T is the type of the elements in the slice. A slice does not own the data it refers\u2026","rel":"","context":"In &quot;Code&quot;","block_context":{"text":"Code","link":"https:\/\/www.gubatron.com\/blog\/category\/code\/"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":3651,"url":"https:\/\/www.gubatron.com\/blog\/codephp-jpgraph-how-to-output-your-graph-as-a-base64-encoded-image\/","url_meta":{"origin":2193,"position":4},"title":"[CODE\/PHP] JpGraph: How to output your graph as a base64 encoded image","author":"gubatron","date":"January 11, 2017","format":false,"excerpt":"Some times you just want to output the image created by your $graph object without having to create a separate .php script that would need to receive a bunch of parameters. Here's a function you can pass your $graph object right before the $graph->Stroke(); call [pastacode lang=\"php\" manual=\"function%20graphInSrc(%24graph%2C%20%24width%2C%20%24height)%20%7B%0A%20%20%24img%20%3D%20%24graph-%3EStroke(_IMG_HANDLER)%3B%0A%20%20ob_start()%3B%0A%20%20imagepng(%24img)%3B%0A%20%20%24img_data%20%3D%20ob_get_contents()%3B%0A%20%20ob_end_clean()%3B%0A%0A%20%20echo%20'%3Cimg%20width%3D%22'.%24width.'%22%20height%3D%22'.%24height.'%22%20src%3D%22data%3Aimage%2Fpng%3Bbase64%2C'.base64_encode(%24img_data).'%22%2F%3E'%3B%0A%7D\" message=\"\" highlight=\"\"\u2026","rel":"","context":"In &quot;Code&quot;","block_context":{"text":"Code","link":"https:\/\/www.gubatron.com\/blog\/category\/code\/"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":2632,"url":"https:\/\/www.gubatron.com\/blog\/javascript-get-n-random-elements-from-a-list\/","url_meta":{"origin":2193,"position":5},"title":"javascript: Get N random elements from a List","author":"gubatron","date":"January 5, 2012","format":false,"excerpt":"[javascript] \/** * Walks linearly through the list to find an element. * returns true if it's found. *\/ function elementIn(collection, element) { for (var i=0; i < collection.length; i++) { if (collection[i]==element) { return true; } } return false; } \/** * Returns a new list of n random\u2026","rel":"","context":"In &quot;Code&quot;","block_context":{"text":"Code","link":"https:\/\/www.gubatron.com\/blog\/category\/code\/"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]}],"_links":{"self":[{"href":"https:\/\/www.gubatron.com\/blog\/wp-json\/wp\/v2\/posts\/2193","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.gubatron.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.gubatron.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.gubatron.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.gubatron.com\/blog\/wp-json\/wp\/v2\/comments?post=2193"}],"version-history":[{"count":0,"href":"https:\/\/www.gubatron.com\/blog\/wp-json\/wp\/v2\/posts\/2193\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.gubatron.com\/blog\/wp-json\/wp\/v2\/media?parent=2193"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.gubatron.com\/blog\/wp-json\/wp\/v2\/categories?post=2193"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.gubatron.com\/blog\/wp-json\/wp\/v2\/tags?post=2193"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}