nikiiv
Hi all, I am trying to learn how to write idiomatic Elixir. I decided to write an implementation of a coding challenge I was given long time ago.
I wrote the implementation and tests, but.. I don’t like it
The problem I see is that I use too many exit checks . The algo is explained on the github page. If someone can take a look and give me some pointers I will be very very grateful.
I should note that the goal is O(n) including how any internal or external libraries could potentially affect it
defmodule CodingTest do
@moduledoc """
* Implement a method that will determinate if exists a range of
* non-negative elements in an array that sum up to a specific non-
* negative number
*
* Example 1 - targetSum 3, numbers = [1,7,1,1,1,5,6,1] - output true (the sum of the elements in range 2 to 4 is 3
* Example 2 - targetSum 7, numbers = [0,4,5,1,8,9,12,3,1] - output false (no range sums to 7)
*
"""
def solution([h|t], target_sum) do
find_solution([h],t,h, target_sum)
end
defp find_solution(_,_,target_sum, target_sum) when target_sum > 0, do: :OK
defp find_solution(_,[0 | _], _, 0), do: :OK
defp find_solution(arr, [h | t], current_sum, target_sum) when current_sum < target_sum do
#Slog.log ["case_less", arr, [h | t], current_sum, target_sum]
current_sum = current_sum + h
find_solution(arr ++ [h], t, current_sum, target_sum)
end
defp find_solution([h | t], right, current_sum, target_sum) when current_sum > target_sum do
current_sum = current_sum - h
find_solution(t, right ,current_sum, target_sum)
end
defp find_solution([], [h|t], _, target_sum), do: find_solution([h],t,h, target_sum)
defp find_solution(_,[],current_sum, target_sum) when current_sum != target_sum do
:KO
end
defp find_solution([],[],_, _), do: :KO
end
TEST
defmodule CodingTestTest do
use ExUnit.Case
doctest CodingTest
test "solution" do
assert CodingTest.solution([1,2,3,4],6) == :OK
assert CodingTest.solution([1,7,1,1,1,5,6,1],3) == :OK
assert CodingTest.solution([0,4,5,1,8,9,12,3,1],7) == :KO
assert CodingTest.solution([5,3,3,3,4,100],13) == :OK
assert CodingTest.solution([5,4,3,2,1,0,1,2,3,4,5],0) == :OK
assert CodingTest.solution([5,4,3,2,1,1,1,2,3,4,5],0) == :KO
end
end
Trending in Questions
I having some trouble figuring out if I have set myself too strict of standards for my production server. Currently I can handle 75% of r...
New
Hi everyone.
My team and I have been working on a fairly modest app based around video streaming and chat, but we’ve landed a customer t...
New
Hello,
I’m trying to build a basic Phoenix web-app, and I’d like to use Tailwind.
However, when I launch mix phx.server, I get an error...
New
I really like the adapter patterns that ecto, nebulex, waffle, etc. use and would love find something similar for a key management servic...
New
Hello folks!
So at work, we are seeing some situations where we have to define some “fixed” strings that are used across the codebase in...
New
How Can I Optimise Compile Time Dependencies
I have been building an elixir application for about 2 years now. Many modules and files ha...
New
I’m working on a small exercise involving update_in/3, and I came up with this solution:
data = %{
name: "Periodic Table",
category:...
New
Other Trending Topics
A little off-topic, but I feel like people here have a good head on their shoulders.
I used to be quite good at making software. Was luc...
New
Hey. Is there anyone here who creates agents in their apps? Not talking about using agents, but creating them. I’m finding it pretty diff...
New
I fully migrated to my own harness from Anthropic/Gemini and I think it’s time to share it. Welcome DSH, the DeepSeek Harness, fully writ...
New
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
There has been a thread to discuss the Stack Overflow Developer Survey on this forum every year since 2018, so here’s yet another one for...
New
I love Elixir. It’s one of 2 programming languages I’ve ever fallen in love with.
But I don’t use it anymore.
Serverless was the promis...
New
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #library
- #deployment
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #elixirconf
- #channels
- #exunit
- #discussion
- #code-sync
- #podcasts
- #javascript
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #ai
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #blog-post
- #elixirconf-us
- #elixir-ls
- #phoenix_html
- #iex
- #graphql
- #genstage
- #websockets
- #supervisor
- #advent-of-code
- #distillery
- #processes
- #elixirconf-eu
- #api
- #forms
- #security
- #metaprogramming











Showing Posts 1 to 10- Show Best Posts
- Show All (oldest first)
- Show All (newest first)
tomekowal
I’d do it this way:
Thoughts:
[h | t] = _nameto convey variable meaningandin guards, so havinglength(current_sublist) > 0drops one of the cases that started from scratch and merges it with the case where we have too little elements (they were doing the same thing conceptually - taking a new element from the rest of the list)We could potentially still put stop conditions first, but the check would be we would be more compiicated and I’d rather reduce the number of clauses.
stefanluptak
I would probably do it this way. You can paste that code into the Livebook app and play more with it.
It’s less effective than the pure recursion in the solution above, but I find it much more readable.
Regarding the Elixir itself, function returning
:OKor:KOis not very idiomatic. I understand you probably decided this way for the sake of simplicity, but it’s worth pointing out for future readers. My solution returns range of the correct sublist ornil.Also, naming your Elixir project with a
Testsuffix is not a good idea too, because that’s usually used for the modules that contains tests. (e.g.MyApp.RegistrationTestis a module that is testingMyApp.Registrationfunctionality).nikiiv
Actually an empty list cannot be a solution, so …
The solution I am after is O(n) and length on a list will increase the complexity.
I should’ve mentioned it. My initial solution disregarding the zero and empty list was pretty mich similar to yours
But there are some valid pointers like putting terminal cases first. Thanks
nikiiv
scan and find_index will increase the complexity. I am after O(n).
Thanks for pointing out the suffix shouldn’t be _test. I started with mix new coding_test
100phlecs
Here’s mind attempt to create less checks.
In order to maintain an O(n) runtime complexity, I reached for the :queue erlang module which allows O(1) inserts and pops for a FIFO data structure.
This allows us to maintain a ‘sliding window’ view of the list, moving the right side it when the range sum is too small and moving the left side when the range sum is too large.
Originally I reached for
Enum.reducebut because we have to process nodes within the list more than once (seewhen sum > targetfunction) recursion makes the most sense.Idiomatic Elixir usually keeps atoms lowercase, and represents empty states either with
nilor{:error, reason}, so I changed those values.As to why I changed
find_solutiontofindis just personal preferenceWithout the
:queuedata structure we could take advantage ofEnum.reverseto simulate a queue, but then the runtime is no longer O(n), but O(n * k) where k is the max length of the simulated queue (I think, feel free to correct if wrong)Edit: I found a case where my solution fails, which is the case where the range is at the very end of the list. It requires modifying the case of
when sum == target:I’m sure there’s more elegant ways to solve this, but I went with this because it’s more readable to me.
Here’s a new test case to confirm it works:
I updated the Livebook (here is where it is hosted)
eksperimental
Hi @nikiiv,
Here’s my solution.
This is as idiomatic as I could make it be.
Naming convention, guards, types, specs, pattern matching, optimization (avoids unnecessary traversing), documentation, doctests, and code formatting.
Feel free to study the code and ask questions.
Later on tonight when I’ve got a bit more of free time I will come back to make a few comments about your implementation and what’s idiomatic in Elixir.
– Cheers
All tests pass:
nikiiv
Thank you so much!
It gives a lot of color to how structure Elixir code.
The.problem with this implementation is the complexity. I am after O(n), though adding an element to the end of the list is spoiling my solution also
eksperimental
How adding elements to a list spoils your solution?
It may look complex but is the most optimal IMO.
You only keep what is needed, and stops as soon as a solution is found.
nikiiv
Because Elixir lists are single linked so adding an element to the end requires is an O(n) operation
Niki
eksperimental
My solution is of O(n²) complexity.
I cannot see how you can solve this problem linearly (O(n)).