From 6a7c6c10c7f7d229afc7192c1666c21e0dba259c Mon Sep 17 00:00:00 2001 From: Olivia Appleton Date: Thu, 12 Sep 2024 18:25:14 -0500 Subject: [PATCH] Refactor --- lua/src/lib/math.lua | 24 +++++++++++++++--------- lua/src/p0015.lua | 4 ++-- 2 files changed, 17 insertions(+), 11 deletions(-) diff --git a/lua/src/lib/math.lua b/lua/src/lib/math.lua index 6192f1b0..286b325a 100644 --- a/lua/src/lib/math.lua +++ b/lua/src/lib/math.lua @@ -9,16 +9,8 @@ local function factorial(n) return answer end -local function n_choose_r(n, r) - if n < 20 -- fast path if number is small - then - return factorial(n) / factorial(r) / factorial(n - r) - end - - -- slow path for big numbers// slow path for larger numbers +local function factor_gen(n, r) local factors = {} - local answer - local tmp -- collect factors of final number for i = 2,n,1 @@ -51,6 +43,19 @@ local function n_choose_r(n, r) end end + return factors +end + +local function n_choose_r(n, r) + if n < 20 -- fast path if number is small + then + return factorial(n) / factorial(r) / factorial(n - r) + end + + -- slow path for big numbers// slow path for larger numbers + local factors = factor_gen(n, r) + local answer + local tmp local i = 2 local j = 2 answer = 1; @@ -95,4 +100,5 @@ end return { factorial = factorial, + n_choose_r = n_choose_r, } diff --git a/lua/src/p0015.lua b/lua/src/p0015.lua index 8932692e..b19690ec 100644 --- a/lua/src/p0015.lua +++ b/lua/src/p0015.lua @@ -3,8 +3,8 @@ -- Turns out this is easy, if you think sideways a bit -- -- You can only go down or right. If we say right=1, then you can only have 20 1s, since otherwise you go off the grid. --- You also can't have fewer than 20 1s, since then you go off the grid the other way. This means you can look at it as a --- bit string, and the number of 40-bit strings with 20 1s is 40c20. +-- You also can't have fewer than 20 1s, since then you go off the grid the other way. This means you can look at it as +-- a bit string, and the number of 40-bit strings with 20 1s is 40c20. -- -- Problem: --