Skip to content

Instantly share code, notes, and snippets.

@UberMouse
Last active December 30, 2015 05:19
Show Gist options
  • Save UberMouse/7782120 to your computer and use it in GitHub Desktop.
Save UberMouse/7782120 to your computer and use it in GitHub Desktop.
Detects simple sequences in a list of numbers. Only capable of determining liner addition/subtraction sequences.
object Worksheet {
val t = List(25, 21, 17, 13, 9) //> t : List[Int] = List(25, 21, 17, 13, 9)
sealed abstract class SequenceType(dif: Int)
case class Addition(dif: Int) extends SequenceType(dif)
case class Subtraction(dif: Int) extends SequenceType(dif)
case class Multiplication(dif: Int) extends SequenceType(dif)
case class Division(dif: Int) extends SequenceType(dif)
case class Invalid extends SequenceType(0)
def analyzeSequence(seq: List[Int]): Option[Int => Int] = {
val List(n1, n2) = seq.take(2)
var ops = List(Addition(n2 - n1),
Subtraction(n2 - n1),
Multiplication(n1 * n2),
Division(n1 / n2))
seq.drop(2).foldLeft(n2) { (prev, cur) =>
ops = ops.map(op => {
op match {
case op: Addition => {
val dif = cur - prev;
if (dif == op.dif && dif > 0) Addition(dif) else Invalid()
}
case op: Subtraction => {
val dif = cur - prev;
if (dif == op.dif && dif < 0) Subtraction(dif) else Invalid()
}
case op: Multiplication => Invalid()
case op: Division => Invalid()
case op: Invalid => Invalid()
}
})
cur
}
ops.filter(x => x match {
case op: Invalid => false
case _ => true
}).headOption match {
case Some(op) => {
val generatorFunc = (n: Int) => {
n match {
case 0 => 0
case 1 => n1
case x if (n > 1) => {
val x = op.asInstanceOf[Subtraction]
x.dif * (n - 1) + n1
}
}
}
Some(generatorFunc)
}
case None => None
}
} //> analyzeSequence: (seq: List[Int])Option[Int => Int]
val gen = analyzeSequence(t).get //> gen : Int => Int = <function1>
for (i <- 1 to 5) println(gen(i)) //> 25
//| 21
//| 17
//| 13
//| 9
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment