Monday, September 1, 2014

Peeping into Julia Dictionaries and using them in problem solving


Julia dictionaries are powerful mapping data structures.we here deal with two problems and using dictionaries.



1)Finding cube root of a no without using inbuilt cbrt() function i.e purely written in Julia

Here we see how to use a Julia dictionary and also map function


Solution:
function cubethRoot(n)
           d = factor(n)
           k,v=keys(d),values(d)
           fact = int([int(m) for m in v][1]/3)
           mykeys=[int(m) for m in k]
           res = map(x->x^fact,mykeys)
    prod(res)
end
@time cubeRoot(512)

2)Factorise from beginning to a given no

factor() is a julia inbuilt which factorises a no and returns a dictionary


Solution:
function showfactor(n)
           for i in 1:n
               d=factor(i)
               println("factors for $i")
               for k in d
                   print("$(k[1])^$(k[2])\t")
               end
               println('\n')
           end
       end
println("Enter a no to which factors to be printed")
m = int(rstrip(readline(STDIN)))
@time showfactor(m)



@time macro is optional to show efficiency of Julia function.