ruby - Multiply all even indexed integers by two -


wanting take fixnum of integers , multiply even(indexed) integers two. figured best way first turn fixnum array. lets following number of 16 digits: = 4408041234567901

i know could:

a.to_s.split('') 

which return 'a' array of 'stringed' numbers. cant follow with:

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

guess i'm kinda stuck on how create method this. question may how turn group of numbers array of fixnums/integers instead of strings.

to change array, 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 multiply alternate numbers 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 little bit, can use hash find number 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, better if can try figure out on own. open irb, type a.to_s , check output. type a.to_s.chars , inspect output , on..


Comments

Popular posts from this blog

jquery - How do you format the date used in the popover widget title of FullCalendar? -

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -