Tuesday, June 5, 2012

Generating sender-reciever pairs from a list of names (Secret Santa)

A colleague asked me to create a program, to generate sender-reciever pairs from a list of names, for a game we are playing in the office (resembles "Secret Santa"). Each person should be a sender and a reciever.
Since the colleague is not a develpoer and works with Windows I chose to implement it in JavaScript, so all she'd need is to open a browser.

You can see the code below and give it a try here.



<html> <head> <script type="text/javascript"> function makePairs() { var namesTextArea = document.getElementsByName("listOfNames")[0].value; var names = namesTextArea.split('\n'); if ( names.length % 2 != 0 ) { alert("there is an odd number of names, please make sure the number of names is even"); return false; } var html = ""; var senders = []; var recipients = []; while ( names.length > 0 ) { var first_index = Math.random() * names.length; sender = names.splice(first_index, 1); var second_index = Math.random() * names.length; recipient = names.splice(second_index, 1); html += sender + ":" + recipient + "\n"; senders.push( sender ); recipients.push( recipient ); } // make each recipient a sender and vice versa while ( senders.length > 0 ) { var sender_index = Math.random() * senders.length; newRecipient = senders.splice(sender_index, 1); var recipient_index = Math.random() * recipients.length; newSender = recipients.splice(second_index, 1); html += newSender + ":" + newRecipient + "\n"; } document.getElementsByName("pairs")[0].value = html; return false; } </script> </head> <body> <table> <tr> <td valign="top">Put a list with an even number of names here:</td> <td valign="top"><textarea id="listOfNames" name="listOfNames" cols="30" rows="50"></textarea></td> <td valign="top"><input type="button" value="Create pairs" onclick="javascript:return makePairs()"></td> <td valign="top"><textarea id="pairs" name="pairs" cols="30" rows="50"></textarea></td> </tr> </table> </body> </html>


No comments:

Post a Comment