Created
October 14, 2013 16:25
-
-
Save tyrcho/6978294 to your computer and use it in GitHub Desktop.
faceted search on integers (facet : sum of divisors to search for friend numbers)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package object facets { | |
type Facet[-I, +F] = I => F | |
type ValuedFacet[-I, +F] = (Facet[I, F], F) | |
type FacetWithValues[-I, +F] = (Facet[I, F], Iterable[F]) | |
type FacetWithFilter[-I, F] = (Facet[I, F], F => Boolean) | |
implicit def valueToFilter[I, F](v: ValuedFacet[I, F]): FacetWithFilter[I, F] = { | |
val (facet, value) = v | |
(facet, _ == value) | |
} | |
def allValues[I, F](items: Iterable[I], facet: Facet[I, F]): Set[F] = | |
items.map(facet).toSet | |
def count[I, F](items: Iterable[I], facets: FacetWithFilter[I, _]*): Int = | |
filter(items, facets: _*).size | |
def filter[I](items: Iterable[I], facets: FacetWithFilter[I, _]*) = | |
items.filter(i => facets.forall { case (facet, filter) => filter(facet(i)) }) | |
def sort[I, F](items: Iterable[I], facet: Facet[I, F]): List[(F, Int)] = | |
sort(items, (facet, allValues(items, facet))) | |
def sort[I, F](items: Iterable[I], facets: FacetWithValues[I, F]): List[(F, Int)] = { | |
val (facet, values) = facets | |
values.map { | |
value => | |
(value, count(items, facet -> value)) | |
}.toList.sortBy(-_._2) | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package facets | |
object FriendsWithFacets extends App { | |
type Property = Facet[Int, Int] | |
val sumOfDivisors = (n: Int) => | |
(for { | |
i <- 1 to Math.sqrt(n).toInt | |
if n % i == 0 | |
} yield i + n / i).sum | |
val isOdd: Int => Boolean = | |
_ % 2 == 1 | |
println(sort(1 to 1000, sumOfDivisors)) | |
println(sort(filter(1 to 1000000, sumOfDivisors -> isOdd), sumOfDivisors)) | |
println(filter(1 to 100000, sumOfDivisors -> 54873)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment