当前位置: 首页>>代码示例>>Scala>>正文


Scala HashMap类代码示例

本文整理汇总了Scala中scala.collection.mutable.HashMap的典型用法代码示例。如果您正苦于以下问题:Scala HashMap类的具体用法?Scala HashMap怎么用?Scala HashMap使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了HashMap类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。

示例1: Problem021

//设置package包名称以及导入依赖的类
object Problem021 {

  def main(args: Array[String]) {

    import scala.collection.mutable.HashMap
    var map = HashMap.empty[Int, Int]

    def getDivSum(num: Int): Int = {
      if (!(map contains num))
        map(num) = (for { a <- 1 until num; if (num % a == 0) } yield a).toList.sum

      map(num)
    }

    def isAmicable(num: Int): Boolean = {
      val fst = getDivSum(num)
      num == getDivSum(fst) && num != fst
    }

    val result = (for {
      i <- 1 to 10000;
      sum = getDivSum(i);
      if (isAmicable(sum))
    } yield sum).toSet

    println(result.sum)
  }
} 
开发者ID:johngrib,项目名称:project_euler,代码行数:29,代码来源:Problem021.scala

示例2: ProblemFourteen

//设置package包名称以及导入依赖的类
package org.nason.euler.ten

import scala.collection.mutable.HashMap


import org.nason.euler.EulerUtils
import org.nason.euler.NumberUtils

object ProblemFourteen {
  def main(args: Array[String]) {
    println( solution4 )
  }
  
  
  def solution4 =
  {
    // memoize function lookup
    val fLengths = new HashMap[BigInt,Int]()
    fLengths(1) = 1
    def f( n:BigInt ) =
    {
      var g = n
      var l = 1
      while( g!=1 )
      {
        if ( fLengths contains g )
        {
          l += fLengths(g) - 1
          g = 1
        }
        else
        {
          (g%2).toInt match
          {
            case 0 => g = g/2
            case 1 => g = BigInt(3)*g + BigInt(1)
          }
          l += 1
        }
      }
      fLengths(n) = l
      l
    }
    NumberUtils seqMax( (1 to 999999) map ( i => (f(i),i) ) )
  }
} 
开发者ID:drkeoni,项目名称:euler-jms-scala,代码行数:47,代码来源:ProblemFourteen.scala

示例3: ProblemTen

//设置package包名称以及导入依赖的类
package org.nason.euler.ten

import scala.collection.mutable.HashMap

object ProblemTen {
  def main(args: Array[String]) {
    println( solution )
  }
  
  def solution =
  {
    val MAX = BigInt(2000000)
    def primes( max : BigInt ) =
    {
      var prime = new HashMap[BigInt,Boolean]
      for( i<-BigInt(2) to max )
        prime(i) = true
      val m = Math ceil (Math sqrt( max toDouble )) toInt
      var stride = BigInt(2)
      while( stride<=m )
      {
        var i = BigInt(2)*stride
        while( i<=max )
        {
          prime( i ) = false
          i += stride
        }
        stride += 1
        while( stride<=m && !prime(stride) )
        {
          stride += 1
        }
      }
      prime filter { a => a._2 } map { a => a._1 }
    }
    primes(MAX) reduceLeft { (a,b) => a+b }
    // for debugging
    //(primes(MAX) toList).sort( (a,b) => a < b )
  }
} 
开发者ID:drkeoni,项目名称:euler-jms-scala,代码行数:41,代码来源:ProblemTen.scala

示例4: table

//设置package包名称以及导入依赖的类
import scala.collection.mutable.HashMap

sealed trait STMap[S,K,V] {
  protected def table: HashMap[K,V]

  def size: ST[S,Int] = ST(table.size)

  // Get the value under a key
  def apply(k: K): ST[S,V] = ST(table(k))

  // Get the value under a key, or None if the key does not exist
  def get(k: K): ST[S, Option[V]] = ST(table.get(k))

  // Add a value under a key
  def +=(kv: (K, V)): ST[S,Unit] = ST(table += kv)

  // Remove a key
  def -=(k: K): ST[S,Unit] = ST(table -= k)
}

object STMap {
  def empty[S,K,V]: ST[S, STMap[S,K,V]] = ST(new STMap[S,K,V] {
    val table = HashMap.empty[K,V]
  })

