Number to Even/Odd String

Instructions

Use the IO.gets function to gather an integer from user input and return a string where EACH digit is converted to an "e" or an "o" string character. This string character is determined by whether the integer digit at that index is odd or even.

For example:

iex> --enter your code here--
13387
"oooeo"

Solutions

Winner

The winning solution was submitted by @henrik:

char count: 66

iex(1)> "#{for x<-(to_char_list IO.gets''),x>10,do: Enum.at'eo',rem(x,2)}"
12231
"oeeoo"

Starting in the middle it IO.gets the user’s input, and converts this binary string into a character list (a list of integer values). Note that the last character will be a \n which is ASCII value 10.

It uses a comprehension (for x<-...) to take each integer from our list and apply the x>10 filter. As all the string values are greater than 10 they pass through, where as the \n escapes. The values are then passed to the body of our comprehension do: Enum.at....

In the body, the integer value bound to x is divided by 2 determining whether it is even or odd. This remainder value is then used by Enum.at to return the corresponding "e" or "o" character.

Finally the code is wrapped in an interpolated string "#{}" to convert the character list into a binary string.

Honourable mentions

Submitted by @henrik:

"#{for x<-'13387',do: Enum.at'eo',rem(x,2)}"
"#{Enum.map'13387',&%{0=>?e,1=>?o}[rem(&1,2)]}"
"#{for x<-'13387',do: Enum.at'eoeoeoeoeo',x-48}"

Submitted by @meadsteve:

import String;for s<-:stdio|>IO.gets|>codepoints,s !="\n",x=s|>to_integer|>rem(2),do: Enum.at'eo',x

Resources

comments powered by Disqus