Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Apr 10th, 2012  |  syntax: Scala  |  size: 1.47 KB  |  hits: 47  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. object Permutations {
  2.  
  3.   trait Permutation {
  4.     def apply(i:Int):Int
  5.     def cycles:IndexedSeq[List[Int]]
  6.     def ==(arg:Permutation):Boolean
  7.     def fixPoints:List[Int]
  8.   }
  9.  
  10.   class ValidPerm(args:Collection[Int]) extends Permutation {
  11.    
  12.     val perm = args.toList
  13.    
  14.     val cycle = cycleNot(perm)
  15.    
  16.     def apply(i:Int) = perm(i-1)
  17.    
  18.     override def toString = {args.foldLeft("s(")((r,c) => r+c+",").init+")"}
  19.    
  20.     private def cycleNot(args:List[Int]) = {
  21.       val v = scala.collection.mutable.Set[Int]()
  22.      
  23.       def gCyc(p:Int, l:List[Int]):List[Int] = if(args(l.head-1) == p) l.reverse
  24.                                                                  else {v+=args(l.head-1);gCyc(p,args(l.head-1)::l)}
  25.      
  26.       for(i <- 1 to args.size if !v(i)) yield gCyc(i, i::Nil)
  27.     }
  28.    
  29.     def cycles = cycle
  30.    
  31.     def ==(arg:Permutation) = this.toString() == arg.toString()
  32.    
  33.     def fixPoints = cycle.foldLeft(List[Int]())((r,c) => if(c.size == 1){ r:+c(0)} else {r})
  34.   }
  35.  
  36.   object NaP extends Permutation{
  37.     override def toString = "NaP"
  38.     def apply(i:Int) = -1
  39.     def cycles = Vector(List())
  40.     def ==(arg:Permutation) = false
  41.     def fixPoints = List()
  42.   }
  43.  
  44.   def checkValidity(args:Collection[Int]) = args.toList.sorted.apply(args.toList.sorted.size-1) == args.toList.sorted.size && args.toList.sorted.size == args.toList.sorted.toSet.size  
  45.  
  46.   def s(args:Int*):Permutation = {
  47.     if(!checkValidity(args)){ NaP}
  48.     else {new ValidPerm(args)}    
  49.   }
  50.  
  51. }