我试图将21点游戏的基本策略表示为具有整数键的映射,其值是固定长度的字符串数组。键表示玩家手牌的值,数组索引表示牌手up牌的值(因此大小为10的固定长度数组对应于牌值2-11)。数组中与牌手的up牌对应的位置处的字符串值包含理想的玩法(stay,hit,split,double)。
即玩家的手牌价值是硬性的8,牌手向上的牌是2。基本策略是玩家应该击球。为了使用我的map来确定这一点,我将获得键值为8的数组(玩家手中的值= 8),然后查看数组索引0中的字符串(Dealer up card = 2)。
我尝试这样定义它:
val hardHandBasicStrategy = collection.mutable.Map[Int,Array[String](10)]
但Scala似乎不喜欢这样...
请帮助我了解我做错了什么,并/或建议一种方法来使其正常工作。
发布于 2012-10-05 05:06:54
Scala没有表示固定大小的数组的类型。您可以简单地使用大小为10的数组--这通常是这样做的--或者,如果您想要更有力地保证它确实是大小为10的数组,您可以自己构造一个10长的数组类:
class ArrayTen[T: ClassManifest](zero: T) {
protected val data = Array.fill(10)(zero)
def apply(i: Int) = data(i)
def update(i: Int, t: T) { data(i) = t }
protected def set(ts: Array[T]) { for (i <- data.indices) data(i) = ts(i) }
def map[U: ClassManifest](f: T => U) = {
val at = new ArrayTen(null.asInstanceOf[U])
at.set(data.map(f))
at
}
def foreach(f: T => Unit) { data.map(f) }
override def toString = data.mkString("#10[",",","]")
override def hashCode = scala.util.MurmurHash.arrayHash(data)
override def equals(a: Any) = a match {
case a: ArrayTen[_] => (data,a.data).zipped.forall(_ == _)
case _ => false
}
// Add other methods here if you really need them
}
示例:
scala> new ArrayTen("(nothing)")
res1: ArrayTen[java.lang.String] =
#10[(nothing),(nothing),(nothing),(nothing),(nothing),
(nothing),(nothing),(nothing),(nothing),(nothing)]
scala> res1(3) = "something!!!"
scala> res1
res3: ArrayTen[java.lang.String] =
#10[(nothing),(nothing),(nothing),something!!!,(nothing),
(nothing),(nothing),(nothing),(nothing),(nothing)]
如果需要固定长度数组接受一个确定长度的参数,那么您应该
trait Size { size: Int }
class ArraySize[S <: Size, T: ClassManifest](zero: T, s: Size) {
protected val data = Array.fill(s.size)(zero)
...
}
除非重新实现集合,否则你不会拥有所有的好东西,但话又说回来,你不想要大多数好东西,因为它们中的大多数可以改变数组的长度。
https://stackoverflow.com/questions/12735623
复制相似问题