Created
September 28, 2016 09:26
-
-
Save trevorsibanda/1713f42b8d07c16918c91f7e15ef3eb5 to your computer and use it in GitHub Desktop.
Consider the function F(N) = 2^N + 1 where N is a positive integer less than 31. Given such a list of 5 integers, find the one that was swapped in and is therefore not part of the original 5 contiguous integers.
This file contains 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
//http://codegolf.stackexchange.com/questions/94679/find-the-odd-one-out-in-a-sequence | |
import math._ | |
object OddOneOut{ | |
case class Test(val l: Seq[Double],val expected: Double){ | |
def apply( _l: Seq[Double], _e: Double ) = new Test( _l, _e ) | |
} | |
def log2(x: Double) = math.log(x)/math.log(2) | |
//y = 1 + 2^n | |
//n = log2(y-1) | |
def n(y: Double) = log2(y-1) | |
//if N is valid then it does not have a decimal poDouble | |
def validN(y: Double): Boolean = ( n(y)%1 == 0 ) | |
// | |
def validSequence(seq: Seq[Double]): Boolean = seq.sliding(2).map(a => a(0)+1 == a(1)).count(identity) > 0 | |
def main(args: Array[String]) { | |
Seq( | |
Test(Seq(5,9,17,33,829), 829 ), | |
Test(Seq(9,5,17,829,33), 829 ), | |
Test(Seq(33, 17, 5, 7, 65),7), | |
Test(Seq(5,9,177,33,65),177), | |
Test(Seq(65,129,259,513,1025), 259), | |
Test(Seq(129,259,513,1025,65), 259), | |
Test(Seq(63,129,257,513,1025), 63), | |
Test(Seq(65,129,257,513,4097), 4097), | |
Test(Seq(5, 9, 2, 17, 33), 2), | |
Test(Seq(9,67108865,134217729,1,268435457), 1) | |
).map{ | |
case Test(l, e) => { | |
val odd = l.filterNot(validN) | |
assert( | |
if(odd.isEmpty) validSequence( l.map{n(_).toDouble} ) else odd == Seq(e) | |
, Test(l, e) ) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment