Scala counting scheme

My list is as follows: List(Person,Invite,Invite,Person,Invite,Person...). I am trying to match based inviteCountRequired, which means that the objects Invitefollowing the object Personin the list are variables. What is the best way to do this? My compliance code still looks like this:

aList match { 
     case List(Person(_,_,_),Invitee(_,_,_),_*) => ...
     case _ => ...
}

The first question is on the stack, please understand me easily.

+3
source share
3 answers

Thanks for your advice. I ended up creating another case class:

case class BallotInvites(person:Person,invites:List[Any])

Then I populated it from the source list:

def constructBallotList(ballots:List[Any]):List[BallotInvites] ={

  ballots.zipWithIndex.collect {
      case (iv:Ballot,i) =>{
                        BallotInvites(iv,
                          ballots.distinct.takeRight(ballots.distinct.length-(i+1)).takeWhile({
                            case y:Invitee => true
                            case y:Person =>true
                            case y:Ballot => false})
                          )}

  }}
val l = Ballot.constructBallotList(ballots) 

Then, to calculate based on inviteCountRequired, I did the following:

val count = l.count(b=>if ((b.invites.count(x => x.isInstanceOf[Person]) / contest.inviteCountRequired)>0) true else false )
0
source

Let be

val aList = List(Person(1), Invite(2), Invite(3), Person(2), Invite(4), Person(3), Invite(6), Invite(7))

Then index each place in the list and select Personinstances,

val persons = (aList zip Stream.from(0)).filter {_._1.isInstanceOf[Person]}

, List((Person(1),0), (Person(2),3), (Person(3),5)). , Person,

val intervals = persons.map{_._2}.sliding(2,1).toArray
res31: Array[List[Int]] = Array(List(0, 3), List(3, 5))

,

val latest = aList.drop(intervals.last.last)  // last Person and Invitees not paired
val associations = intervals.map { case List(pa,pb,_*) => b.slice(pa,pb) } ++ latest

,

Array(List(Person(1), Invite(2), Invite(3)), List(Person(2), Invite(4)), List(Person(3), Invite(6), Invite(7)))

,

associations.map { a => 
  val person = a.take(1)
  val invitees = a.drop(1) 
  // ...
}

.

0

I'm not sure that I understand the domain, but you will only need to iterate once to create a list of people + invites the tuple.

sealed trait PorI
case class P(i: Int) extends PorI
case class I(i: Int) extends PorI

val l: List[PorI] = List(P(1), I(1), I(1), P(2), I(2), P(3), P(4), I(4))

val res = l.foldLeft(List.empty[(P, List[I])])({ case (res, t) =>
  t match {
    case p @ P(_) => (p, List.empty[I]) :: res
    case i @ I(_) => {
      val head :: tail = res
      (head._1, i :: head._2) :: tail
    }
  }
})

res // List((P(4),List(I(4))), (P(3),List()), (P(2),List(I(2))), (P(1),List(I(1), I(1))))
0
source

All Articles