1

I have two arrays of strings, say

A = ('abc', 'joia', 'abas8', '09ma09', 'oiam0') 

and

B = ('gfdg', '89jkjj', '09ma09', 'asda', '45645ghf', 'dgfdg', 'yui345gd', '6456ds', '456dfs3', 'abas8', 'sfgds'). 

What I want to do is simply to count the number of elements of every string in A that appears in B (if any). For example, the resulted array here should be: C = (0, 0, 1, 1, 0). How can I do that?

3 Answers 3

6

try this:

A.map( x => B.count(y => y == x)))
Sign up to request clarification or add additional context in comments.

1 Comment

I like this one better than my solution that uses foldLeft
3

You can do it how idursun suggested, it will work, but may be not efficient as if you'll prepare intersection first. If B is much bigger than A it will give massive speedup. 'intersect' method has better 'big-O' complexity then doing linear search for each element of A in B.

  val A = Array("abc", "joia", "abas8", "09ma09", "oiam0") 
  val B = Array("gfdg", "89jkjj", "09ma09", "asda", "45645ghf", "dgfdg", "yui345gd", "6456ds", "456dfs3", "abas8", "sfgds")

  val intersectCounts: Map[String, Int] =
    A.intersect(B).map(s => s -> B.count(_ == s)).toMap

  val count = A.map(intersectCounts.getOrElse(_, 0))

  println(count.toSeq)

Result

(0, 0, 1, 1, 0)

1 Comment

I don't think you need intersect and toMap. Just val intersectCounts = B.groupBy(identity).mapValues(_.size) should do the job. It's a bit faster too (still O(n+m), but less overhead).
0

Use a foldLeft construction as the yield off of each element of A:

  val A = List("a","b")
  val B = List("b","b")

  val C = for (a <- A) 
          yield B.foldLeft(0) { case (totalc : Int, w : String) =>
      totalc + (if (w == a) 1 else 0)
    }

And the result:

C: List[Int] = List(0, 2)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.