0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

jsで指定した割合で・確率・重み付けしたうえで抽選する

Last updated at Posted at 2022-02-22

コード

const array = [];
// 合計が100になるように値を設定してください。
const patterns = {
  "1st": 10,
  "2nd": 30,
  "3rd": 60,
};
for (var i = 0; i < 10000; i++) {
  // 0〜99までの整数
  const rand = Math.floor(Math.random() * 100);
  let result = "";
  let rate = 0;
  for (const name in patterns) {
    rate += patterns[name];
    if (rand < rate) {
      result = name;
      break;
    }
  }
  array.push(result);
}
for (const name in patterns) {
  console.log(name, array.filter((n) => n === name).length);
}

@332f さんのコメントから、 if (rand <= rate) {if (rand < rate) { に変更しました。

# console.log 例

> 1st 1095
> 2nd 3060
> 3rd 5845

> 1st 1121
> 2nd 2968
> 3rd 5911

参考

合計値が10の場合の例

const array = [];
// 合計が10になるように値を設定してください。
const patterns = {
  "1st": 1,
  "2nd": 3,
  "3rd": 6,
};
for (var i = 0; i < 10000; i++) {
  // 0〜9までの整数
  const rand = Math.floor(Math.random() * 10);
  let result = "";
  let rate = 0;
  for (const name in patterns) {
    rate += patterns[name];
    if (rand < rate) {
      result = name;
      break;
    }
  }
  array.push(result);
}
for (const name in patterns) {
  console.log(name, array.filter((n) => n === name).length);
}
0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?