Skip to content

Instantly share code, notes, and snippets.

@RP-3
Last active August 26, 2017 23:46
Show Gist options
  • Save RP-3/86805d4a2a95b6b8484489c8a31036e8 to your computer and use it in GitHub Desktop.
Save RP-3/86805d4a2a95b6b8484489c8a31036e8 to your computer and use it in GitHub Desktop.
Slotted Aloha Efficiency Simulation
/*jshint esversion: 6 */
const ps = [0.01, 0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4]; // these are the p vals that will be tested
const numHosts = 3; // change this to vary the number of hosts
// change this to vary the maximum number of messages a host might want to send
// unsigned 16-bit int
const maxMessageCount = 10;
// number of times to repeat the simulation for given p, numHosts and maxMessageCount
// unsigned 16-bit int
const batchSize = 1000;
/*
Returns the number of 'rounds' taken for numHosts hosts to send
a randomised number of messages less than maxMessageCount with
each host having a probability of transmitting a message of p.
*/
const runSimulation = (p, numHosts, maxMessageCount) => {
let rounds = 0;
let charCode = 65;
// initialize each host with a randomised number of messages to send
const hostMessages = new Int16Array(numHosts)
.map(() => Math.floor(Math.random()*maxMessageCount));
let messagesRemaining = hostMessages.reduce((a, b) => a + b);
// transmit a message with a probability of p, if there is a message to be sent
const transmit = (callerIndex) => {
if(hostMessages[callerIndex] === 0) return -1;
if(rounds === 0) return callerIndex;
return (Math.random() < p) ? callerIndex : -1;
};
const tick = () => {
rounds++;
// have all hosts transmit a message with a probability of p
const senders = hostMessages
.map((_, senderIndex) => transmit(senderIndex))
.filter((senderIndex) => senderIndex >= 0);
// it only worked if exactly one host transmitted
if(senders.length === 1){
hostMessages[senders[0]]--;
messagesRemaining--;
}
};
while(messagesRemaining > 0) tick();
return rounds;
};
// return the average results after running batchSize simulations
const runSimulationBatch = function(p, numHosts, maxMessageCount){
return new Uint16Array(batchSize)
.map(() => runSimulation(p, numHosts, maxMessageCount))
.reduce((a, b) => a + b) / batchSize;
};
const formatToTwoDecimals = (num) => parseFloat(Math.round(num * 100) / 100).toFixed(2);
console.log(`Running simulation for ${numHosts} hosts, each sending up to ${maxMessageCount} messages.`);
console.log('pVal | #averageTimeSlots');
ps.forEach(function(pVal){
var answer = runSimulationBatch(pVal, numHosts, maxMessageCount);
console.log(formatToTwoDecimals(pVal), '|', answer);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment