Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

(COMPLETE) Number Finder #2

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions exercises/number_finder.livemd
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,20 @@ defmodule NumberFinder do
iex> NumberFinder.smallest([2, 2, 3, 4, 10, 20, -3])
-3
"""

## Input - Output: inputs a list - outputs a number
## Potential solution: go through the list and
## keep the smallest number found in the accumulator.
## If the current number is smaller than the current accumulator, update the accumulator

def smallest(number_list) do
## Enum.min(number_list) - This works
## Enum.reduce([1, 2, 3], fn(number, acc) -> if number < acc do number end end)
Enum.reduce(number_list, 4, fn number, smallest ->
if number < smallest do

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What is your else case?

Remember that if number < smallest is false if will return nil. Then your next accumulator is nil and your code will run into problems.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Your initial accumulator is 4 here. That works because it's larger than any element in the list. You made a comment about not having a good neutral accumulator, so what if your accumulator was just the first element in your list?

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you! Concepts start to be clarified in my head. Yesterday's class also helped a lot.

number
end
end)
end

@doc """
Expand All @@ -60,6 +73,31 @@ defmodule NumberFinder do
def largest(number_list) do
end
end

NumberFinder.smallest([2, 2, 3, 4])
```

```elixir
def TestModule
def smallest(number_list) do
Enum.reduce(number_list, smallest, fn number, smallest -> IO.puts(number, smallest) end)
# if number < smallest do smallest = number end end)
end
end
TestModule.smallest([1,2])


```

```elixir
Enum.reduce([1, 2, 3], acc, fn number, acc ->
if number < acc do
acc = number
end
end)

# numbernumber + acc end)
# Enum.reduce([1, 2, 3], 0, fn(x, acc) -> x + acc end)
```

## Up Next
Expand Down