Sha256: 59c8c59d9895d6d0dca39954f77de9492f0dbfca57022585fa2406390428e0d2

Contents?: true

Size: 1.18 KB

Versions: 69

Compression:

Stored size: 1.18 KB

Contents

defmodule Transpose do
  @doc """
  Given an input text, output it transposed.

  Rows become columns and columns become rows. See https://en.wikipedia.org/wiki/Transpose.

  If the input has rows of different lengths, this is to be solved as follows:
    * Pad to the left with spaces.
    * Don't pad to the right.

  ## Examples
  iex> Transpose.transpose("ABC\nDE")
  "AD\nBE\nC"

  iex> Transpose.transpose("AB\nDEF")
  "AD\nBE\n F"
  """

  @spec transpose(String.t()) :: String.t()
  def transpose(matrix) do
    rows = String.split(matrix, "\n")

    max_length = get_longest_row_length(rows)

    rows
    |> Enum.map(fn x -> get_padded_row(x, max_length) end)
    |> Enum.map(fn x -> String.to_charlist(x) end)
    |> List.zip()
    |> Enum.map(fn x -> Tuple.to_list(x) end)
    |> Enum.map(fn x -> List.to_string(x) end)
    |> Enum.map(fn x -> String.replace(x, "*", " ") end)
    |> Enum.join("\n")
    |> String.trim_trailing()
  end

  defp get_longest_row_length(rows) do
    rows
    |> Enum.map(fn row -> String.length(row) end)
    |> Enum.max()
  end

  defp get_padded_row(row, max_length) do
    padding = String.duplicate("*", max_length - String.length(row))
    row <> padding
  end
end

Version data entries

69 entries across 69 versions & 1 rubygems

Version Path
trackler-2.2.1.180 tracks/elixir/exercises/transpose/example.exs
trackler-2.2.1.179 tracks/elixir/exercises/transpose/example.exs
trackler-2.2.1.178 tracks/elixir/exercises/transpose/example.exs
trackler-2.2.1.177 tracks/elixir/exercises/transpose/example.exs
trackler-2.2.1.176 tracks/elixir/exercises/transpose/example.exs
trackler-2.2.1.175 tracks/elixir/exercises/transpose/example.exs
trackler-2.2.1.174 tracks/elixir/exercises/transpose/example.exs
trackler-2.2.1.173 tracks/elixir/exercises/transpose/example.exs
trackler-2.2.1.172 tracks/elixir/exercises/transpose/example.exs
trackler-2.2.1.171 tracks/elixir/exercises/transpose/example.exs
trackler-2.2.1.170 tracks/elixir/exercises/transpose/example.exs
trackler-2.2.1.169 tracks/elixir/exercises/transpose/example.exs
trackler-2.2.1.167 tracks/elixir/exercises/transpose/example.exs
trackler-2.2.1.166 tracks/elixir/exercises/transpose/example.exs
trackler-2.2.1.165 tracks/elixir/exercises/transpose/example.exs
trackler-2.2.1.164 tracks/elixir/exercises/transpose/example.exs
trackler-2.2.1.163 tracks/elixir/exercises/transpose/example.exs
trackler-2.2.1.162 tracks/elixir/exercises/transpose/example.exs
trackler-2.2.1.161 tracks/elixir/exercises/transpose/example.exs
trackler-2.2.1.160 tracks/elixir/exercises/transpose/example.exs