Skip to content

Instantly share code, notes, and snippets.

// project euler 28
//
// The sum of the vertices can be expressed as follows. The w is width of the square.
//
// sum = (w - 2)^2 + (w - 1)
// + (w - 2)^2 + 2(w - 1)
// + (w - 2)^2 + 3(w - 1)
// + (w - 2)^2 + 4(w - 1)
// = 4w^2 - 6w + 6
//
require 'redis'
require 'hiredis'
$redis = Redis.new(
host: "127.0.0.1",
port: 6379,
timeout: 30.0,
driver: :hiredis
)
require 'date'
t1 = DateTime.parse(ARGV[0])
t2 = DateTime.parse(ARGV[1])
seconds = ((t2 - t1) * 24 * 60 * 60).to_i
r = seconds.divmod(60)
puts "#{r[0]}min#{r[1]}sec"
f1 = 1
f2 = 2
sum = 0
loop {
break if f2 > 4000000
sum += f2 if f2 % 2 == 0
f2 = f1 + f2
f1 = f2 - f1
}
// compile error
import scala.annotation.tailrec
@tailrec
def fib(n: Int): Int = n match {
case 1 | 2 => 1
case _ => fib(n - 1) + fib(n - 2)
}
trait Monoid[A] {
def mappend(a: A, b: A): A
def mzero: A
}
object Monoid {
implicit val IntMonoid: Monoid[Int] = new Monoid[Int] {
def mappend(a: Int, b: Int) = a + b
def mzero = 0
}
trait Greeter {
val s: String
def greet(): String = s"greet! $s"
}
object Greeter {
implicit def convertInt(i: Int): Greeter = new Greeter { val s = i.toString }
}
import Greeter._
@yutaono
yutaono / xml.scala
Created April 2, 2015 05:49
scala xml memo
scala> val a: Option[String] = Some("msg")
a: Option[String] = Some(msg)
scala> <msg content={a orNull} />
warning: there was one feature warning; re-run with -feature for details
res3: scala.xml.Elem = <msg content="msg"/>
scala> val a: Option[String] = None
a: Option[String] = None
@yutaono
yutaono / gist:c862584dc0b4e95ed876
Last active August 29, 2015 14:18
scala tail recursive optimization
  • Main.scala
import scala.annotation.tailrec

object Main extends App {
  def f(a: Int): Int = {
    a match {
      case x if x <= 1 => 1
      case x => x * f(x - 1)
scala> class A[M[_]]
warning: there was one feature warning; re-run with -feature for details
defined class A
scala> class B[M[+_]]
warning: there was one feature warning; re-run with -feature for details
defined class B
scala> class C[M[-_]]
warning: there was one feature warning; re-run with -feature for details