Number to Even/Odd String


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--



The winning solution was submitted by @henrik:

char count: 66

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

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:

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 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:'eo',rem(x,2)}"
"#{for x<-'13387',do:'eoeoeoeoeo',x-48}"

Submitted by @meadsteve:

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


comments powered by Disqus