papasmurf22

papasmurf22

Find the first recurring character in a string

hi everyone,
I have the simple problem of “Find the first recurring character in a string” that I can easily think about solving in an OO language with a for loop and a counter variable but am wondering how you would solve this “the functional way”.

i.e: If “ABCDAHWX” was passed in to the function as argument you would return the first recurring character “A”.

What is the FP way to do this in elixir? Would u use recursion or maybe matching on function parameters?

Thank you for your time

Most Liked

LostKobrakai

LostKobrakai

I’d use Enum.reduce_while:

result = Enum.reduce_while(String.graphemes("ABCDAHWX"), [], fn character, prev ->
  if character in prev, do: {:halt, character}, else: {:cont, [character | prev]}
end)

with char when is_binary(char) <- result do
  char
else
  [_ | _] -> :no_duplicates
end
peerreynders

peerreynders

https://www.regular-expressions.info/

https://regexr.com/ set the RegEx Engine to PCRE (Perl Compatible Regular Expressions)

idi527

idi527

Of course, I expect the regular expression version to be faster

iex(2)> :timer.tc fn -> Enum.each 1..1_000, fn _ -> Test.first_recurring("ABCDAHWX") end end
{1876, :ok}
iex(4)> reg = ~r/(.).*?\1/
~r/(.).*?\1/
iex(6)> :timer.tc fn -> Enum.each 1..1_000, fn _ -> Regex.run(reg, "ABCDAHWX") end end
{5585, :ok}
iex(7)> :timer.tc fn -> Enum.each 1..1_000, fn _ -> Regex.run(reg, "ABCDAHWX") end end
{3823, :ok}
iex(8)> :timer.tc fn -> Enum.each 1..1_000, fn _ -> Regex.run(reg, "ABCDAHWX") end end
{4058, :ok}

Although the regex pattern is not compiled, but the elixir version (above) is not optimized either. I usually find regexes to be much slower than erlang’s pattern matching since they do much more work.

jamesnorton

jamesnorton

I would uses a regular expression for this.

iex(1)> reg = ~r/(.).*?\1/
~r/(.).*?\1/
iex(2)> s = "ABCDAHWX"
"ABCDAHWX"
iex(3)> Regex.run(reg, s)
["ABCDA", "A"]

The regular expression uses a capture group to match a single character and then a back reference to the captured value to match the repeated character.

idi527

idi527

Same way, probably.

defmodule Test do
  def first_recurring(str) do
    do_first_recurring(str, [])
  end

  defp do_first_recurring(<<letter, rest::bytes>>, chars) do
    if letter in chars do
      <<letter>>
    else
      do_first_recurring(rest, [letter | chars])
    end
  end
  defp do_first_recurring("", _chars), do: nil
end

Not particularly efficient, but should provide you with a general idea.

iex(2)> Test.first_recurring("ABCDAHWX")
"A"

Where Next?

Popular in Questions Top

srinivasu
How to handle excepions in elixir? Suppose i have A, B, C ,D, E modules. and each module has get() function. A.get() method will call th...
New
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
New
lk-geimfari
What is most correct way to open, read and parse JSON file with poison? For example if we have example.json file in root of some projec...
New
rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list....
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New

Other popular topics Top

senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
ycv005
I have followed this StackOverflow post to install the specific version of Erlang. And When I am running mix ecto.setup then getting fol...
New
New
lk-geimfari
What is most correct way to open, read and parse JSON file with poison? For example if we have example.json file in root of some projec...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
msaraiva
Surface is an experimental library built on top of Phoenix LiveView and its new LiveComponent API that aims to provide a more declarative...
564 42633 214
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New

We're in Beta

About us Mission Statement