0

I really like Julia's Digits function which will return an array of the individual digits that make up the input integer (See code example). My question is, once you have this array, is there an easy way to join the individual values back into the original value passed into digits?

Now, I suppose I could just take each integer's index value and multiply by it's corresponding power of 10 and modify the array in place. Then I could use sum on the array, but is there a better way to do it?

I.E

function getDigits(x)
    return digits(x)
end

Julia> getDigits(1234)
4-element Array{Int64,1}:
4
3
2
1

function joinDigits(digitArray)
     for i in 0:length(digitArray)-1
         digitArray[i+1] = digitArray[i+1] * 10 ^ i
     end
     return sum(digitArray)

Julia> joinDigits([4,3,2,1])
1234
Community
  • 1
  • 1
Don
  • 13
  • 1
  • 4
  • The solution proposed in the OP is risky because it needlessly mutates the input vector. At least the function name should be marked with a `!`. – DNF Aug 13 '19 at 18:10
  • Yeah you're right, I need to either put an exclamation mark before the function name or make a new vector to perform my calculation. Also, my apologies for the repeat. I did truly look, I just didn't propose the question in my search the same way it was asked. – Don Aug 14 '19 at 19:23

1 Answers1

2

foldr((rest, msd) -> rest + 10*msd,x) is a one liner that does the same thing. It's terse, but probably not as clean as the for loop.

Oscar Smith
  • 5,766
  • 1
  • 20
  • 34
  • 3
    Other options are e.g. `sum(v * 10^(i-1) for (i, v) in enumerate(x))` or `parse(Int, join(reverse(x)))` (the latter is not fast but terse). The `foldr` solution can be written more shortly as `foldr((rest, msd) -> rest + 10*msd, x)`. – Bogumił Kamiński Aug 13 '19 at 16:02
  • 1
    Thanks. I was wondering how to do a 2 argument function with that syntax. The docs should probably have that in them. – Oscar Smith Aug 13 '19 at 16:04
  • If the `digits` have been reversed you can use `foldr((rest, msd) -> 10rest + msd, x)`. – Jake Ireland Oct 18 '21 at 03:23