2012-10-26 11 views
15

可能性の重複:
Turning long fixed number to array Ruby整数の数字をどのように反復するのですか?

まあ、私はRubyで整数の桁数を反復しなければなりません。今は配列に分割して、それを繰り返していただけです。しかし、私はこれを行うより速い方法があるかどうか疑問に思っていましたか?

+0

あなたが速いとはどういう意味ですか?よりパフォーマンスの高い、より簡潔な? –

+2

@link Btw、それはStringかFixnumの整数ですか? (1233または "1233") – robertodecurnex

+0

現在、どのようにあなたがそれをやっているかを示してください。 – tokland

答えて

32

最短ソリューションは、おそらくです:

1234.to_s.chars.map(&:to_i) 
#=> [1, 2, 3, 4] 

よりオーソドックスな数学的アプローチ:

class Integer 
    def digits(base: 10) 
    quotient, remainder = divmod(base) 
    quotient == 0 ? [remainder] : [*quotient.digits(base: base), remainder] 
    end 
end 

0.digits #=> [0] 
1234.digits #=> [1, 2, 3, 4] 
0x3f.digits(base: 16) #=> [3, 15] 
+0

数字だけを反復するには、配列スライスメソッドを使用することもできます。 N = 12.to_s 和=(N [0..1] .to_i + N [1..2] .to_i) 積=(N [0,1] .to_i * N [1、 1] .to_i) – Linju

2

10(あなたに最後の桁を与えます)、次に10で除算して(残りの桁を与えます)、最後の桁まで降りるまでこれを繰り返します。もちろん、数字を左から右に移動したい場合は、順序を逆にする必要があります。

14

あなたが10でモジュラス/除算の古いトリックを使用することができますが、あなたは巨大な番号を持っていない限り、これは測定可能速くなりません、そして、それは後方あなたに数字を与える:

i = 12345 

while i > 0 
    digit = i % 10 
    i /= 10 
    puts digit 
end 

出力:

5 
4 
3 
2 
1 
5
split=->(x, y=[]) {x < 10 ? y.unshift(x) : split.(x/10, y.unshift(x%10))} 

split.(1000) #=> [1,0,0,0] 
split.(1234) #=> [1,2,3,4] 
2

Rubyは一度にx%10x/10の両方を計算しますdivmodを、持っている:

速度はであるプロジェクト・オイラー、のようなものについては
class Integer 
    def split_digits 
    return [0] if zero? 
    res = [] 
    quotient = self.abs #take care of negative integers 
    until quotient.zero? do 
     quotient, modulus = quotient.divmod(10) #one go! 
     res.unshift(modulus) #put the new value on the first place, shifting all other values 
    end 
    res # done 
    end 
end 

p 135.split_digits #=>[1, 3, 5] 

いくつかの重要性、これは良いです。これをIntegerに定義すると、Bignumでも利用できるようになります。

2

私は列挙子の良さが好きです。私は私のプロジェクトのためにこのコードを書いた:

class Integer 
    def digits 
    Enumerator.new do |x| 
     to_s.chars.map{|c| x << c.to_i } 
    end 
    end 
end 

これは、あなたがすべての良い列挙子のものにアクセスできます:

num = 1234567890 

# use each to iterate over the digits 
num.digits.each do |digit| 
    p digit 
end 

# make them into an array 
p num.digits.to_a  # => [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] 

# or take only some digits 
p num.digits.take(5) # => [1, 2, 3, 4, 5] 

# you can also use next and rewind 
digits = num.digits 
p digits.next   # => 1 
p digits.next   # => 2 
p digits.next   # => 3 
digits.rewind 
p digits.next   # => 1 
関連する問題