Skip to content

Commit

Permalink
refactor: extract functions
Browse files Browse the repository at this point in the history
  • Loading branch information
scarf005 committed Dec 7, 2024
1 parent b97ac74 commit 7241d73
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 6 deletions.
5 changes: 0 additions & 5 deletions 2024/day07.scala
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,9 @@ package `2024`.day07
import prelude.*
import scala.annotation.tailrec

def digits(x: Long) = math.log10(x.toDouble).toInt + 1

extension (a: Long)
inline def ||(b: Long) = (a * math.pow(10, digits(b)) + b).toLong

extension [C <: Iterable, A](xs: C[A])
def orEmpty[B](f: C[A] => B)(els: => B) = if (xs.isEmpty) els else f(xs)

type Op = Long => Long => List[Long]

def getCombo(xs: List[Long], next: Op) =
Expand Down
10 changes: 9 additions & 1 deletion prelude/iterable.scala
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,12 @@ extension [A](xs: IterableOnce[A])
* items.map(_.length).sum // 6
* }}}
*/
inline def sumBy[B >: Int](f: A => B)(using Numeric[B]): B = xs.iterator.map(f).sum
inline def sumBy[B >: Int](f: A => B)(using Numeric[B]): B =
xs.iterator.map(f).sum

extension [C <: Iterable, A](xs: C[A])
/** Maps the iterable to a new iterable using the given function `f` if the
* iterable is not empty. Otherwise, returns the given value `default`.
*/
def orEmpty[B](f: C[A] => B)(default: => B) =
if (xs.isEmpty) default else f(xs)
3 changes: 3 additions & 0 deletions prelude/math.scala
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
package prelude

def digits(x: Int) = math.log10(x.toDouble).toInt + 1
def digits(x: Long) = math.log10(x.toDouble).toInt + 1

extension (n: Int)
inline infix def divmod(d: Int) = (n / d, n % d)
inline infix def moddiv(d: Int) = (n % d, n / d)
Expand Down

0 comments on commit 7241d73

Please sign in to comment.