本文整理汇总了Scala中scala.collection.mutable.HashSet类的典型用法代码示例。如果您正苦于以下问题:Scala HashSet类的具体用法?Scala HashSet怎么用?Scala HashSet使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了HashSet类的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: ProblemTwelve
//设置package包名称以及导入依赖的类
package org.nason.euler.ten
import scala.collection.mutable.HashSet
object ProblemTwelve {
def main(args: Array[String]) {
println( solution3 )
}
val MAX = 500
def allFactors( v:Int ) =
{
val max = Math.floor(Math sqrt( v )).toInt
( for ( i<-1 to max; if v%i==0 ) yield (i, v/i) )
.foldLeft(List[Int]())( (a,b) => {
if ( b._1 == b._2 )
b._1 :: a
else
b._1 :: b._2 :: a
} )
}
def unique[A]( v:Iterable[A] ) =
{
val all = new HashSet[A]()
v foreach ( all += _ )
all.toList
}
def solution =
{
val i = ( 1 to 100000 ) map ( i => i*(i+1)/2 ) map (allFactors(_).length) takeWhile( _ <= MAX )
val n = i.length + 1
n * (n+1) / 2
}
def solution3 =
{
def nFactorsTriangle( n:Int ) = n%2 match
{
case 0 => allFactors(n/2).length * allFactors(n+1).length
case 1 => allFactors((n+1)/2).length * allFactors(n).length
}
val i = ( 1 to 100000 ) map( nFactorsTriangle(_) ) takeWhile( _ <= MAX )
val n = i.length + 1
n * (n+1) / 2
}
}
示例2: TaggedCorpus
//设置package包名称以及导入依赖的类
package util
import scala.io.Source
import scala.util.matching.Regex
import scala.collection.mutable.HashSet
abstract class TaggedCorpus {
val posSymbSet: HashSet[String]
def getSentIter: TaggedSentIter
}
abstract class PatternCorpus extends TaggedCorpus {
val filename: String
val pattern: Regex
// TODO: wrap in try/catch block or figure out how to deal with `source`
def getSentIter: TaggedSentIter = {
val source = Source.fromInputStream(getClass.getResourceAsStream(filename))
for (line <- source.reset().getLines() if line.trim.nonEmpty)
yield pattern.findAllMatchIn(line).map( m => TagTuple(m.group("word"),m.group("symb")) )
}
}
case class GeneCorpus(filename: String) extends PatternCorpus {
val pattern = new Regex("""([^\s\|]+)\|([^\s\|]+)""", "word", "symb")
val posSymbSet = HashSet("I-GENE")
}
case class WikiCorpus(filename: String) extends PatternCorpus {
val pattern = new Regex("""([^\s\|]+)\|([^\|]+)\|([^\s\|]+)""", "word", "POS", "symb")
val posSymbSet = HashSet("I-MISC","I-PER","I-ORG","I-LOC")
}
示例3: PageTracker
//设置package包名称以及导入依赖的类
import akka.actor.Actor
import scala.collection.mutable.{HashSet, Set}
class PageTracker extends Actor {
var pages: Set[Page] = new HashSet[Page]()
def receive = {
case PageCheck(page, replyTo) => {
if (pages.contains(page)) {
replyTo ! DoNotCrawl(page)
} else {
pages.add(page)
replyTo ! DoCrawl(page)
}
}
case RemovePage(page) => {
pages.remove(page)
}
}
}
示例4: ScraperController
//设置package包名称以及导入依赖的类
import akka.actor.{Actor, Cancellable, ActorRef, Props}
import UnitsScraper.{Scan, SearchResults}
import scala.collection.mutable.{HashMap, HashSet}
import scala.concurrent.duration._
//TODO: schedule checkup/removal at endtime. Future: bid-bot
class ScraperController extends Actor { //TODO: implement persistence in case of crash
import ScraperController._ //case classes defined in companion object
val searchCancelActorMap = new HashMap[SearchTerm, (ActorRef, Cancellable)]
val oldCategorizedResults = new HashMap[SearchTerm, Set[AuctionObject]]
val oldObjects = new HashSet[AuctionObject]
val serverActor = context.actorOf(Props[WebServer], name = "Server")
val pushbullet = context.actorOf(Props[PushAPI], name = "Pushbullet")
val system = akka.actor.ActorSystem("system")
def receive = {
case SearchResults(result) => {
val searchTerm = sender.path.name
val newObjectsInCategory = result -- oldCategorizedResults.getOrElse(SearchTerm(searchTerm), new HashSet[AuctionObject])
serverActor ! NewCategoryResults(searchTerm, newObjectsInCategory)
if (Preferences.isPushbulletActive && !Preferences.NeedtoConfigure) {
for (obj <- newObjectsInCategory) {
pushbullet ! pushLink(s"""New auction object in search "$searchTerm": ${obj.title}""", obj.link)
}
}
oldCategorizedResults(SearchTerm(searchTerm)) = result
}
case NewSearchTerm(s) => {
val sT = SearchTerm(s)
//creates an actor in this context, i.e. a child actor
val actor = context.actorOf(Props[UnitsScraper], name = s)
//sets the ExecutionContext for the message sending task
import system.dispatcher
//sets a schedule to scan the search page every 5 minutes, starting in 200 milliseconds
val cancel: Cancellable = system.scheduler.schedule(200 milliseconds, 5 minutes, actor, Scan)(sender = context.self, executor = system.dispatcher)
searchCancelActorMap += (sT -> ((actor, cancel)))
}
case DeleteSearchTerm(s) => {
val sT = SearchTerm(s)
val actorCancelTuple = searchCancelActorMap(sT)
actorCancelTuple._2.cancel
context stop actorCancelTuple._1
searchCancelActorMap -= sT
}
case WebServer.Shutdown => context.system.terminate
}
}
object ScraperController {
case class SearchTerm(s: String)
case class NewSearchTerm(s: String)
case class DeleteSearchTerm(s: String)
case class NewCategoryResults(searchTerm: String, objects: Set[AuctionObject])
}
示例5: StopwordDict
//设置package包名称以及导入依赖的类
package edu.berkeley.nlp.summ.data
import scala.collection.mutable.HashSet
object StopwordDict {
// N.B. This set was extracted from the RST treebank (train and test) mostly to reproduce
// Hirao's results; it shouldn't really be used for other things
val stopwords = Set("!", "", "#", "$", "%", "&", "'", "''", "'S", "'s", "()", ",", "-", "--", "-owned", ".", "", ":", ";", "<", "?", "",
"A", "A.", "", "AND", "After", "All", "Am", "An", "And", "Any", "As", "At", "BE", "Between", "Both", "But", "By", "Each",
"Few", "For", "From", "Had", "He", "Here", "How", "I", "If", "In", "Is", "It", "Its", "MORE", "More", "Most", "NO", "No", "No.",
"Not", "OF", "Of", "On", "One", "Only", "Or", "Other", "Our", "Over", "She", "So", "Some", "Such", "THE", "Than", "That", "The",
"Their", "Then", "There", "These", "They", "Those", "To", "UPS", "Under", "Until", "WHY", "We", "What", "When", "While", "Why",
"Would", "You", "`It", "``", "a", "about", "above", "after", "again", "again.", "", "against", "all", "am", "an", "and", "any",
"as", "at", "be", "been", "being", "below", "between", "both", "but", "by", "ca", "can", "could", "did", "do", "doing", "down",
"each", "few", "for", "from", "further", "had", "have", "having", "he", "her", "here", "herself", "him", "him.", "", "himself",
"how", "if", "in", "into", "is", "it", "its", "itself", "let", "lets", "me", "more", "most", "must", "my", "n't", "no", "nor",
"not", "of", "off", "on", "one", "ones", "only", "or", "other", "others", "ought", "our", "out", "over", "own", "owned", "owns",
"same", "she", "should", "so", "some", "such", "than", "that", "the", "their", "them", "then", "there", "these", "they", "those",
"through", "to", "too", "under", "until", "up", "very", "we", "were", "what", "when", "where", "which", "while", "who", "whom",
"why", "with", "wo", "would", "you", "your", "yourself", "{", "}")
// Leave $ in there
val stopwordTags = new HashSet[String] ++ Array("CC", "DT", "EX", "IN", "LS", "MD", "PDT", "POS", "PRN", "PRP", "PRP$", "RP", "SYM",
"TO", "WDT", "WP", "WP$", "WRB", ".", ",", "``", "''", ";", ":", "-LRB-", "-RRB-", "-LSB-", "-RSB-", "-LCB-", "-RCB-")
}
示例6: ElimSuperfluousDimNodesVisitor
//设置package包名称以及导入依赖的类
package polyite.schedule.schedule_tree.normalization
import polyite.schedule.schedule_tree.DimNode
import polyite.schedule.schedule_tree.BandNode
import polyite.schedule.schedule_tree.LeafNode
import polyite.schedule.schedule_tree.ScheduleNode
import scala.collection.mutable.HashSet
import polyite.schedule.schedule_tree.ScheduleNodeVisitorLeaveNDegUnchanged
import isl.VoidCallback1
import isl.Conversions._
import polyite.schedule.schedule_tree.ScheduleTreeConstruction
import polyite.schedule.schedule_tree.util.SchedTreeUtil
import polyite.schedule.schedule_tree.BandNodeLoop
import polyite.schedule.schedule_tree.SimpleBandNode
class ElimSuperfluousDimNodesVisitor extends ScheduleNodeVisitorLeaveNDegUnchanged {
override def toString() : String = "eliminate superfluous dim nodes."
def visit(t : DimNode) : ScheduleNode = {
var domainStmts : HashSet[String] = HashSet.empty
t.getDomain.foreachSet((s : isl.Set) => {
domainStmts.add(s.getTupleName)
})
val domainStmtsArr : Array[String] = domainStmts.toArray
var canEliminate : Boolean = true
for (i <- 0 until domainStmtsArr.size) {
val s1 : String = domainStmtsArr(i)
for (j <- i until domainStmtsArr.size) {
val s2 : String = domainStmtsArr(j)
val stmts : Set[String] = Set(s1, s2)
val schedPrefix : List[isl.UnionMap] = if (t.isRoot)
List.empty
else {
t.getFather.getSchedulePrefix(stmts)
}
val order = SchedTreeUtil.calcOrder(t.getSched, schedPrefix, s1, s2, t.getDomain)
if (order.isDefined && !order.get.isZeroOnly)
canEliminate = false
}
}
if (canEliminate)
return t.getChild.accept(this)
return new DimNode(t.getDomain, t.getSched, t.getChild.accept(this))
}
private def handleBandNodes : ScheduleNode = throw new UnsupportedOperationException("Operation is not implemented for BandNodes.")
def visit(t : SimpleBandNode) : ScheduleNode = handleBandNodes
def visit(t : BandNodeLoop) : ScheduleNode = handleBandNodes
def visit(t : LeafNode) : ScheduleNode = t
}
示例7: toString
//设置package包名称以及导入依赖的类
package sbt
import java.io.File
import scala.collection.mutable.{HashSet, Set}
trait Format[T] extends NotNull
{
def toString(t: T): String
def fromString(s: String): T
}
abstract class SimpleFormat[T] extends Format[T]
{
def toString(t: T) = t.toString
}
object Format
{
def path(basePath: Path): Format[Path] = new Format[Path]
{
def toString(path: Path) = Path.relativize(basePath.asFile, path.asFile).getOrElse(error("Path " + path + " not in " + basePath))
def fromString(s: String) = Path.fromString(basePath, s)
}
implicit val file: Format[File] = new Format[File]
{
def toString(file: File) = file.getAbsolutePath
def fromString(s: String) = (new File(s)).getAbsoluteFile
}
implicit val hash: Format[Array[Byte]] = new Format[Array[Byte]]
{
def toString(hash: Array[Byte]) = Hash.toHex(hash)
def fromString(hash: String) = Hash.fromHex(hash)
}
def set[T](implicit format: Format[T]): Format[Set[T]] = new Format[Set[T]]
{
def toString(set: Set[T]) = set.toList.map(format.toString).mkString(File.pathSeparator)
def fromString(s: String) = (new HashSet[T]) ++ FileUtilities.pathSplit(s).map(_.trim).filter(!_.isEmpty).map(format.fromString)
}
implicit val string: Format[String] = new SimpleFormat[String] { def fromString(s: String) = s }
implicit val test: Format[TestDefinition] = new SimpleFormat[TestDefinition]
{
def fromString(s: String) = TestParser.parse(s).fold(error, x => x)
}
}
示例8: DagSpecification
//设置package包名称以及导入依赖的类
package sbt
import org.scalacheck._
import Prop._
import scala.collection.mutable.HashSet
object DagSpecification extends Properties("Dag")
{
specify("No repeated nodes", (dag: TestDag) => isSet(dag.topologicalSort))
specify("Sort contains node", (dag: TestDag) => dag.topologicalSort.contains(dag))
specify("Dependencies precede node", (dag: TestDag) => dependenciesPrecedeNodes(dag.topologicalSort))
implicit lazy val arbTestDag: Arbitrary[TestDag] = Arbitrary(Gen.sized(dagGen))
private def dagGen(nodeCount: Int): Gen[TestDag] =
{
val nodes = new HashSet[TestDag]
def nonterminalGen(p: Gen.Params): Gen[TestDag] =
{
for(i <- 0 until nodeCount; nextDeps <- Gen.someOf(nodes).apply(p))
nodes += new TestDag(i, nextDeps)
for(nextDeps <- Gen.someOf(nodes)) yield
new TestDag(nodeCount, nextDeps)
}
Gen.parameterized(nonterminalGen)
}
private def isSet[T](c: Seq[T]) = Set(c: _*).size == c.size
private def dependenciesPrecedeNodes(sort: List[TestDag]) =
{
val seen = new HashSet[TestDag]
def iterate(remaining: List[TestDag]): Boolean =
{
remaining match
{
case Nil => true
case node :: tail =>
if(node.dependencies.forall(seen.contains) && !seen.contains(node))
{
seen += node
iterate(tail)
}
else
false
}
}
iterate(sort)
}
}
class TestDag(id: Int, val dependencies: Iterable[TestDag]) extends Dag[TestDag]
{
override def toString = id + "->" + dependencies.mkString("[", ",", "]")
}
示例9: Processor
//设置package包名称以及导入依赖的类
package de
import scala.annotation.tailrec
import java.util.concurrent.ConcurrentHashMap
import scala.collection.mutable.HashSet
class Processor(implicit granter:Granter, mapping: ConcurrentHashMap[(Long,Long), HashSet[Long]]) extends Runnable{
@tailrec
private def divisorsOf(num:Long, curr:Long=1, acc: List[Long]=Nil) : List[Long] = num match {
case x if(x==curr) => x::acc
case x if((x.toDouble % curr)==0) => divisorsOf(num, curr+1, curr::acc)
case _ => divisorsOf(num, curr+1, acc)
}
@tailrec
private def gcd(x: Long, y: Long): Long = if(y==0) x else gcd(y, x % y)
override def run(){
var task = granter.get()
while(!task.eq(None)){
for {
n <- task.get.starts to task.get.ends
} {
val divs = divisorsOf(n)
val divsSum = divs.sum
val gcdVal = gcd(n, divsSum)
val numerator = divsSum/gcdVal
val denominator = n/gcdVal
//println(n)
val id = (numerator, denominator)
var l : HashSet[Long] = null
mapping.synchronized{
l = mapping.get(id)
if(l==null){
l = HashSet[Long]()
mapping.put(id, l)
}
}
l.synchronized{ l.+=(n) }
}
task = granter.get(task.get)
}
}
}