DEV Community

Anton
Anton

Posted on

Help me solve the "Triple Trouble" challenge on Codewars with Elixir.

Triple Trouble

Create a function that will return a string that combines all of the letters of the three inputed strings in groups. Taking the first letter of all of the inputs and grouping them next to each other. Do this for every letter, see example below!

Ex) Input: "aa", "bb" , "cc" => Output: "abcabc"

Note: You can expect all of the inputs to be the same length.


You are welcome to solve the challenge in any language. I just don't know how to solve it with Elixir.

Top comments (7)

Collapse
 
antonrich profile image
Anton • Edited

Spoiler:
Guys on reddit helped me with the problem.

My final solution is this:

defmodule Triple do
  def triple_trouble(one, two, three) do
    list = [one, two, three]
    [first, second, third] = Enum.map(list, &String.graphemes/1)

    Enum.zip([first, second, third])
    |> Enum.map(&Tuple.to_list/1)
    |> List.flatten
    |> Enum.join
  end
end
Collapse
 
chenge profile image
chenge • Edited

You can add a "elixir" after 3 symbols to get color. Your solution is quite good for read.

defmodule Triple do
  def triple_trouble(one, two, three) do
    list = [one, two, three]
    [first, second, third] = Enum.map(list, &String.graphemes/1)

    Enum.zip([first, second, third])
    |> Enum.map(&Tuple.to_list/1)
    |> List.flatten
    |> Enum.join
  end
end
Collapse
 
antonrich profile image
Anton

Thanks, I added the colors.

Collapse
 
antonrich profile image
Anton

I think I'm getting closer.

defmodule Triple do
  def triple_trouble(one, two, three) do
    first = String.graphemes one
    second = String.graphemes two
    third = String.graphemes three

    List.foldl(first, [], fn char1, acc1 ->
      List.foldl(second, [], fn char2, _acc2 ->
        List.foldl(third, [], fn char3, _acc3 ->
          [char1 <> char2 <> char3] ++ acc1
        end)
      end)
    end)
  end
end

Input "what", "what", "what"
Incorrect output ["ttt", "att", "htt", "wtt"]

Collapse
 
antonrich profile image
Anton • Edited

Here's what I've got so far:

defmodule Triple do
  def triple_trouble(one, two, three) do
    first = String.graphemes one
    second = String.graphemes two
    third = String.graphemes three

    List.foldl(first, [], fn char, acc ->
      [char <> Enum.at(second, 0) <> Enum.at(third, 0)] ++ acc
    end)
  end
end

I need to make an expression out of Enum.at(second, 0) so it actually gives the right index. Don't know how to do that yet.

Collapse
 
antonrich profile image
Anton

List comprehensions are too much of an overdue, they produce more things to deal with than an actual solution.

Thinking of another solution.

Collapse
 
antonrich profile image
Anton

While, I was eating I had an idea. I haven't thought of list comprehensions. I'm gonna try them now and see if it will solve the problem.