{"id":432,"date":"2024-08-26T15:00:00","date_gmt":"2024-08-26T15:00:00","guid":{"rendered":"https:\/\/fdswebdesign.com\/?p=432"},"modified":"2024-10-15T23:32:28","modified_gmt":"2024-10-15T23:32:28","slug":"generating-unique-random-numbers-in-javascript-using-sets","status":"publish","type":"post","link":"https:\/\/fdswebdesign.com\/index.php\/2024\/08\/26\/generating-unique-random-numbers-in-javascript-using-sets\/","title":{"rendered":"Generating Unique Random Numbers In JavaScript Using Sets"},"content":{"rendered":"

Generating Unique Random Numbers In JavaScript Using Sets<\/title><\/p>\n<article>\n<header>\n<h1>Generating Unique Random Numbers In JavaScript Using Sets<\/h1>\n<address>Amejimaobari Ollornwi<\/address>\n<p> 2024-08-26T15:00:00+00:00<br \/>\n 2024-10-15T23:05:45+00:00<br \/>\n <\/header>\n<p>JavaScript comes with a lot of built-in functions that allow you to carry out so many different operations. One of these built-in functions is the <code>Math.random()<\/code> method, which generates a random floating-point number that can then be manipulated into integers.<\/p>\n<p>However, if you wish to generate a series of unique random numbers and create more random effects in your code, you will need to come up with a custom solution for yourself because the <code>Math.random()<\/code> method on its own cannot do that for you.<\/p>\n<p>In this article, we\u2019re going to be learning how to circumvent this issue and generate a series of unique random numbers using the <code>Set<\/code> object in JavaScript, which we can then use to create more randomized effects in our code.<\/p>\n<p><strong>Note<\/strong>: <em>This article assumes that you know how to generate random numbers in JavaScript, as well as how to work with sets and arrays.<\/em><\/p>\n<div data-audience=\"non-subscriber\" data-remove=\"true\" class=\"feature-panel-container\">\n<aside class=\"feature-panel\">\n<div class=\"feature-panel-left-col\">\n<div class=\"feature-panel-description\">\n<p>Roll up your sleeves and <strong>boost your UX skills<\/strong>! Meet <strong><a data-instant href=\"https:\/\/smart-interface-design-patterns.com\/\">Smart Interface Design Patterns<\/a><\/strong> \ud83c\udf63, a 10h video library by Vitaly Friedman. <strong>100s of real-life examples<\/strong> and live UX training. <a href=\"https:\/\/www.youtube.com\/watch?v=3mwZztmGgbE\">Free preview<\/a>.<\/p>\n<p><a data-instant href=\"https:\/\/smart-interface-design-patterns.com\/\" class=\"btn btn--green btn--large\">Jump to table of contents \u21ac<\/a><\/div>\n<\/div>\n<div class=\"feature-panel-right-col\"><a data-instant href=\"https:\/\/smart-interface-design-patterns.com\/\" class=\"feature-panel-image-link\"><\/p>\n<div class=\"feature-panel-image\">\n<img decoding=\"async\" loading=\"lazy\" class=\"feature-panel-image-img lazyload\" src=\"data:image\/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==\" alt=\"Feature Panel\" width=\"690\" height=\"790\" data-src=\"https:\/\/archive.smashing.media\/assets\/344dbf88-fdf9-42bb-adb4-46f01eedd629\/8c98e7f9-8e62-4c43-b833-fc6bf9fea0a9\/video-course-smart-interface-design-patterns-vitaly-friedman.jpg\"><\/p>\n<\/div>\n<p><\/a>\n<\/div>\n<\/aside>\n<\/div>\n<h2 id=\"generating-a-unique-series-of-random-numbers\">Generating a Unique Series of Random Numbers<\/h2>\n<p>One of the ways to generate a unique series of random numbers in JavaScript is by using <code>Set<\/code> objects. The reason why we\u2019re making use of sets is because the elements of a set are unique. We can iteratively generate and insert random integers into sets until we get the number of integers we want.<\/p>\n<p>And since sets do not allow duplicate elements, they are going to serve as a filter to remove all of the duplicate numbers that are generated and inserted into them so that we get a set of unique integers.<\/p>\n<p>Here\u2019s how we are going to approach the work:<\/p>\n<ol>\n<li>Create a <code>Set<\/code> object.<\/li>\n<li>Define how many random numbers to produce and what range of numbers to use.<\/li>\n<li>Generate each random number and immediately insert the numbers into the <code>Set<\/code> until the <code>Set<\/code> is filled with a certain number of them.<\/li>\n<\/ol>\n<p>The following is a quick example of how the code comes together:<\/p>\n<div class=\"break-out\">\n<pre><code class=\"language-javascript\">function generateRandomNumbers(count, min, max) {\n \/\/ 1: Create a `Set` object\n let uniqueNumbers = new Set();\n while (uniqueNumbers.size < count) {\n \/\/ 2: Generate each random number\n uniqueNumbers.add(Math.floor(Math.random() * (max - min + 1)) + min);\n }\n \/\/ 3: Immediately insert them numbers into the Set...\n return Array.from(uniqueNumbers);\n}\n\/\/ ...set how many numbers to generate from a given range\nconsole.log(generateRandomNumbers(5, 5, 10));\n<\/code><\/pre>\n<\/div>\n<p>What the code does is create a new <code>Set<\/code> object and then generate and add the random numbers to the set until our desired number of integers has been included in the set. The reason why we\u2019re returning an array is because they are easier to work with.<\/p>\n<p>One thing to note, however, is that the number of integers you want to generate (represented by <code>count<\/code> in the code) should be less than the upper limit of your range plus one (represented by <code>max + 1<\/code> in the code). Otherwise, the code will run forever. You can add an <code>if statement<\/code> to the code to ensure that this is always the case:<\/p>\n<div class=\"break-out\">\n<pre><code class=\"language-javascript\">function generateRandomNumbers(count, min, max) {\n \/\/ if statement checks that `count` is less than `max + 1`\n if (count > max + 1) {\n return \"count cannot be greater than the upper limit of range\";\n } else {\n let uniqueNumbers = new Set();\n while (uniqueNumbers.size < count) {\n uniqueNumbers.add(Math.floor(Math.random() * (max - min + 1)) + min);\n }\n return Array.from(uniqueNumbers);\n }\n}\nconsole.log(generateRandomNumbers(5, 5, 10));\n<\/code><\/pre>\n<\/div>\n<div class=\"partners__lead-place\"><\/div>\n<h2 id=\"using-the-series-of-unique-random-numbers-as-array-indexes\">Using the Series of Unique Random Numbers as Array Indexes<\/h2>\n<p>It is one thing to generate a series of random numbers. It\u2019s another thing to use them.<\/p>\n<p>Being able to use a series of random numbers with arrays unlocks so many possibilities: you can use them in shuffling playlists in a music app, randomly sampling data for analysis, or, as I did, <a href=\"https:\/\/github.com\/jimavictor\/remoji\">shuffling the tiles in a memory game<\/a>.<\/p>\n<p>Let\u2019s take the code from the last example and work off of it to return random letters of the alphabet. First, we\u2019ll construct an array of letters:<\/p>\n<div class=\"break-out\">\n<pre><code class=\"language-javascript\">const englishAlphabets = [\n 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', \n 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'\n];\n\n\/\/ rest of code\n<\/code><\/pre>\n<\/div>\n<p>Then we <code>map<\/code> the letters in the range of numbers:<\/p>\n<div class=\"break-out\">\n<pre><code class=\"language-javascript\">const englishAlphabets = [\n 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', \n 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'\n];\n\n\/\/ generateRandomNumbers()\n\nconst randomAlphabets = randomIndexes.map((index) => englishAlphabets[index]);\n<\/code><\/pre>\n<\/div>\n<p>In the original code, the <code>generateRandomNumbers()<\/code> function is logged to the console. This time, we\u2019ll construct a new variable that calls the function so it can be consumed by <code>randomAlphabets<\/code>:<\/p>\n<div class=\"break-out\">\n<pre><code class=\"language-javascript\">const englishAlphabets = [\n 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', \n 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'\n];\n\n\/\/ generateRandomNumbers()\n\nconst randomIndexes = generateRandomNumbers(5, 0, 25);\nconst randomAlphabets = randomIndexes.map((index) => englishAlphabets[index]);\n<\/code><\/pre>\n<\/div>\n<p>Now we can log the output to the console like we did before to see the results:<\/p>\n<div class=\"break-out\">\n<pre><code class=\"language-javascript\">const englishAlphabets = [\n 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', \n 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'\n];\n\n\/\/ generateRandomNumbers()\n\nconst randomIndexes = generateRandomNumbers(5, 0, 25);\nconst randomAlphabets = randomIndexes.map((index) => englishAlphabets[index]);\nconsole.log(randomAlphabets);\n<\/code><\/pre>\n<\/div>\n<p>And, when we put the <code>generateRandomNumbers<\/code><code>()<\/code> function definition back in, we get the final code:<\/p>\n<div class=\"break-out\">\n<pre><code class=\"language-javascript\">const englishAlphabets = [\n 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', \n 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'\n];\nfunction generateRandomNumbers(count, min, max) {\n if (count > max + 1) {\n return \"count cannot be greater than the upper limit of range\";\n } else {\n let uniqueNumbers = new Set();\n while (uniqueNumbers.size < count) {\n uniqueNumbers.add(Math.floor(Math.random() * (max - min + 1)) + min);\n }\n return Array.from(uniqueNumbers);\n }\n}\nconst randomIndexes = generateRandomNumbers(5, 0, 25);\nconst randomAlphabets = randomIndexes.map((index) => englishAlphabets[index]);\nconsole.log(randomAlphabets);\n<\/code><\/pre>\n<\/div>\n<p>So, in this example, we created a new array of alphabets by randomly selecting some letters in our <code>englishAlphabets<\/code> array.<\/p>\n<p>You can pass in a count argument of <code>englishAlphabets.length<\/code> to the <code>generateRandomNumbers<\/code> function if you desire to shuffle the elements in the <code>englishAlphabets<\/code> array instead. This is what I mean:<\/p>\n<pre><code class=\"language-javascript\">generateRandomNumbers(englishAlphabets.length, 0, 25);\n<\/code><\/pre>\n<div class=\"partners__lead-place\"><\/div>\n<h2 id=\"wrapping-up\">Wrapping Up<\/h2>\n<p>In this article, we\u2019ve discussed how to create randomization in JavaScript by covering how to generate a series of unique random numbers, how to use these random numbers as indexes for arrays, and also some practical applications of randomization.<\/p>\n<p>The best way to learn anything in software development is by consuming content and reinforcing whatever knowledge you\u2019ve gotten from that content by practicing. So, don\u2019t stop here. Run the examples in this tutorial (if you haven\u2019t done so), play around with them, come up with your own unique solutions, and also don\u2019t forget to share your good work. Ciao!<\/p>\n<div class=\"signature\">\n <img decoding=\"async\" src=\"data:image\/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==\" alt=\"Smashing Editorial\" width=\"35\" height=\"46\" loading=\"lazy\" class=\"lazyload\" data-src=\"https:\/\/www.smashingmagazine.com\/images\/logo\/logo--red.png\"><br \/>\n <span>(yk)<\/span>\n<\/div>\n<\/article>\n","protected":false},"excerpt":{"rendered":"<p>Generating Unique Random Numbers In JavaScript Using Sets Generating Unique Random Numbers In JavaScript Using Sets Amejimaobari Ollornwi 2024-08-26T15:00:00+00:00 2024-10-15T23:05:45+00:00 JavaScript comes with a lot of built-in functions that allow you to carry out so many different operations. One of these built-in functions is the Math.random() method, which generates a random floating-point number that can…<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[10],"tags":[],"class_list":["post-432","post","type-post","status-publish","format-standard","hentry","category-javascript"],"_links":{"self":[{"href":"https:\/\/fdswebdesign.com\/index.php\/wp-json\/wp\/v2\/posts\/432","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/fdswebdesign.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/fdswebdesign.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/fdswebdesign.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/fdswebdesign.com\/index.php\/wp-json\/wp\/v2\/comments?post=432"}],"version-history":[{"count":1,"href":"https:\/\/fdswebdesign.com\/index.php\/wp-json\/wp\/v2\/posts\/432\/revisions"}],"predecessor-version":[{"id":433,"href":"https:\/\/fdswebdesign.com\/index.php\/wp-json\/wp\/v2\/posts\/432\/revisions\/433"}],"wp:attachment":[{"href":"https:\/\/fdswebdesign.com\/index.php\/wp-json\/wp\/v2\/media?parent=432"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/fdswebdesign.com\/index.php\/wp-json\/wp\/v2\/categories?post=432"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/fdswebdesign.com\/index.php\/wp-json\/wp\/v2\/tags?post=432"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}