jazzyer
I’m beating myself that I can’t figure it out, but if anybody could help me/guide me through I would really appreciate it.
So the problem itself:
A binary gap within a positive integer N is any maximal sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of N.
For example, number 9 has binary representation 1001 and contains a binary gap of length 2. The number 529 has binary representation 1000010001 and contains two binary gaps: one of length 4 and one of length 3. The number 20 has binary representation 10100 and contains one binary gap of length 1. The number 15 has binary representation 1111 and has no binary gaps. The number 32 has binary representation 100000 and has no binary gaps.
Write a function:
function solution(N);
that, given a positive integer N, returns the length of its longest binary gap. The function should return 0 if N doesn't contain a binary gap.
For example, given N = 1041 the function should return 5, because N has binary representation 10000010001 and so its longest binary gap is of length 5. Given N = 32 the function should return 0, because N has binary representation '100000' and thus no binary gaps.
Write an efficient algorithm for the following assumptions:
N is an integer within the range [1..2,147,483,647].
And my first approach was:
defmodule Codility1BinaryGap do
def largest_bg(number) do
# in if statement I was trying filter all binary reps where I have at least two "1"s
if Enum.count(Integer.digits(number, 2), fn x -> div(x, 1) == 1 end) >= 2 do
# converting int to binary string represenatation: for int 68 -> "1000100"
Integer.to_string(number, 2)
# splitting "1000100" -> ["", "000", "00"]
|> String.split("1")
# counting length of each x in ["", "000", "00"]
|> Enum.map(fn x -> String.length(x) end)
# getting max
|> Enum.max()
else
0
end
end
end
It is ugly and not sufficient, but it worked except the only case where the provided number is 20 or "10100"
It has two "1"s and it passing if statement, but it is returning, obviously 2 instead of 1.
so, I’ve started differently using Enum.reduce where the main idea was:
acc = 0
#1.
if x == "0", do: acc + 1
#2.
if x == "1" -> need to insert acc to a list and reset acc to 0 and start over
#3.
at the end Enum.max() for the list where I stored everything
so having this simple example I can clearly see that acc collect 3 and 2 for "1000100":
defmodule Codility1BinaryGap do
def largest_bg(number) do
list = Integer.to_string(number, 2) |> String.graphemes()
Enum.reduce(list, 0, fn x, acc ->
if x == "0" do
(acc + 1) |> IO.inspect(label: "IF: \n")
else
0 |> IO.inspect(label: "ELSE: \n")
end
end)
end
end
ELSE:
: 0
IF:
: 1
IF:
: 2
IF:
: 3
ELSE:
: 0
IF:
: 1
IF:
: 2
So my question how properly insert acc to a list, reset it to zero and start over?
The solution is very easy in JS or Python since we can use and rebind variables
Thank you so much in advance for any possible help!
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
Documentation
While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
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
Hi everyone,
I am toying with the idea of building a “match maker” for giving personal help to people that wants to start coding.
I sta...
New
I recently noticed that Elixir’s Logger defaults its primary log level to :debug when no :logger, :level application configuration is pre...
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
I’ve got trouble wrapping my head around the order in which functions are called in this snippet (from Phoenix’s authentication):
toke...
New
Other Trending Topics
Edit: 2026 May 15 - This post is archived.
Mob is alive!!
Main docs: mob v0.7.11 — Documentation
A bit of explanation for the slightly c...
New
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
I am happy to introduce the very α version of the new programming language compiled to BEAM.
Welcome Cure.
It has literally three kille...
New
Hobbes is a low-level distributed database for the Elixir programming language.
Hobbes provides a simple, safe, and scalable storage lay...
New
Hi everyone!
The first release candidate for the Expert language server project is now available!
We’ve published a press release detai...
New
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
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
- #full-time-contract
- #podcasts-by-brainlid
- #ai
- #ecto-query
- #elixirconf-us
- #blog-post
- #elixir-ls
- #phoenix_html
- #iex
- #graphql
- #genstage
- #websockets
- #supervisor
- #advent-of-code
- #distillery
- #processes
- #elixirconf-eu
- #api
- #forms
- #metaprogramming
- #hex










Showing Posts 1 to 7- Show Best Posts
- Show All (oldest first)
- Show All (newest first)
mindok
Your accumulator in
Enum.reducecan be a more complex structure than a simple value. You could, for example, have a tuple that represents the current count of zero and a list of previous zero counts.e.g.
jazzyer
@mindok Thank you so much! I really appreciate your time and effort to help!
Let me fully absorb what is happening in your code and I will get back shortly!
Thanks again!
srowley
Enum.reduce/{2,3}is terse, and I use it plenty, but sometimes I have a hard time reading it and immediately understanding what is going on. Same goes for using it. At the end of the day it is just another way to write a recursive function, so when I am stuck it can be helpful to just write the recursive functions. On top of that, writing recursive functions to traverse a list in Elixir can be pretty straightforward thanks to pattern matching.For example:
mudasobwa
This is the perfect example of the problem when plain old good recursion is much more comprehensive and succinct than all the syntactic sugar.
kip
I think the recursive definition by @mudasobwa is what I would do. But just for fun here’s a different approach using a regex to split the number:
mudasobwa
Unfortunately, this is also vulnerable to the longest trailing zero block. It should be somewhat like:
jazzyer
Beautiful people! I am really sorry for my late response here, but I just wanted to say thanks to everyone! I really appreciate your time!
Yeah, the solution from @mudasobwa looks the most concise. Thanks again!
Also, @mindok thanks for reminding that
accin Enum.reduce() might be more complex than just value: it helped me to reconsider many things I’ve implemented using Enum.reduce()Thanks again all!