  def fromMap[S,K,V](m: Map[K,V]): ST[S, STMap[S,K,V]] = ST(new STMap[S,K,V] {
    val table = (HashMap.newBuilder[K,V] ++= m).result
  })
} 
开发者ID:F-kinungi,项目名称:Solutions,代码行数:30,代码来源:03.answer.scala

示例5: Schema

//设置package包名称以及导入依赖的类
package eu.stratosphere.benchmarks.systemml.cli.command.visualizationUtil

import scala.collection.mutable.HashMap
import scala.collection.mutable.ArrayBuffer


class Schema(listc: ArrayBuffer[Metric], mapc: HashMap[String, Int]) {

  var list: ArrayBuffer[Metric] = listc
  var epochID = -1

  def this (listt: ArrayBuffer[Metric]) {
    this(listt, new HashMap[String, Int]())
    
    for (m <- list) {
      if (m.isEpoch()) {
        epochID = m.id
      }
    }
  }
  
  def size() : Int = {
    list.size
  }
} 
开发者ID:fschueler,项目名称:sysml-benchmark,代码行数:26,代码来源:Schema.scala

示例6: GlobalDeviceSet

//设置package包名称以及导入依赖的类
package rocketchip

import Chisel.log2Ceil
import cde.{Parameters, Field}
import scala.collection.mutable.HashMap
import junctions._

case object GlobalDeviceSet extends Field[DeviceSet]

case class Device(name: String, size: Int, dtype: String,
  readable: Boolean = true, writeable: Boolean = true)

class DeviceSet {
  val deviceMap = new HashMap[String, Device]()

  def addDevice(name: String, size: Int, dtype: String, readable: Boolean = true, writeable: Boolean = true): Unit =
      addDevice(Device(name, size, dtype, readable, writeable))

  def addDevice(dev: Device): Unit =
    deviceMap(dev.name) = dev

  def toSeq: Seq[Device] = deviceMap.values.toSeq

  def getAddrMap: AddrMap = {
    val devices = this.toSeq.sortWith((a, b) => a.size > b.size)
    val entries = devices.map { case Device(name, size, _, readable, writeable) =>
      val prot = (if (readable) AddrMapProt.R else 0) | (if (writeable) AddrMapProt.W else 0)
      AddrMapEntry(name, MemSize(size, MemAttr(prot)))
    }
    new AddrMap(entries)
  }
} 
开发者ID:shunshou,项目名称:testrocket-chip,代码行数:33,代码来源:DeviceSet.scala

示例7: AkkademyDb

//设置package包名称以及导入依赖的类
package com.akkademy

import akka.actor.Actor
import akka.event.Logging
import akka.actor.Status
import scala.collection.mutable.HashMap

import com.akkademy.messages._

class AkkademyDb extends Actor {
    val map = new HashMap[String, Object]
    val log = Logging(context.system, this)

    override def receive = {
        case SetRequest(key, value) => {
            log.info("received SetRequest - key: {}  - value: {}", key, value)
            map.put(key, value)
            sender() ! Status.Success(key)
        }
        case SetIfNotExistsRequest(key, value) => {
            log.info("received SetIfNotExistsRequest - key: {}  - value: {}", key, value)
            if (!map.contains(key)) map.put(key, value)
            sender() ! Status.Success(key)
        }
        case GetRequest(key) => {
            log.info("received GetRequest - key {}", key)
            map.get(key) match {
                case Some(value) => sender() ! value
                case None => sender() ! Status.Failure (KeyNotFoundException(key))
            }
        }
        case DeleteRequest(key) => {
            log.info("received DeleteRequest - key {}", key)
            if (map.contains(key)) {
                map -= key
                sender() ! Status.Success(key)
            } else {
                sender() ! Status.Failure(KeyNotFoundException(key))
            }
        }
        case o => {
            log.info("received unknown message: {}", o);
            sender() ! Status.Failure (new ClassNotFoundException)
        }
    }
} 
开发者ID:miguelsaddress,项目名称:akkademy-db,代码行数:47,代码来源:AkkademyDb.scala

示例8: CSPElementEqual

//设置package包名称以及导入依赖的类
package gregd.cspsolve.constraint

import gregd.cspsolve.log.MyLogger
import gregd.cspsolve.solve.CSPVar
import gregd.cspsolve.solve.CSPConstraint
import gregd.cspsolve.solve.CSPElement
import scala.collection.mutable.HashMap

object CSPElementEqual {
  val logger = new MyLogger("CSPElementEqual") 
}


