hacker-scripts icon indicating copy to clipboard operation
hacker-scripts copied to clipboard

potential out of range error

Open at0g opened this issue 9 years ago • 3 comments

This line: https://github.com/NARKOZ/hacker-scripts/blob/master/nodejs/hangover.js#L33

var excuse = excuses[Math.floor(Math.random() * excuses.length)];

should be:

~~var excuse = excuses[Math.floor(Math.random() * excuses.length - 1)];~~

var excuse = excuses[Math.floor(Math.random() * (excuses.length - 1))];

at0g avatar Dec 16 '15 06:12 at0g

@at0g you are wrong because Math.random() * excuses.length - 1 could give you a negative integer, the proper way is var excuse = excuses[Math.floor(Math.random() * excuses.length)%excuses.length];

xsami avatar Dec 28 '15 17:12 xsami

The current code is totally fine, your code is wrong. Math.random returns a number between 0 (inclusive) and 1 (exclusive). So Math.random() * length can never be equal length, is always lower than length.

emre1702 avatar Apr 13 '19 22:04 emre1702

That's true @emre1702 , the line of code var excuse = excuses[Math.floor(Math.random() * excuses.length)]; works perfectly fine. No change must be performed. Making my change will cause an error in case that excuses = []

xsami avatar May 28 '19 19:05 xsami