সমস্যা বিবরণ
দুটি নম্বর দিয়ে একটি রেঞ্জ দেওয়া আছে। সেই রেঞ্জের মধ্যে (ইনক্লूसিভ) একটি র্যান্ডম হোল নম্বর জেনারেট করতে হবে।
সমাধান
const range = [5, 15];
const randomBetween = ([min, max]) => {
// +1 to include the max range
const random = Math.random() * (max - min + 1);
const whole = Math.floor(random) + min;
return whole;
};
for (let i = 0; i < 10; i++) {
console.log(randomBetween(range));
}
আউটপুট
13 10 6 10 12 5 14 13 11 6
নোট: প্রতিটি রানে আউটপুট ভিন্ন হবে।
ব্যাখ্যা
Math.random(): ০ (ইনক্লूसিভ) থেকে ১ (এক্সক্লুসিভ) পর্যন্ত র্যান্ডম ফ্লোট।(max - min + 1): রেঞ্জের সাইজ (ইনক্লूसিভ)।Math.floor(): ইন্টিজারে রূপান্তর।+ min: রেঞ্জের শুরুতে শিফট।
রিযুজেবল ফাংশন
const randomInt = (min, max) =>
Math.floor(Math.random() * (max - min + 1)) + min;