class CSPElementEqual(varRange : Array[CSPVar], el : CSPElement, count : Int) extends CSPConstraint {
	val vars = new scala.collection.immutable.HashSet[CSPVar]() ++ varRange
  
    def getSatisfaction(varsEls : HashMap[CSPVar, scala.collection.mutable.HashSet[CSPElement]]) : Double = {
	  
	  val elCount = vars.:\((0, 0)){
	    (curVar, curCount) => 
	      val (ofOneCount, multCount) = curCount
	    val domain = varsEls.get(curVar).getOrElse{
	      CSPElementEqual.logger.error("mapping of variables does not contain CSPVar " + curVar)
	      throw new IllegalArgumentException("map does not contain necessary variable")
	    }
	    
	     (domain.contains(el), domain.size == 1) match {
	       case (true, true) => (ofOneCount + 1, multCount + 1)
	       case (true, false) => (ofOneCount, multCount + 1)
	       case _ => curCount
	     }
	  }
	  
	  val (oneElement, multElements) = elCount
	  
      if (oneElement > count || multElements < count) 0.0
      else 1.0
    }

	
    def getEffectedVars() : scala.collection.immutable.HashSet[CSPVar] = vars  
} 
开发者ID:gdicristofaro,项目名称:CSPSolver,代码行数:43,代码来源:CSPElementEqual.scala

示例9: CSPElementMax

//设置package包名称以及导入依赖的类
package gregd.cspsolve.constraint

import gregd.cspsolve.log.MyLogger
import gregd.cspsolve.solve.CSPElement
import gregd.cspsolve.solve.CSPVar
import gregd.cspsolve.solve.CSPConstraint
import scala.collection.mutable.HashMap

object CSPElementMax {
  val logger = new MyLogger("CSPElementMax") 
}


class CSPElementMax(varRange : Array[CSPVar], el : CSPElement, count : Int) extends CSPConstraint {
	val vars = new scala.collection.immutable.HashSet[CSPVar]() ++ varRange
  
    def getSatisfaction(varsEls : HashMap[CSPVar, scala.collection.mutable.HashSet[CSPElement]]) : Double = {
	  
	  val elCount = vars.:\(0){
	    (curVar, curCount) => 
	    val domain = varsEls.get(curVar).getOrElse{
	      CSPElementMax.logger.error("mapping of variables does not contain CSPVar " + curVar)
	      throw new IllegalArgumentException("map does not contain necessary variable")
	    }
	    
	     if (domain.size == 1 && domain.contains(el)) curCount + 1
	     else curCount
	  }
      if (elCount > count) 0.0
      else 1.0
    }

	
    def getEffectedVars() : scala.collection.immutable.HashSet[CSPVar] = vars  
} 
开发者ID:gdicristofaro,项目名称:CSPSolver,代码行数:36,代码来源:CSPElementMax.scala

示例10: CSPPairEither

//设置package包名称以及导入依赖的类
package gregd.cspsolve.constraint

import gregd.cspsolve.log.MyLogger
import gregd.cspsolve.solve.CSPVar
import gregd.cspsolve.solve.CSPConstraint
import scala.collection.mutable.HashMap
import gregd.cspsolve.solve.CSPElement

object CSPPairEither {
	val logger = new MyLogger("CSPPairEither")	
}

class CSPPairEither(var1 : CSPVar, var2 : CSPVar) extends CSPConstraint {
	val vars = scala.collection.immutable.HashSet[CSPVar](var1, var2)
  
    def getSatisfaction(varsEls : HashMap[CSPVar, scala.collection.mutable.HashSet[CSPElement]]) : Double = {
	  val var1Dom = varsEls.get(var1).getOrElse{
		  CSPPairEither.logger.error("mapping of variables does not contain CSPVar 1")
	      throw new IllegalArgumentException("map does not contain necessary variable")}
	      
	  val var2Dom = varsEls.get(var2).getOrElse{
		  CSPPairEither.logger.error("mapping of variables does not contain CSPVar 2")
	      throw new IllegalArgumentException("map does not contain necessary variable")}
	  
	  val toReturn =
	    if (var1Dom.size > 1 || var2Dom.size > 1 || var1Dom != var2Dom) 1.0
	    else 0.0
	  
	  CSPPairEither.logger.debug(
	      "var 1: " + var1 + " domain is " + var1Dom + 
	      "var 2: " + var2 + " domain is " + var2Dom +
	      " resulting score is " + toReturn + " (absolute: " + isAbsolute + ")")
	      
	  toReturn
    }

