Created
January 15, 2014 16:30
-
-
Save davepkennedy/8439399 to your computer and use it in GitHub Desktop.
Max factor of the permutations of a list
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
object permutations { | |
def insertAt[T](e: T, p: Int, l: List[T]): List[T] = p match { | |
case 0 => e :: l | |
case _ => l.head :: insertAt(e, p-1, l.tail) | |
} //> insertAt: [T](e: T, p: Int, l: List[T])List[T] | |
def permute[T] (l: List[T]): List[List[T]] = l match { | |
case Nil => Nil | |
case h :: t => | |
println(h, t) | |
permute(t) match { | |
case Nil => List(List(h)) | |
case permutations => | |
for { | |
permutation <- permutations | |
i <- 0 to permutation.length | |
} yield insertAt(h, i, permutation) | |
} | |
} //> permute: [T](l: List[T])List[List[T]] | |
def factor (a: List[Int], b: List[Int]): Int = { | |
if (a.length == 0 || b.length == 0) 0 | |
else { | |
val ah = a.head | |
val bh = b.head | |
(ah*bh) + factor (a.tail, b.tail) | |
} | |
} //> factor: (a: List[Int], b: List[Int])Int | |
def maxFactor (a: List[List[Int]], b: List[List[Int]], max: Int = 0): Int = { | |
if (a.length == 0 || b.length == 0) {max} | |
else { | |
val al = a.head | |
val bl = b.head | |
maxFactor(a.tail, b.tail, math.max(max, factor(al, bl))) | |
} | |
} //> maxFactor: (a: List[List[Int]], b: List[List[Int]], max: Int)Int | |
val a = permute (List(1,2,3)) //> (1,List(2, 3)) | |
//| (2,List(3)) | |
//| (3,List()) | |
//| a : List[List[Int]] = List(List(1, 2, 3), List(2, 1, 3), List(2, 3, 1), Lis | |
//| t(1, 3, 2), List(3, 1, 2), List(3, 2, 1)) | |
val b = permute (List(4,5,6)) //> (4,List(5, 6)) | |
//| (5,List(6)) | |
//| (6,List()) | |
//| b : List[List[Int]] = List(List(4, 5, 6), List(5, 4, 6), List(5, 6, 4), Lis | |
//| t(4, 6, 5), List(6, 4, 5), List(6, 5, 4)) | |
maxFactor (a,b) //> res0: Int = 32 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment