Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Julia: breaking number into different digits

Tags:

julia

I am interested in writing a function to convert a number to words in Julia. Such as f(1234) return to "one thousand two hundred and thirty-four".

I am getting held up on figuring out how to extract each digit and turn it back into a number. The following works, but it is pretty ugly. Thanks

x = 123456789
digits = split("$x","")
intx = zeros(length(digits))
for i=1:length(digits) intx[i]=int(digits[i]) end
intx
like image 674
Francis Smart Avatar asked Sep 14 '14 19:09

Francis Smart


2 Answers

How about the digits function in Base?

In  [23]: x = 123456789

Out [23]: 123456789

In  [24]: digits(x)

Out [24]: 9-element Array{Int64,1}:
 9
 8
 7
 6
 5
 4
 3
 2
 1
like image 123
quinnj Avatar answered Nov 10 '22 11:11

quinnj


How about this:

x = 123456789
digits = Int[]  # Empty array of Ints
while x != 0
    rem = x % 10  # Modulo division - get last digit
    push!(digits, rem)
    x = div(x,10)  # Integer division - drop last digit
end
println(digits)  # [9,8,7,6,5,4,3,2,1]

To do it in the style you were doing it (which you probably shouldn't do), you can do

x = 123456789
digits = [int(string(c)) for c in string(x)]
println(digits)  # {1,2,3,4,5,6,7,8,9}

Where c in string(x) iterates over the characters of the string, so c::Char. int(c) would give us the ASCII chracter code, so we need to change it back to a string then convert to integer.

like image 33
IainDunning Avatar answered Nov 10 '22 12:11

IainDunning