    def getEffectedVars() : scala.collection.immutable.HashSet[CSPVar] = vars
} 
开发者ID:gdicristofaro,项目名称:CSPSolver,代码行数:39,代码来源:CSPPairEither.scala

示例11: CSPElementMin

//设置package包名称以及导入依赖的类
package gregd.cspsolve.constraint

import gregd.cspsolve.log.MyLogger
import gregd.cspsolve.solve.CSPVar
import gregd.cspsolve.solve.CSPElement
import gregd.cspsolve.solve.CSPConstraint
import scala.collection.mutable.HashMap

object CSPElementMin {
  val logger = new MyLogger("CSPElementMin") 
}


class CSPElementMin(varRange : Array[CSPVar], el : CSPElement, count : Int) extends CSPConstraint {
	val vars = new scala.collection.immutable.HashSet[CSPVar]() ++ varRange
  
    def getSatisfaction(varsEls : HashMap[CSPVar, scala.collection.mutable.HashSet[CSPElement]]) : Double = {
	  
	  val elCount = vars.:\(0){
	    (curVar, curCount) => 
	    val domain = varsEls.get(curVar).getOrElse{
	      CSPElementMin.logger.error("mapping of variables does not contain CSPVar " + curVar)
	      throw new IllegalArgumentException("map does not contain necessary variable")
	    }
	    
	     if (domain.contains(el)) curCount + 1
	     else curCount
	  }
      if (elCount < count) 0.0
      else 1.0
    }

	
    def getEffectedVars() : scala.collection.immutable.HashSet[CSPVar] = vars  
} 
开发者ID:gdicristofaro,项目名称:CSPSolver,代码行数:36,代码来源:CSPElementMin.scala

示例12: CSPDifferentElementInRange

//设置package包名称以及导入依赖的类
package gregd.cspsolve.constraint

import gregd.cspsolve.log.MyLogger
import gregd.cspsolve.solve.CSPConstraint
import gregd.cspsolve.solve.CSPElement
import gregd.cspsolve.solve.CSPVar
import scala.collection.mutable.HashMap

object CSPDifferentElementInRange {
  val logger = new MyLogger("CSPDifferentElementInRange") 
}


class CSPDifferentElementInRange(varRange : List[CSPVar], el : List[CSPElement], count : Int) extends CSPConstraint {
	val vars = new scala.collection.immutable.HashSet[CSPVar]() ++ varRange
	
	val checkEls = new scala.collection.immutable.HashSet[CSPElement]() ++ el
  
	private def overList(allVars : HashMap[CSPVar, scala.collection.mutable.HashSet[CSPElement]], 
	    vars : List[CSPVar], checkEls :scala.collection.immutable.HashSet[CSPElement], els : scala.collection.immutable.HashSet[CSPElement], countLeft : Int) : Double = {
	  vars match {
	    case Nil => 1.0
	    case v :: tl =>
	      val curDomain = allVars.get(v).getOrElse{
		      CSPElementMax.logger.error("mapping of variables does not contain CSPVar " + v)
		      throw new IllegalArgumentException("map does not contain necessary variable")
		    }
	      
	      //CSPDifferentElementInRange.logger.debug("curDomain is " + curDomain + " size is " + curDomain.size + " contained )
	      
	      
	      if (curDomain.size == 1 && checkEls.contains(curDomain.head) && !els.contains(curDomain.head)) {	        
	        if (countLeft <= 0) 0.0
	        else overList(allVars, tl, checkEls, els ++ curDomain, countLeft - 1)
	      }
	      else overList(allVars, tl, checkEls, els, countLeft)
	  }
	}
	
    def getSatisfaction(varsEls : HashMap[CSPVar, scala.collection.mutable.HashSet[CSPElement]]) : Double = {
		overList(varsEls, varRange, checkEls, new scala.collection.immutable.HashSet[CSPElement], count)
    }

	
    def getEffectedVars() : scala.collection.immutable.HashSet[CSPVar] = vars  
} 
开发者ID:gdicristofaro,项目名称:CSPSolver,代码行数:47,代码来源:CSPDifferentElementInRange.scala

示例13: CSPPairBoth

//设置package包名称以及导入依赖的类
package gregd.cspsolve.constraint

import gregd.cspsolve.log.MyLogger
import gregd.cspsolve.model.ModelConstraint
import gregd.cspsolve.constraintarg.VarArg
import gregd.cspsolve.constraintarg.ConstraintArg
import gregd.cspsolve.solve.CSPConstraint
import gregd.cspsolve.solve.CSPVar
import scala.collection.mutable.HashMap
import gregd.cspsolve.solve.CSPElement


