4
2

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.

Elixirで総当たり戦プログラム

Last updated at Posted at 2022-01-10

このプログラムについて

Elixirで総当たり戦のプログラムを書く機会があり、こちらのサイトを参考にして作成しました。
参加者の人数が奇数だった際は、対戦の発生しない組が生まれるようにしてあります。
そこそこ再利用しやすいかなと思い、Qiitaで共有させていただきます。

プログラム

defmodule Util do
  def main() do
    n = "number of members: "
      |> IO.gets()
      |> String.trim()
      |> String.to_integer()

    w = 1
    x = gen_members_list_odd(n)
    y = gen_members_list_even(n)

    next_round(n, w, x, y)
  end

  defp next_round(n, w, list_x, list_y) when n >= w do
    IO.puts("Round #{w}")

    list_x = List.insert_at(list_x, length(list_x), Enum.at(list_y, length(list_x)-1))
    list_y = List.insert_at(list_y, 0,              Enum.at(list_x, 1))
    {_, list_x} = List.pop_at(list_x, 1)
    {_, list_y} = List.pop_at(list_y, length(list_y)-1)

    list_x
    |> inspect()
    |> IO.puts()

    list_y
    |> inspect()
    |> IO.puts()

    0..length(list_x)-1
    |> Enum.to_list()
    |> Enum.each(fn i ->
      IO.puts("#{Enum.at(list_x, i)}-#{Enum.at(list_y, i)}")
    end)

    next_round(n, w+1, list_x, list_y)
  end
  defp next_round(_, _, _, _), do: nil

  defp gen_members_list_odd(n) do
    1..n*2
    |> Enum.to_list()
    |> Enum.filter(&rem(&1, 2) == 1)
    |> Enum.filter(&(&1 <= n))
  end

  defp gen_members_list_even(n) when rem(n, 2) == 0 do
    1..n*2
    |> Enum.to_list()
    |> Enum.filter(&rem(&1, 2) == 0)
    |> Enum.filter(&(&1 <= n))
  end

  defp gen_members_list_even(n) do
    n-1
    |> gen_members_list_even()
    |> List.insert_at(0, nil)
  end
end

Util.main()
4
2
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
4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?