Skip to content

Commit

Permalink
digits(n, [base, [pad]]): returns an array of digits of n [close #2737]
Browse files Browse the repository at this point in the history
  • Loading branch information
StefanKarpinski committed Apr 4, 2013
1 parent 3eb0c05 commit 0d22e92
Showing 1 changed file with 12 additions and 1 deletion.
13 changes: 12 additions & 1 deletion base/intfuncs.jl
Original file line number Diff line number Diff line change
Expand Up @@ -291,7 +291,6 @@ base(base::Integer, n::Integer, pad::Integer) = _base(dig_syms,int(base),unsigne
base(symbols::Array{Uint8}, n::Integer, p::Integer) = _base(symbols,length(symbols),unsigned(abs(n)),p,n<0)
base(base_or_symbols::Union(Integer,Array{Uint8}), n::Integer) = base(base_or_symbols, n, 1)


for sym in (:bin, :oct, :dec, :hex)
@eval begin
($sym)(x::Unsigned, p::Int) = ($sym)(x,p,false)
Expand All @@ -307,6 +306,18 @@ bits(x::Union(Char,Int32,Uint32,Float32)) = bin(reinterpret(Uint32,x),32)
bits(x::Union(Int64,Uint64,Float64)) = bin(reinterpret(Uint64,x),64)
bits(x::Union(Int128,Uint128)) = bin(reinterpret(Uint128,x),128)

function digits{T<:Integer}(n::Integer, base::T=10, pad::Int=1)
2 <= base || error("invalid base: $base")
i = max(pad,ndigits0z(n,base))
a = zeros(T,i)
while i > 0
a[i] = rem(n,base)
n = div(n,base)
i -= 1
end
return a
end

const PRIMES = [
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71,
73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151,
Expand Down

3 comments on commit 0d22e92

@JeffBezanson
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It seems more useful to me to return the digits in the reverse order of this, i.e. with the ones place always in a[1]. That way the place values are the same for all numbers, and the identity n == sum([a[k]*b^(k-1) for k=1:length(a)]) holds.

@StefanKarpinski
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That seems reasonable enough. This was just the order they print in.

@alanedelman
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

... and it respects column major order too.

Can we generalize to take a base vector like APL's encode, (and also inspired by a "zero based" Cartesian)
(note the code is practically the same)

function Alandigits(n,base::Array,pad::Int=1)
    k=length(base);
    a=zeros(Int,max(k,pad));i=k;
    for i=k:-1:1
        a[k+1-i] = rem(n,base[i])
        n = div(n,base[i])
    end
   a
 end     

map(n->Alandigits(n,[5,3],3),0:14)
15-element Array{Array{Int64,1},1}:
[0,0,0]
[1,0,0]
[2,0,0]
[0,1,0]
[1,1,0]
[2,1,0]
[0,2,0]
[1,2,0]
[2,2,0]
[0,3,0]
[1,3,0]
[2,3,0]
[0,4,0]
[1,4,0]
[2,4,0]

Please sign in to comment.