LoginSignup
3
2

More than 3 years have passed since last update.

ElixirでPaizaのD問題

Last updated at Posted at 2019-04-28

ElixirでPaizaのD問題を解いてみた

実際に提出したコードと問題番号を公開したいところなのだけど、Paizaは解法の公開を禁じているので、類題を作問してその解答を載せていく。

2倍にせよ

整数が入力されるので2倍して表示しなさい。

a = IO.read(:stdio, :line)
b = String.trim(a)
IO.puts String.to_integer(b) * 2 

初めてElixirで解いた問題。何もわからないところからスタートしたので、20分ぐらいかかってしまった。
Elixirは引数の括弧を省略できるのだが、省略した場合、1行に複数の処理を書く方法がわからない。

0をN回表示せよ

0をN回表示しなさい。

count = String.to_integer(String.trim(IO.read(:stdio, :line))) 

defmodule My do
  def loop(0) do
  end

  def loop(times) do
    IO.write "0"
    loop(times - 1)
  end
end

My.loop count

Elixirにはループが存在しないので、かわりに再帰を使うらしい。うまくライブラリ化すれば再帰は意識しなくてよいかも?

XをPに置換せよ。

2文字の文字列(例:XX、SS)が入力されるので、1文字目がXだった場合はPに置換して出力せよ。

str = IO.read(:stdio, :line)

if (String.at str, 0) == "X" do
  IO.write "P"
else
  IO.write String.at str, 0
end
IO.write String.at str, 1
3
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
3
2