Created
December 1, 2012 13:09
-
-
Save edofic/4182192 to your computer and use it in GitHub Desktop.
aps naloga 3 scala
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
import java.io.{BufferedWriter, PrintWriter, FileWriter, File} | |
import java.util.Scanner | |
object Naloga3s { | |
def Reader(filename: String) = { | |
val sc = new Scanner(new File(filename)) | |
def loop(): Stream[Int] = { | |
if (sc.hasNextInt){ | |
sc.nextInt() #:: loop | |
} else | |
Stream.empty[Int] | |
} | |
loop() | |
} | |
def MultiReader(prefix: String, phase: Int, N: Int, up: Boolean) = { | |
def loop(last: Int, sources: Seq[Stream[Int]]): Stream[Int] = { | |
val nonEmpty = sources.filterNot(_.isEmpty) | |
if(nonEmpty.length==0) | |
Stream.empty[Int] | |
else { | |
val (low,high) = nonEmpty. | |
map(_.head).zipWithIndex.partition(t => up && t._1 < last || !up && t._1 > last) | |
val (e,i) = (if(high.length>0) high else low).minBy(_._1) | |
e #:: loop(e, nonEmpty.updated(i, nonEmpty(i).tail)) | |
} | |
} | |
loop(0, (0 until N).map(n => Reader(prefix + "-" + phase + "-" + n))) | |
} | |
trait Writer{ | |
def write(num: Int): Writer | |
def moreThanOneUsed: Boolean | |
} | |
def Writer(prefix: String, phase: Int, N: Int, up: Boolean): Writer = { | |
val tracks = (0 until N).map(n => new PrintWriter(new BufferedWriter(new FileWriter(prefix+"-"+phase+"-"+n)))) | |
def mkWriter(i: Int, last: Int, used: Boolean): Writer = new Writer{ | |
def write(num: Int) = { | |
val (ni,nu) = | |
if (up && num < last || !up && num > last) | |
((i + 1) % tracks.length, true) | |
else (i, used) | |
tracks(ni).print(num) | |
tracks(ni).print(' ') | |
tracks(ni).flush() | |
mkWriter(ni, num, nu) | |
} | |
def moreThanOneUsed = used | |
} | |
mkWriter(0, if (up) Integer.MIN_VALUE else Integer.MAX_VALUE, used=false) | |
} | |
def main(args: Array[String]){ | |
val inName = args(0) | |
val prefix = args(1) | |
val N = Integer.parseInt(args(2)) | |
val up = args.length <= 3 || !args(3).equalsIgnoreCase("down") | |
def loop(i: Int, source: Stream[Int]){ | |
val sink = source.foldLeft(Writer(prefix, i, N, up))(_ write _) //looks ugly inlined | |
if (sink.moreThanOneUsed) loop(i+1, MultiReader(prefix, i, N ,up)) | |
} | |
loop(0, Reader(inName)) | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment