Search code examples
rubyarraysloopsfixnum

Multiply all even indexed integers by two


Wanting to take a fixnum of integers and multiply all even(indexed) integers by two. I figured the best way to do this is first turn fixnum into an array. So lets say the following number of 16 digits: a = 4408041234567901

I know I could:

a.to_s.split('')

Which will return 'a' to an array of 'stringed' numbers. But then I cant follow up with:

a.map!.with_index {|i,n| i.even? n*2}

Guess I'm kinda stuck on how to create a method to do this. So my question may even be how to turn that group of numbers into an array of fixnums/integers instead of strings.


Solution

  • To change it to an Array, you could do

    a = 4408041234567901
    arr = a.to_s.chars.map(&:to_i)
    # => [4, 4, 0, 8, 0, 4, 1, 2, 3, 4, 5, 6, 7, 9, 0, 1]
    

    You can also multiply alternate numbers by 2

    arr = a.to_s.chars.map.with_index {|n,i| i.even? ? n.to_i * 2 : n.to_i }
    # => [8, 4, 0, 8, 0, 4, 2, 2, 6, 4, 10, 6, 14, 9, 0, 1]
    

    Improving a little bit, you can use a Hash to find the number to be multiplied.

    h = {true => 2, false => 1}
    a.to_s.each_char.map.with_index {|n,i| n.to_i * h[i.even?]}
    

    EDIT

    I can explain each step, But it will be better if you can try to figure it out on your own. Open irb, type a.to_s and check the output. Then type a.to_s.chars and inspect the output and so on..