object CSPPairBoth {
	val logger = new MyLogger("CSPPairBoth")	
}

class CSPPairBoth(var1 : CSPVar, var2 : CSPVar, els : List[CSPElement]) extends CSPConstraint {
	val vars = scala.collection.immutable.HashSet[CSPVar](var1, var2)
	
	val consideredEls = scala.collection.immutable.HashSet[CSPElement]() ++ els
  
    def getSatisfaction(varsEls : HashMap[CSPVar, scala.collection.mutable.HashSet[CSPElement]]) : Double = {
	  val var1Dom = varsEls.get(var1).getOrElse{
		  CSPPairBoth.logger.error("mapping of variables does not contain CSPVar 1 " + var1)
	      throw new IllegalArgumentException("map does not contain necessary variable")}
	      
	  val var2Dom = varsEls.get(var2).getOrElse{
		  CSPPairBoth.logger.error("mapping of variables does not contain CSPVar 2 " + var2)
	      throw new IllegalArgumentException("map does not contain necessary variable")}
	  
	  //println("getting here...")
	  
	  //if the only elements in a domain are the elements to be considered, then do a check
	  //otherwise it could be fine
	  if ((var1Dom.intersect(consideredEls).size == var1Dom.size)
	      || (var2Dom.intersect(consideredEls).size == var2Dom.size)) {
	    
	      if (var1Dom.intersect(var2Dom).size > 0) 1.0
		  else {
		    //println("dom of " + var1 + " is + " + var1Dom + " and for " + var2 + " is " + var2Dom + " with included dom of " + consideredEls)
		    0.0
		  }
	  }
	  else 1.0 
    }

    def getEffectedVars() : scala.collection.immutable.HashSet[CSPVar] = vars
}






 
开发者ID:gdicristofaro,项目名称:CSPSolver,代码行数:49,代码来源:CSPPairBoth.scala

示例14: AkkademyDb

//设置package包名称以及导入依赖的类
package com.example

import akka.actor.{Actor, Status}
import akka.event.Logging

import scala.collection.mutable.HashMap



class AkkademyDb extends Actor{
  val map = new HashMap[String, Object]
  val log = Logging(context.system, this)

  override def receive = {
    case SetRequest(key, value) => {
      log.info(s"received SetRequest - key: {$key} value: {$value}")
      map.put(key,value)
    }
    case others => log.info(s"received unknown messages: {$others}")
  }

}

class ScalaPongActor extends Actor{
  override def receive: Receive = {
    case "ping" => sender() ! "pong"
    case _ => sender() ! Status.Failure(new Exception("unknow message"))
  }
} 
开发者ID:hanchenyi,项目名称:FirstAkkaProject,代码行数:30,代码来源:AkkademyDb.scala

示例15: Matrix

//设置package包名称以及导入依赖的类
package matrix

import scala.collection.mutable.HashMap
import scala.collection._

class Matrix[N <: AnyVal](val rows: Int, val cols: Int) {

  private var entries: HashMap[Tuple2[Int, Int], N] = new HashMap()

  def shape: Tuple2[Int, Int] = (rows, cols)

  def shapeAsString: String = rows + "×" + cols

  
  def apply(i: Int, j: Int) = {
    if (0 <= i && i < rows && 0 <= j && j < cols) {
      if (entries contains (i, j))
        entries(i, j)
      else 0
    }
    throw new IndexOutOfBoundsException("Index " + (i, j) + " is invalid for a " + shapeAsString + " matrix")
  }

  def isSquare: Boolean = (rows == cols)

}

abstract class MatrixIterator[N <: AnyVal](val m: Matrix[N]) extends AbstractIterator[N] {
  private var i: Int = 0
  private var j: Int = 0

  override def hasNext = (i >= m.rows && j >= m.cols)

  override def next = {
    // Moving horizontally
    val res = m(i, j)
    j += 1
    // then vertically
    // I'd love a way to signal the end of a row, but () (type Unit) won't work because it extends AnyRef, not AnyVal.
    if (j >= m.cols) {
      j = 0  // CR
      i += 1 // LF
    }
    res
  }
} 
开发者ID:aidan-fitz,项目名称:math2941,代码行数:47,代码来源:matrix.scala


注:本文中的scala.collection.mutable.HashMap类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。