{"id":401,"date":"2022-09-14T22:20:55","date_gmt":"2022-09-14T16:50:55","guid":{"rendered":"https:\/\/jassweb.com\/new22\/solved-java-how-do-i-generate-a-random-number-that-is-weighted-towards-certain-numbers-duplicate\/"},"modified":"2022-09-14T22:20:55","modified_gmt":"2022-09-14T16:50:55","slug":"solved-java-how-do-i-generate-a-random-number-that-is-weighted-towards-certain-numbers-duplicate-2","status":"publish","type":"post","link":"https:\/\/jassweb.com\/solved\/solved-java-how-do-i-generate-a-random-number-that-is-weighted-towards-certain-numbers-duplicate-2\/","title":{"rendered":"[Solved] JAVA \u2013 How do I generate a random number that is weighted towards certain numbers? [duplicate]"},"content":{"rendered":"<h2> Introduction <\/h2>\n<p>[ad_1]<\/p>\n<p>Generating random numbers is a common task in programming, and it can be useful for a variety of applications. However, sometimes it is desirable to generate random numbers that are weighted towards certain numbers. This can be useful for creating a more realistic random distribution, or for creating a game with a higher chance of certain outcomes. In this article, we will discuss how to generate a random number that is weighted towards certain numbers using Java. We will discuss the different methods available, and provide examples of how to use them.<\/p>\n<h2> Solution<\/h2>\n<p><\/p>\n<p>The following code snippet can be used to generate a random number that is weighted towards certain numbers:<\/p>\n<p>\/\/ Create an array of weights<br \/>\nint[] weights = {1, 2, 3, 4, 5};<\/p>\n<p>\/\/ Create a random number generator<br \/>\nRandom rand = new Random();<\/p>\n<p>\/\/ Generate a random number between 0 and the sum of the weights<br \/>\nint totalWeight = 0;<br \/>\nfor (int weight : weights) {<br \/>\n    totalWeight += weight;<br \/>\n}<br \/>\nint randomNumber = rand.nextInt(totalWeight);<\/p>\n<p>\/\/ Find the index of the weight that the random number falls into<br \/>\nint index = 0;<br \/>\nint cumulativeWeight = 0;<br \/>\nfor (int weight : weights) {<br \/>\n    cumulativeWeight += weight;<br \/>\n    if (randomNumber < cumulativeWeight) {\n        break;\n    }\n    index++;\n}\n\n\/\/ The index is the weighted random number\nint weightedRandomNumber = index; <\/p>\n<p><\/p>\n<div class=\"entry-content\" itemprop=\"text\">\n<script async src=\"https:\/\/pagead2.googlesyndication.com\/pagead\/js\/adsbygoogle.js?client=ca-pub-1088640234840270\" crossorigin=\"anonymous\"><\/script><\/p>\n<p><script><\/p>\n<p><\/script><\/p>\n<p>\n<\/p>\n<div id=\"answer-44763234\" class=\"answer js-answer accepted-answer js-accepted-answer\" data-answerid=\"44763234\" data-parentid=\"44763015\" data-score=\"0\" data-position-on-page=\"1\" data-highest-scored=\"1\" data-question-has-accepted-highest-score=\"1\" itemprop=\"acceptedAnswer\" itemscope itemtype=\"https:\/\/schema.org\/Answer\">\n<div class=\"post-layout\">\n<div class=\"votecell post-layout--left\"><\/div>\n<div class=\"answercell post-layout--right\">\n<div class=\"s-prose js-post-body\" itemprop=\"text\">\n<pre><code>public static void main(String[] args){\n    ArrayList&lt;Integer&gt; list = new ArrayList&lt;Integer&gt;();\n    list.add(5);list.add(2);\/\/ to be continued ...        \n    int randomInt = list.get((int) (Math.random() * list.size()));\n    System.out.println(randomInt);\n}\n<\/code><\/pre>\n<p>You\u2019ll get your List of values, and then you just need to pick randomly an index and get back the value <\/p>\n<p><code>Math.random()<\/code> will pick a value in [0;1[, if you multiply by the size of a <code>List<\/code> of 10 elements, you\u2019ll a value in [0;10[ , when you cast as an <code>int<\/code> you\u2019ll get 10 possibilities of index to look into the <code>List<\/code><\/p>\n<p>The <code>ArrayList<\/code> (implementation of <code>List<\/code>) <strong>allows duplicate element<\/strong> so :<br \/>\nif you add 1,2,2,3,4,5,6,7,8,9 (the order does not matter) you\u2019ll have 10 elements with each one to be find with <strong>1\/10 = 10\/100 = 10%<\/strong> of probability (aka chance), but the element 2 which appears twice will have <strong>20%<\/strong> chance to be choosen in the method, more the number appears more it\u2019s chance to be choosen increase, with as you said (number of time the number appears)\/(total number of element) (this is basic maths)<\/p>\n<\/div>\n<div class=\"mt24\"><\/div>\n<\/div>\n<p> <span class=\"d-none\" itemprop=\"commentCount\">6<\/span> <\/p>\n<\/div>\n<\/div>\n<p>solved JAVA \u2013 How do I generate a random number that is weighted towards certain numbers? [duplicate] <\/p>\n<p><script async src=\"https:\/\/pagead2.googlesyndication.com\/pagead\/js\/adsbygoogle.js?client=ca-pub-1088640234840270\" crossorigin=\"anonymous\"><\/script><\/p>\n<p><script><\/p>\n<p><\/script> <\/div>\n<p>[ad_2]<\/p>\n<p>Generating a random number that is weighted towards certain numbers can be done in Java using the Random class. The Random class provides a method called nextInt(int n) which returns a random integer between 0 (inclusive) and the specified value (exclusive). To generate a random number that is weighted towards certain numbers, you can use the following approach:<\/p>\n<ol>\n<li>Create an array of integers that represent the weights of the numbers you want to generate.<\/li>\n<li>Create a new array that contains the cumulative sum of the weights.<\/li>\n<li>Generate a random number between 0 and the sum of the weights.<\/li>\n<li>Use a binary search to find the index of the random number in the cumulative sum array.<\/li>\n<li>Return the number at the index of the cumulative sum array.<\/li>\n<\/ol>\n<p>For example, if you want to generate a random number that is weighted towards the numbers 1, 2, and 3, with weights of 0.2, 0.3, and 0.5 respectively, you can use the following code:<\/p>\n<pre><code>int[] weights = {0.2, 0.3, 0.5};\nint[] cumulativeSum = new int[weights.length];\ncumulativeSum[0] = weights[0];\nfor (int i = 1; i &lt; weights.length; i++) {\n    cumulativeSum[i] = cumulativeSum[i - 1] + weights[i];\n}\n\nRandom random = new Random();\nint randomNumber = random.nextInt(cumulativeSum[cumulativeSum.length - 1]);\nint index = Arrays.binarySearch(cumulativeSum, randomNumber);\nif (index &lt; 0) {\n    index = Math.abs(index + 1);\n}\nint number = index + 1;\n<\/code><\/pre>\n<p>In this example, the random number generated will be 1, 2, or 3 with the specified weights.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Introduction [ad_1] Generating random numbers is a common task in programming, and it can be useful for a variety of applications. However, sometimes it is desirable to generate random numbers that are weighted towards certain numbers. This can be useful for creating a more realistic random distribution, or for creating a game with a higher &#8230; <a title=\"[Solved] JAVA \u2013 How do I generate a random number that is weighted towards certain numbers? [duplicate]\" class=\"read-more\" href=\"https:\/\/jassweb.com\/solved\/solved-java-how-do-i-generate-a-random-number-that-is-weighted-towards-certain-numbers-duplicate-2\/\" aria-label=\"More on [Solved] JAVA \u2013 How do I generate a random number that is weighted towards certain numbers? [duplicate]\">Read more<\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[320],"tags":[323,1014],"class_list":["post-401","post","type-post","status-publish","format-standard","hentry","category-solved","tag-java","tag-random"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v26.5 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>[Solved] JAVA \u2013 How do I generate a random number that is weighted towards certain numbers? [duplicate] - JassWeb<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/jassweb.com\/solved\/solved-java-how-do-i-generate-a-random-number-that-is-weighted-towards-certain-numbers-duplicate-2\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"[Solved] JAVA \u2013 How do I generate a random number that is weighted towards certain numbers? [duplicate] - JassWeb\" \/>\n<meta property=\"og:description\" content=\"Introduction [ad_1] Generating random numbers is a common task in programming, and it can be useful for a variety of applications. However, sometimes it is desirable to generate random numbers that are weighted towards certain numbers. This can be useful for creating a more realistic random distribution, or for creating a game with a higher ... Read more\" \/>\n<meta property=\"og:url\" content=\"https:\/\/jassweb.com\/solved\/solved-java-how-do-i-generate-a-random-number-that-is-weighted-towards-certain-numbers-duplicate-2\/\" \/>\n<meta property=\"og:site_name\" content=\"JassWeb\" \/>\n<meta property=\"article:published_time\" content=\"2022-09-14T16:50:55+00:00\" \/>\n<meta name=\"author\" content=\"Kirat\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Kirat\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"3 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/jassweb.com\/solved\/solved-java-how-do-i-generate-a-random-number-that-is-weighted-towards-certain-numbers-duplicate-2\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/jassweb.com\/solved\/solved-java-how-do-i-generate-a-random-number-that-is-weighted-towards-certain-numbers-duplicate-2\/\"},\"author\":{\"name\":\"Kirat\",\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31\"},\"headline\":\"[Solved] JAVA \u2013 How do I generate a random number that is weighted towards certain numbers? [duplicate]\",\"datePublished\":\"2022-09-14T16:50:55+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/jassweb.com\/solved\/solved-java-how-do-i-generate-a-random-number-that-is-weighted-towards-certain-numbers-duplicate-2\/\"},\"wordCount\":522,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\/\/jassweb.com\/solved\/#organization\"},\"keywords\":[\"java\",\"random\"],\"articleSection\":[\"Solved\"],\"inLanguage\":\"en-US\"},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/jassweb.com\/solved\/solved-java-how-do-i-generate-a-random-number-that-is-weighted-towards-certain-numbers-duplicate-2\/\",\"url\":\"https:\/\/jassweb.com\/solved\/solved-java-how-do-i-generate-a-random-number-that-is-weighted-towards-certain-numbers-duplicate-2\/\",\"name\":\"[Solved] JAVA \u2013 How do I generate a random number that is weighted towards certain numbers? [duplicate] - JassWeb\",\"isPartOf\":{\"@id\":\"https:\/\/jassweb.com\/solved\/#website\"},\"datePublished\":\"2022-09-14T16:50:55+00:00\",\"breadcrumb\":{\"@id\":\"https:\/\/jassweb.com\/solved\/solved-java-how-do-i-generate-a-random-number-that-is-weighted-towards-certain-numbers-duplicate-2\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/jassweb.com\/solved\/solved-java-how-do-i-generate-a-random-number-that-is-weighted-towards-certain-numbers-duplicate-2\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/jassweb.com\/solved\/solved-java-how-do-i-generate-a-random-number-that-is-weighted-towards-certain-numbers-duplicate-2\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/jassweb.com\/solved\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"[Solved] JAVA \u2013 How do I generate a random number that is weighted towards certain numbers? [duplicate]\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/jassweb.com\/solved\/#website\",\"url\":\"https:\/\/jassweb.com\/solved\/\",\"name\":\"JassWeb\",\"description\":\"Build High-quality Websites\",\"publisher\":{\"@id\":\"https:\/\/jassweb.com\/solved\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/jassweb.com\/solved\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/jassweb.com\/solved\/#organization\",\"name\":\"Jass Web\",\"url\":\"https:\/\/jassweb.com\/solved\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png\",\"contentUrl\":\"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png\",\"width\":693,\"height\":132,\"caption\":\"Jass Web\"},\"image\":{\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/\"}},{\"@type\":\"Person\",\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31\",\"name\":\"Kirat\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1776403586\",\"contentUrl\":\"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1776403586\",\"caption\":\"Kirat\"},\"sameAs\":[\"http:\/\/jassweb.com\"],\"url\":\"https:\/\/jassweb.com\/solved\/author\/jaspritsinghghumangmail-com\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"[Solved] JAVA \u2013 How do I generate a random number that is weighted towards certain numbers? [duplicate] - JassWeb","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/jassweb.com\/solved\/solved-java-how-do-i-generate-a-random-number-that-is-weighted-towards-certain-numbers-duplicate-2\/","og_locale":"en_US","og_type":"article","og_title":"[Solved] JAVA \u2013 How do I generate a random number that is weighted towards certain numbers? [duplicate] - JassWeb","og_description":"Introduction [ad_1] Generating random numbers is a common task in programming, and it can be useful for a variety of applications. However, sometimes it is desirable to generate random numbers that are weighted towards certain numbers. This can be useful for creating a more realistic random distribution, or for creating a game with a higher ... Read more","og_url":"https:\/\/jassweb.com\/solved\/solved-java-how-do-i-generate-a-random-number-that-is-weighted-towards-certain-numbers-duplicate-2\/","og_site_name":"JassWeb","article_published_time":"2022-09-14T16:50:55+00:00","author":"Kirat","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Kirat","Est. reading time":"3 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/jassweb.com\/solved\/solved-java-how-do-i-generate-a-random-number-that-is-weighted-towards-certain-numbers-duplicate-2\/#article","isPartOf":{"@id":"https:\/\/jassweb.com\/solved\/solved-java-how-do-i-generate-a-random-number-that-is-weighted-towards-certain-numbers-duplicate-2\/"},"author":{"name":"Kirat","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31"},"headline":"[Solved] JAVA \u2013 How do I generate a random number that is weighted towards certain numbers? [duplicate]","datePublished":"2022-09-14T16:50:55+00:00","mainEntityOfPage":{"@id":"https:\/\/jassweb.com\/solved\/solved-java-how-do-i-generate-a-random-number-that-is-weighted-towards-certain-numbers-duplicate-2\/"},"wordCount":522,"commentCount":0,"publisher":{"@id":"https:\/\/jassweb.com\/solved\/#organization"},"keywords":["java","random"],"articleSection":["Solved"],"inLanguage":"en-US"},{"@type":"WebPage","@id":"https:\/\/jassweb.com\/solved\/solved-java-how-do-i-generate-a-random-number-that-is-weighted-towards-certain-numbers-duplicate-2\/","url":"https:\/\/jassweb.com\/solved\/solved-java-how-do-i-generate-a-random-number-that-is-weighted-towards-certain-numbers-duplicate-2\/","name":"[Solved] JAVA \u2013 How do I generate a random number that is weighted towards certain numbers? [duplicate] - JassWeb","isPartOf":{"@id":"https:\/\/jassweb.com\/solved\/#website"},"datePublished":"2022-09-14T16:50:55+00:00","breadcrumb":{"@id":"https:\/\/jassweb.com\/solved\/solved-java-how-do-i-generate-a-random-number-that-is-weighted-towards-certain-numbers-duplicate-2\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/jassweb.com\/solved\/solved-java-how-do-i-generate-a-random-number-that-is-weighted-towards-certain-numbers-duplicate-2\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/jassweb.com\/solved\/solved-java-how-do-i-generate-a-random-number-that-is-weighted-towards-certain-numbers-duplicate-2\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/jassweb.com\/solved\/"},{"@type":"ListItem","position":2,"name":"[Solved] JAVA \u2013 How do I generate a random number that is weighted towards certain numbers? [duplicate]"}]},{"@type":"WebSite","@id":"https:\/\/jassweb.com\/solved\/#website","url":"https:\/\/jassweb.com\/solved\/","name":"JassWeb","description":"Build High-quality Websites","publisher":{"@id":"https:\/\/jassweb.com\/solved\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/jassweb.com\/solved\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/jassweb.com\/solved\/#organization","name":"Jass Web","url":"https:\/\/jassweb.com\/solved\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/","url":"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png","contentUrl":"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png","width":693,"height":132,"caption":"Jass Web"},"image":{"@id":"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/"}},{"@type":"Person","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31","name":"Kirat","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/person\/image\/","url":"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1776403586","contentUrl":"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1776403586","caption":"Kirat"},"sameAs":["http:\/\/jassweb.com"],"url":"https:\/\/jassweb.com\/solved\/author\/jaspritsinghghumangmail-com\/"}]}},"_links":{"self":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/posts\/401","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/comments?post=401"}],"version-history":[{"count":0,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/posts\/401\/revisions"}],"wp:attachment":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/media?parent=401"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/categories?post=401"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/tags?post=401"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}