Skip to content

étude 6-3 and appending to a list #42

@miguelcobain

Description

@miguelcobain

In Chapter 6 there is an interlude referring to the problem of adding to the tail of a list.
To work around it the solution presented is to add to that tail and reverse afterwards.

I think a better solution would be to use the ++ operator ti add to the tail.
Solution to étude 6-3:

defmodule Teeth do

  def alert(depths) do
    alert(depths, 1, [])
  end

  def alert([], _, result) do
    result
  end

  def alert([tooth | teeth], number, result) do
    cond do
      Stats.maximum(tooth) >= 4 -> alert(teeth, number + 1, result ++ [number])
      true -> alert(teeth, number + 1, result)
    end
  end

  def pocket_depths do
    [[0], [2,2,1,2,2,1], [3,1,2,3,2,3],
    [3,1,3,2,1,2], [3,2,3,2,2,1], [2,3,1,2,1,1],
    [3,1,3,2,3,2], [3,3,2,1,3,1], [4,3,3,2,3,3],
    [3,1,1,3,2,2], [4,3,4,3,2,3], [2,3,1,3,2,2],
    [1,2,1,1,3,2], [1,2,2,3,2,3], [1,3,2,1,3,3], [0],
    [3,2,3,1,1,2], [2,2,1,1,3,2], [2,1,1,1,1,2],
    [3,3,2,1,1,3], [3,1,3,2,3,2], [3,3,1,2,3,3],
    [1,2,2,3,3,3], [2,2,3,2,3,3], [2,2,2,4,3,4],
    [3,4,3,3,3,4], [1,1,2,3,1,2], [2,2,3,2,1,3],
    [3,4,2,4,4,3], [3,3,2,1,2,3], [2,2,2,2,3,3],
    [3,2,3,2,3,2]]
  end

end

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions