Skip to content

Instantly share code, notes, and snippets.

@ck3g
Created February 14, 2019 16:14
Show Gist options
  • Save ck3g/faa5df7c9b380430c5a192115806f341 to your computer and use it in GitHub Desktop.
Save ck3g/faa5df7c9b380430c5a192115806f341 to your computer and use it in GitHub Desktop.
How to read from STDIN in Elixir (for HackerRank)
defmodule Solution do
#Enter your code here. Read input from STDIN. Print output to STDOUT
end
array_length = IO.read(:stdio, :line)
array = IO.read(:stdio, :line)
array_length
|> String.trim
|> String.to_integer
|> IO.puts
array
|> String.split(" ")
|> Enum.map(fn n -> String.to_integer(n) end)
|> IO.inspect
@samuelralak
Copy link

@vysogot
Copy link

vysogot commented Sep 24, 2019

input = IO.read(:stdio, :all)
  |> String.split("\n")
  |> Enum.map(fn x -> Integer.parse(x) |> elem(0) end)
  
[n | elements] = input
Solution.function_name(n, elements)

@simonewebdesign
Copy link

If you need all lines:

defmodule Solution do
  def run(n, elements) do
    IO.inspect n, label: "n"
    IO.inspect elements, label: "elements"
    IO.puts "your solution here"
  end
end

input =
  IO.read(:stdio, :all)
  |> String.split("\n")

[n | rest] = input

lines = Enum.map(rest, fn line ->
  line
  |> String.split(" ")
  |> Enum.map(&String.to_integer/1)
end)

Solution.run(n, lines)

@TB-Development
Copy link

TB-Development commented Nov 9, 2021

defmodule Solution do  
    IO.read(:stdio, :all) 
    |> String.split("\n") 
    |> Enum.map(&(String.to_integer(&1))) 
    |> Enum.sum()
    |> IO.inspect()
end

@uxjp
Copy link

uxjp commented Sep 7, 2022

https://gist.github.com/uxjp/e8e73a121f2d6563718db58eb3332c3a

Here is different solution, not using pipes all the way. I'm just beggining with Elixir, will I do everything with pipes in the future ?

@simonewebdesign
Copy link

Here is different solution, not using pipes all the way. I'm just beggining with Elixir, will I do everything with pipes in the future ?

FWIW you don't have to use the pipe operator |> at all, but it is seen as somewhat idiomatic in Elixir. See: https://elixirschool.com/en/lessons/basics/pipe_operator

@uxjp
Copy link

uxjp commented Sep 9, 2022

FWIW

Thanks for the advice Simon.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment