3
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 5 years have passed since last update.

Elixirで抽選するプログラムを作った

Last updated at Posted at 2019-12-25

複数の人の中から抽選で1人を選ぶプログラムをElixirで作りました。

もっと具体的に言うと、数名でイクラを通販したんですが、おまけでカニが1杯ついてきたのでElixirの勉強がてら抽選プログラムを作成して決めてしまおうということで作りました。

環境

  • Mac OSX 10.15.2
  • IEx 1.9.1 (compiled with Erlang/OTP 22)

プログラム

参加者の名前でリストを作り、ランダムで1つ取り出すのを複数回実行し、取り出された名前が何回あったのかをカウントします。

名前をもっとも多く取り出された人がカニをゲットできることとしました。

defmodule Kani do

  def lottery(list, count) do
    gets(list, count)
    |> Enum.reduce(%{}, fn (name, acc) -> Map.update(acc, name, 1, &(&1 + 1)) end)
    |> Enum.sort()
  end


  defp get_random(list) do
    list
    |> Enum.random()
  end

  defp gets(list, count) do
    lists = for _i <- count do
      get_random(list)
    end
    lists
  end

end

実行結果(例)

iex
iex> list = ["A", "B", "C", "D", "E"]
["A", "B", "C", "D", "E"]

iex> Kani.lottery(list, 1..10_000)
[
  {"A", 1979},
  {"B", 1928},
  {"C", 2033},
  {"D", 2038},  ←カニはDさんがゲット!
  {"E", 2022}
]

まとめ

公平な抽選をした結果、ケンカすることなく @32hero さんがカニをゲットしました。

本当のところ、TaskとかAgentを使ったりmapの値でソートしたかったんですが時間切れになったのでもう少しブラッシュアップしていきたいなぁと感じています。

3
0
0

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
3
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?