本文整理汇总了Scala中scala.collection.mutable.Map类的典型用法代码示例。如果您正苦于以下问题:Scala Map类的具体用法?Scala Map怎么用?Scala Map使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Map类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: Problem011
//设置package包名称以及导入依赖的类
object Problem011 {
def main(args: Array[String]) {
val numbers = """
08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08
49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00
81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65
52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91
22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80
24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50
32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70
67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21
24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72
21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95
78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92
16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57
86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58
19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40
04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66
88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69
04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36
20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16
20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54
01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48
""";
import scala.collection.mutable.Map
def get4times(numbers: Map[Int, Int])(ruleY: Int, ruleX: Int)(y: Int, x: Int): Int = {
val num: List[Int] = (
for {
i <- 0 to 3;
yy = (ruleY * i) + y;
xx = (ruleX * i) + x
if (yy >= 0 && yy < 20 && xx >= 0 && xx < 20)
} yield numbers(yy * 100 + xx)).toList
if (num.length == 4) (1 /: num)(_ * _) // reduce
else -1
}
var i, max = -1;
val map = Map.empty[Int, Int]
numbers.trim.split("[\n\\s]").toList.map(_.toInt)
.foreach((x) => { i += 1; map((i / 20) * 100 + i % 20) = x; });
for {
rule <- List((1, 0), (0, 1), (1, 1), (-1, 1))
i <- 0 to 20;
j <- 0 to 20
res = get4times(map)(rule._1, rule._2)(i, j)
if (res > max)
} max = res
println(max)
}
}
示例2: Problem012
//设置package包名称以及导入依赖的类
object Problem012 {
import scala.collection.mutable.Map
def main(args: Array[String]) {
var primes = List(2L, 3L, 5L);
var factorSaved = Map.empty[Long, List[Long]];
def calc(count: Long, isLeftOdd: Boolean): Long = {
val left: Long = if (isLeftOdd) count else count / 2;
val right: Long = if (isLeftOdd) (count + 1) / 2 else count + 1;
val fac = getFactor(left) ::: getFactor(right) // ??? ?? ??
if (getFactorCount(fac) < 500) // ??? ??? 500 ? ????? ??
calc(count + 1, !isLeftOdd)
else
left * right
}
val start = System.currentTimeMillis();
println(calc(3, true)) // 3 ?? ????? ????
val end = System.currentTimeMillis();
println("???? ", end - start)
}
}
示例3: ListOptions
//设置package包名称以及导入依赖的类
package com.orendain.sraw.model
import scala.collection.mutable.Map
case class ListOptions(
before: String = "",
after: String = "",
count: Int = -1,
limit: Int = -1,
showAll: Boolean = false,
sr_detail: Boolean = false
) {
val toMap = {
val map = Map.empty[String, String]
if (count >= 0) map += ("count" -> count.toString)
if (limit >= 0) map += ("limit" -> limit.toString)
if (showAll) map += ("show" -> "all")
if (sr_detail) map += ("sr_detail" -> "true")
if (!before.isEmpty) map += ("before" -> before)
else if (!after.isEmpty) map += ("after" -> after)
map.toMap
}
}
object ListOptions {
val Empty = ListOptions()
}
示例4: ChecksumAccumulator
//设置package包名称以及导入依赖的类
import scala.collection.mutable.Map
class ChecksumAccumulator {
private var sum = 0
def add(b: Byte) {sum += b}
def checksum(): Int = ~(sum & 0xFF) + 1
}
object ChecksumAccumulator {
private val cache = Map[String, Int]()
def calculate(s: String): Int = {
if (cache.contains(s))
cache(s)
else {
val acc = new ChecksumAccumulator
for (c <- s) acc.add(c.toByte)
val cs = acc.checksum()
cache += (s -> cs)
cs
}
}
}
示例5: Profile
//设置package包名称以及导入依赖的类
package edu.rosehulman.client
import edu.rosehulman.collections.DistributedMap
import scala.collection.mutable.Map
case class Profile(name: String, email: String, creditcard: String)
object Application extends App {
val workers = List(
"akka.tcp://[email protected]:2553/user/worker",
"akka.tcp://[email protected]:2554/user/worker",
"akka.tcp://[email protected]:2555/user/worker"
)
val map: Map[String, Profile] = new DistributedMap[Profile](workers)
map += "adam" -> Profile("Adam Michael", "[email protected]", "234567890")
println("OK Trying get")
println(map.get("adam"))
}
示例6: JSMap
//设置package包名称以及导入依赖的类
package akka.util
import scala.collection.mutable.{ Map, MapLike }
import scala.scalajs.js
import js.annotation.JSBracketAccess
final class JSMap[A] private () extends Map[String, A]
with MapLike[String, A, JSMap[A]] {
private[this] val dict: js.Dictionary[A] = js.Dictionary.empty[A]
override def empty: JSMap[A] = new JSMap[A]
override def get(key: String): Option[A] = {
if (dict.isDefinedAt(key)) Some(dict(key))
else None
}
override def +=(kv: (String, A)): this.type = {
dict(kv._1) = kv._2
this
}
override def -=(key: String): this.type = {
dict.delete(key)
this
}
override def iterator: Iterator[(String, A)] = {
for {
key <- dict.keys.iterator
} yield {
(key, dict(key))
}
}
}
object JSMap {
def empty[A]: JSMap[A] = new JSMap[A]
}
示例7: Label
//设置package包名称以及导入依赖的类
package casl.controls
import scala.collection.mutable.Map
import scala.reflect.ClassTag
class Label[T](val name: String)(implicit c: ClassTag[T]) {
Label.put(this)
private var values: Array[T] = Array[T]()
private var reservedValue: T = _
def DC(value: T): Unit = {
this.values = new Array[T](1)
this.values(0) = value
}
def DS(size: Int): Unit = this.values = new Array[T](size)
def get() = this.getValues()(0)
def set(value: T): Unit = this.set(0, value)
def set(position: Int, value: T): Unit = {
this.values(position) = value
this.cancelReserve()
}
def reserve(value: T) = this.reservedValue = value
def cancelReserve() = this.reservedValue = null.asInstanceOf[T]
def asString() = if (this.getValues().isEmpty) "" else this.getValues().mkString("")
private def getValues(): Array[T] = {
if (this.reservedValue != null) {
this.set(0, this.reservedValue)
}
return this.values
}
override def toString = s"Label{name=$name, values=[${values.mkString(", ")}, reservedValue=$reservedValue]"
}
object Label {
private val map = Map[String, Label[_]]()
def put(label: Label[_]) = Label.map.put(label.name, label)
def get(name: String) = Label.map(name)
}
示例8: Caching
//设置package包名称以及导入依赖的类
import scala.collection.mutable.Map
import scala.util.Random
object Caching {
val TestMap = Map[Int, String]()
def cache(key: Int) = {
if(TestMap.size > 1000){
val random = new Random
val r_val = TestMap(random.nextInt(TestMap.size)).toInt
//var r_val = TestMap.toVector(random(TestMap.size))
TestMap -= r_val
TestMap += (key -> "Testing val")
}
else{
TestMap += (key -> "Testing val")
}
}
def time[R](block: => R): R = {
val t0 = System.nanoTime()
val result = block // call-by-name
val t1 = System.nanoTime()
println("Elapsed time: " + (t1 - t0) + "ns")
result
}
def main(args: Array[String]): Unit = {
val rand = new Random
var tot = 0
for (a <- 0 to 1010){
if (a > 1005)
time {cache(rand.nextInt(3000))}
else
cache(rand.nextInt(3000))
}
val runtime = Runtime.getRuntime
println("** Used Memory: " + (runtime.totalMemory - runtime.freeMemory)/1010)
}
}
示例9: AutServicios
//设置package包名称以及导入依赖的类
package autenticacion.servicios
import autenticacion.modelo.Auth
import java.util.{Date, UUID}
import com.nimbusds.jose.crypto.MACSigner
import com.nimbusds.jose.{JWSAlgorithm, JWSHeader}
import com.nimbusds.jwt.{JWTClaimsSet, SignedJWT}
import scala.collection.JavaConversions._
import scala.collection.mutable.Map
object AutServicios {
private val ISSUER = "MigranaApp"
private val SIGNING_KEY = "fasdSsdfalsdkoliieñs9423o4ilñaslñ4ññslkAAÑk6sdlkfaiseo7nalksdmc8m9lsnklfnlaiengldyhsltohsnf0lsinnoi"
def validarUsuario( aut: Auth ): Option[ String ] = {
if (true) //aqui debemos consultar en la bd
Some(createToken( aut.user ))
else None
}
def createToken(user: String): String = {
val issued: Long = System.currentTimeMillis()
val claimsSet: JWTClaimsSet = new JWTClaimsSet()
claimsSet.setIssueTime(new Date(issued))
claimsSet.setJWTID(UUID.randomUUID.toString)
claimsSet.setIssuer(ISSUER)
val customData = Map[String, String](
"user" -> user,
"rol" -> "paciente"
)
claimsSet.setCustomClaims(customData)
val signedJWT: SignedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.HS256), claimsSet)
val signer: MACSigner = new MACSigner(SIGNING_KEY)
signedJWT.sign(signer)
signedJWT.serialize() // este es el Token
}
}
示例10: ChecksumAccumulator
//设置package包名称以及导入依赖的类
package io.sweetheart.examples.pis.classesAndObjects
class ChecksumAccumulator {
private var sum = 0
def add(b: Byte) { sum += b }
def checksum(): Int = ~(sum & 0xFF) + 1
}
import scala.collection.mutable.Map
object ChecksumAccumulator {
private val cache = Map[String, Int]()
def calculate(s: String): Int =
if (cache.contains(s))
cache(s)
else {
val acc = new ChecksumAccumulator
for (c <- s)
acc.add(c.toByte)
val cs = acc.checksum()
cache += (s -> cs)
cs
}
}
示例11: Capitals
//设置package包名称以及导入依赖的类
package io.sweetheart.examples.pis.collections
object Capitals {
def useImmut(): Unit = {
var capital = Map("US" -> "Washington", "France" -> "Paris")
capital += ("Japan" -> "Tokyo")
println(capital("France"))
}
def useMut(): Unit = {
import scala.collection.mutable.Map
var capital = Map("US" -> "Washington", "France" -> "Paris")
capital += ("Japan" -> "Tokyo")
println(capital("France"))
}
def main(args: Array[String]): Unit = {
useImmut()
useMut()
}
}
示例12: ExperienceFeature
//设置package包名称以及导入依赖的类
package applicant.ml.regression.features
import applicant.etl.ApplicantData
import applicant.ml.regression.FeatureSetting
import scala.collection.mutable.{ListBuffer, Map}
import scala.collection.JavaConversions.JListWrapper
class ExperienceFeature(newSetting: FeatureSetting) extends BaseFeature {
val setting = newSetting
def getFeatureScore(applicant: ApplicantData): Double = {
val infoMap = setting.values(0).asInstanceOf[Map[String,JListWrapper[AnyRef]]]
val positionKeywords: ListBuffer[String] = infoMap("positions").asInstanceOf[JListWrapper[String]].toList.to[ListBuffer]
val degreeKeywords: ListBuffer[String] = infoMap("degrees").asInstanceOf[JListWrapper[String]].toList.to[ListBuffer]
var rawGPA = applicant.gpa
//Scale the gpa by the type of degree
if (checkDegree(applicant.degree, degreeKeywords)) {
rawGPA = gpaScaler(rawGPA, 0.5)
} else {
rawGPA *= gpaScaler(rawGPA, 0.25)
}
var positionScore = 0.0
positionScore = checkPosition(positionScore, applicant.recentTitle, positionKeywords)
for (position <- applicant.otherTitleList) {
positionScore = checkPosition(positionScore, applicant.recentTitle, positionKeywords)
}
val maxScore = Math.max(rawGPA, positionScore) / 4.0
return if (maxScore > 1.0) 1.0 else maxScore
}
}
示例13: RationalMill
//设置package包名称以及导入依赖的类
package models
import scala.collection.mutable.{Stack,Map}
import scala.util._
import edu.neu.coe.scala.numerics.Rational
object RationalMill {
val conv: String=>Try[Rational] = RationalMill.valueOf _
val lookup: String=>Option[Rational] = RationalMill.constants.get _
implicit val store = Map[String,Rational]()
implicit val parser = new ExpressionParser[Rational](conv,lookup)
def apply(): Mill[Rational] = new Mill(Stack[Rational]()) {
def apply(s: String): Try[Rational] = RationalMill.valueOf(s)
}
def valueOf(s: String): Try[Rational] = Try(Rational(s))
val constants = Map("e"->Rational(BigDecimal(math.E)), "pi"->Rational(BigDecimal(math.Pi)))
}
示例14: Mill
//设置package包名称以及导入依赖的类
package models
import scala.collection.mutable.{Stack,Map}
import scala.util._
abstract class Mill[A : Numeric](stack: Stack[A])(implicit store: Map[String,A]) extends Function1[Valuable[A],Try[A]] { self =>
var debugMill = false;
def value = if (stack.size>0) Success(stack.top) else Failure(new IllegalArgumentException("stack is empty"))
def toSeq = stack.toSeq
def show = println(stack)
def push(x: A) = { if (debugMill) println(s"push $x");stack.push(x)}
def pop = {val x = stack.pop; if (debugMill) println(s"popped $x"); x}
def setDebug(b: Boolean) { debugMill = b }
def has(n: Int) = assert(stack.size>=n,s"operation requires $n element(s) on stack")
def apply(v: Valuable[A]) = v match {
case n @ Number(x) => n.apply match {case Success(x) => push(x); case Failure(e) => throw e}; value
case k @ Constant(x) => k.apply match {case Success(x) => push(x); case Failure(e) => throw e}; value
case Operator(s) => operate(s); value
case MemInst(s,n) => memInst(s,n); value
}
def dyadic(f: (A,A)=>A) = { has(2); push(f(pop,pop)) }
def monoadic(f: (A)=>A) = { has(1); push(f(pop)) }
def monoadic2(f: (A,A)=>A)(a: A) = { has(1); push(f(a,pop)) }
def operate(s: String): Unit = s match {
case "+" => operate("plus")
case "plus" => dyadic(implicitly[Numeric[A]].plus)
case "-" => operate("chs"); operate("plus")
case "chs" => monoadic(implicitly[Numeric[A]].negate)
case "*" => operate("times")
case "times" => dyadic(implicitly[Numeric[A]].times)
case "div" => operate("/")
case "/" => operate("inv"); operate("times")
case "inv" => val i = implicitly[Numeric[A]]; if (i.isInstanceOf[Fractional[A]]) monoadic2(i.asInstanceOf[Fractional[A]].div _)(i.one)
case "swap" => has(2); val (top,next) = (pop,pop); push(top); push(next)
case "del" => has(1); pop
case "clr" => stack.clear
case x => throw new IllegalArgumentException(s"operator $x is not supported")
}
def memInst(s: String, k: String) = s.toLowerCase match {
case "sto" => value match {case Success(x) => store.put(k,x); case Failure(e) => throw e}
case "rcl" => store.get(k) match {case Some(x) => push(x); case None => throw new IllegalArgumentException(s"no value at memory location $k")}
}
def parse(s: String)(implicit parser: ExpressionParser[A]): Try[A] =
parser.parseAll(parser.expr,s) match {
case parser.Success(ws,_) => try {
(for (w <- ws) yield apply(w)).reverse.head
} catch {
case t: Throwable => Failure(t)
}
case parser.Failure(e,_) => Failure(new IllegalArgumentException(s"parseResult error: $e"))
case r @ _ => Failure(new IllegalArgumentException(s"logic error: parseResult is $r"))
}
}
示例15: DoubleMill
//设置package包名称以及导入依赖的类
package models
import scala.collection.mutable.{Stack,Map}
import scala.util._
//
object DoubleMill {
val conv: String=>Try[Double] = DoubleMill.valueOf _
val lookup: String=>Option[Double] = DoubleMill.constants.get _
implicit val store = Map[String,Double]()
implicit val parser = new ExpressionParser[Double](conv,lookup)
def apply(): Mill[Double] = new Mill(Stack[Double]()) {
def apply(s: String): Try[Double] = DoubleMill.valueOf(s)
}
def valueOf(s: String): Try[Double] = Try(s.toDouble)
val constants = Map("e"->math.E, "pi"->math.Pi)
}