+ 3
CHALLENGE : Factorial base conversion
Any number N can be represented by its factorial representation (d0,d1,...dn) where 0<= dn <=n AND N=d0.0!+d1.1!...+dn.n! Write the functions tofactorial(N)=[d0,d1,...dn] AND fromfactorial([d0,d1,...dn]=N Ex: N=463 <=> [0 1 0 1 4 3] because 3Ă5! + 4Ă4! + 1Ă3! + 0Ă2! + 1Ă1! + 0Ă0! = 463 Bonus for efficient & readable one liners :)
12 Respostas
+ 3
Did somebody say functional programming one-liners?
Haskell:
x = 463
main = print $ dropWhile (==0) . snd . foldl f (x, []) . reverse . takeWhile (<=x) . scanl1 (*) $ [1..] where f (m, xs) n = (m `mod` n, (m `div` n) : xs)
https://tio.run/##LY29CsIwAIT3PsUNDomUYlEcxGyO7g6l0GBSGsxPSULN28ekuBwfx/0sPHyk1jkrszof8eCRd08VYtMkMFyu58ZwZQuuXtmIA4R362tRWoIwdqLoEKwoOjstNGaQ1GIYq@/lJn2QhSL/yH/nztLeeXOre5AjLZND33Ujvov0sg6YFilQ1FNiMBknJth2Z6G2whS3msj5Bw
+ 2
and..heres mine....
both functions are included
https://code.sololearn.com/cnk5axwNeK36/?ref=app
+ 2
i am barely breathing now...after doing the code...hurriedly...
spare me..fr some time...đđđ
+ 2
ok...see now...fact and fromfactorial are one liner functions...
đ
+ 2
@schindlabua
n2fac=lambda n,k=1:[n%k]+n2fac(n//k,k+1) if n else [] if k-1 else [0]
in this its not only n%k..its recursive lambda
1st n%k
2ns ( n//k) % (k+1)
3rd (( n//k)//(k+1))%(( k+1)+1)
....
going on
0
Haha. What about a functional programming oneliner ?
0
@shindlabua py is the one liner languagz
https://code.sololearn.com/cD33vbPPcA9C/?ref=app
0
Wow that's a cool algorithm. Why/how does it work?
0
Nah the other one. Not totally sure why n%k would give you the right answer!
0
I'm an idiot. I read the question wrong and implemented a wrong algorithm that happened to do (almost) the right thing. Sorry for being dense :P
- 1
Define f as fromfact([d0,...dn])=d0.0+d1.1!+...+(i-1)!*((di-1)+f([di,...dn])) then recursively compute f and return f([d0,...dn],1)=fromfact([di,...dn])
- 1
đđ