Skip to content

Instantly share code, notes, and snippets.

@ademilter
Forked from husrevo/Merged.scala
Created February 10, 2016 20:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ademilter/732a5e44e9204a977360 to your computer and use it in GitHub Desktop.
Save ademilter/732a5e44e9204a977360 to your computer and use it in GitHub Desktop.
import scala.collection.mutable
import scala.util.Random
/**
* Created by husrev on 10/02/16.
*/
object HelloApp extends App {
type Point = (Int, Int)
type Trace = List[Point]
val rowCount = 5
val colCount = 5
val colorCount = 6
//random map olusturma
val list = for (x <- 0 until rowCount; y <- 0 until colCount) yield (x, y) -> Random.nextInt(colorCount).toString
val map = mutable.Map() ++ list.toMap
// bas haritayi
printMap(map)
val possibleTraces = for (a <- 0 until rowCount; b <- 0 until colCount) yield {
findAtLeast(3, map, List((a, b)))
}
val traces = possibleTraces.collect { case Some(res) => res.toSet }
val blocks = traces.toSet
val uniqueBlocks = merge(blocks)
/* BOYAMA KODU
for ((block, i) <- uniqueBlocks.zipWithIndex) {
val char = ('A' + i).toChar
for ((a, b) <- block)
map.put((a, b), char.toString)
}
println
printMap(map)
*/
// En az n tane kendinle ayni renkte adam bulabilir misin? Bulursan butun yolu dondur, yoksa None.
def findAtLeast(n: Int, map: mutable.Map[Point, String], previous: Trace): Option[Trace] = {
val (x, y) = previous.head
val current = map(x, y)
val possibleNeighbors =
List( (x, y + 1), (x, y - 1), (x + 1, y), (x - 1, y)).filter { case (a, b) =>
a >= 0 && b >= 0 && a < rowCount && b < colCount && !previous.contains((a, b))
}
val neighborsWithSameValue = possibleNeighbors.filter { case (a, b) =>
current == map(a, b)
}
val neighborResults = neighborsWithSameValue.map { case (nX, nY) =>
findAtLeast(n - 1, map, (nX, nY) :: previous)
}.collect { case Some(result) => result }
if (neighborResults.size == 0 && n > 1)
None
else if(neighborResults.size == 0 && n <=1 ) Some(previous)
else {
val best = neighborResults.maxBy(_.size)
if(best.size >= n-1)
Some(best)
else None
}
}
// Verilen set'lerden ortak elemani olanlari birlestir.
def merge(sets: Set[Set[Point]]): Set[Set[Point]] = {
var anythingMergedYet = false
val uniqueBlocks = mutable.Set() ++ sets
for(a <- sets; b <- sets)
if(a != b && !a.forall(!b.contains(_))) {
uniqueBlocks.remove(a)
uniqueBlocks.remove(b)
uniqueBlocks.add(a++b)
anythingMergedYet = true
}
if(anythingMergedYet)
merge(uniqueBlocks.toSet)
else
sets
}
// bas bas haritayi ekrani
def printMap(map: mutable.Map[Point, String]): Unit = {
for (x <- 0 until rowCount) {
for (y <- 0 until colCount)
print(map((x, y)) + " ")
println()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment