Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

potential out of range error #117

Open
at0g opened this issue Dec 16, 2015 · 3 comments
Open

potential out of range error #117

at0g opened this issue Dec 16, 2015 · 3 comments

Comments

@at0g
Copy link

at0g commented Dec 16, 2015

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))];

@xsami
Copy link

xsami commented Dec 28, 2015

@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];

@emre1702
Copy link

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.

@xsami
Copy link

xsami commented May 28, 2019

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 = []

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants