// Here is my scala solution
package chessdojo
object Main extends Application {
// a8, b7, b6 could return [ c7 , b5 , d6 , b7 ]
val p = new Position("A8")
p.shortestPath(new Position("B7"), Set(new Position("B6")))
val p3 = new Position("A8")
p3.shortestPath(new Position("A5"), Set(new Position("B6")))
// Example 2: a8 , g6 , b6 , c7 would return nil
val p2 = new Position("A8")
p2.shortestPath(new Position("G6"), Set(new Position("B6"),new
Position("C7")))
}
class Solution {
var shortestPath = Integer.MAX_VALUE;
}
final class Position(xpos: Int,ypos: Int) {
val x=xpos
val y=ypos
def this(p: String) {
this(p.charAt(0)-64,p.charAt(1)-48)
}
def shortestPath(target: Position, forbidden : Set[Position]): List
[Position] = {
val l = search(target: Position, forbidden : Set[Position],
List(),new Solution())
print(this+" -> "+target+" : ")
l.foreach( (p:Position) => print(p+" "))
println
l
}
private def search(target: Position, forbidden : Set[Position],
visited : List[Position],s:Solution) : List
[Position] = {
if (this == target) {
s.shortestPath = visited.length
visited+this
} else if (s.shortestPath<visited.length) Nil
else {
val avail = availableMoves -- forbidden -- visited
if (avail.isEmpty) Nil else {
val l = for (p <- avail) yield p.search(target,
forbidden+this ,visited+this,s)
var t = List[Position]()
var size=Integer.MAX_VALUE
l.foreach( p => if (!p.isEmpty && p.length<size)
{t=p; size=p.size} )
t
}
}
}
private def availableMoves: Set[Position] = {
val pos = for (i <- Set((1,2),(2,1),(1,-2),(2,-1),
(-1,2),(-2,1),(-1,-2),(-2,-1))) yield
new Position(x+i._1,y+i._2)
pos.filter((p: Position)=> p.x>0 && p.y>0 && p.x<=8 && p.y<=8)
}
override def toString = (x+64).toChar +""+ (48+y).toChar
override def hashCode: Int = 41*x+y
override def equals(other: Any) = other match {
case that: Position => this.x == that.x && this.y == that.y
case _ => false
}
}
On Mar 9, 11:13 am, Ivan Sanchez <
s4nc...@gmail.com> wrote:
> For those having problems with tinyurl, the link ishttp://
rubyquiz.com/quiz27.html
>
> I liked the problem although I wouldn't even know how to start
> solving it. Well, that's one of the reasons we attend the dojo, isn't
> it?
>
> See you guys tonight
>
> Ivan
>
> On Fri, Mar 6, 2009 at 5:14 AM, andhapp <
dutta.a...@googlemail.com> wrote:
>
> > Knights Travails -
http://tinyurl.com/d5jg3al