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.119 tracks/elixir/exercises/transpose/example.exs
trackler-2.2.1.118 tracks/elixir/exercises/transpose/example.exs
trackler-2.2.1.117 tracks/elixir/exercises/transpose/example.exs
trackler-2.2.1.116 tracks/elixir/exercises/transpose/example.exs
trackler-2.2.1.115 tracks/elixir/exercises/transpose/example.exs
trackler-2.2.1.114 tracks/elixir/exercises/transpose/example.exs
trackler-2.2.1.113 tracks/elixir/exercises/transpose/example.exs
trackler-2.2.1.111 tracks/elixir/exercises/transpose/example.exs
trackler-2.2.1.110 tracks/elixir/exercises/transpose/example.exs