16 Jul 2013, 02:25
Dave_gnome_head_isolated_pragsmall

Dave Thomas (337 posts)

  • Write a function that takes a list of dqs and prints each on a separate line, centered in a column which is the width of the longest. Make sure it works with UTF characters.

    iex> center(["cat", "zebra", "elephant"])
      cat
     zebra
    elephant
    
A Possible Solution
defmodule MyString do

  def center(strings) do
    strings 
    |> Enum.map_reduce(0, accumulate_max_length(&1, &2))
    |> center_strings_in_field
    |> Enum.each(IO.puts(&1))
  end

  # We jump through this hoop to avoid calculating the string length twice.
  # Here, we build a tuple containing the length and the string, and
  # nest it in a tuple containing the maximum length seen so far
  defp accumulate_max_length(string, max_length_so_far) do
    l = String.length(string)
    { {string, l}, max(l, max_length_so_far) }
  end

  defp center_strings_in_field({strings, field_width}) do
    strings |> Enum.map(center_one_string(field_width, &1))
  end

  defp center_one_string(field_width, {string, length}) do
    %b[#{String.duplicate(" ", div(field_width - length, 2))}#{string}]
  end
end

MyString.center %w{ cat zebra elephant }
31 Oct 2013, 15:24
Mac 128k logic board 96x96_pragsmall

Roger Turner (5 posts)


  def center(strings) do
    strings 
    |> center_strings 
    |> Enum.each &IO.puts/1
  end

  def center_strings(strings) do
    max_length = strings |> Enum.map(&String.length/1) |> Enum.max
    in_width = fn (string) ->
      l = String.length string
      div(max_length - l, 2) + l
    end
    strings |> Enum.map &(String.rjust(&1, in_width.(&1)))
  end

14 Jan 2014, 01:41
Generic-user-small

Daniel Ashton (7 posts)

defmodule Binaries do

  import Enum, only: [max: 1, map: 2, each: 2]
  import String, only: [length: 1, duplicate: 2]
  import Kernel, except: [length: 1]

  def center(str_list) do
    max_len = str_list |> map(&(length &1)) |> max
    str_list |> each &(IO.puts duplicate(" ", div(max_len - length(&1), 2)) <> &1)
  end

end
  You must be logged in to comment