score:2

Accepted answer

update

i have shamelessly borrowed from the answer by truhland to give this improved version of my answer that does not fail with empty or single-element lists:

def createtuple(words: list[string]): map[tuple2[string, string], int] =
  words
    .zip(words.drop(1))
    .groupby(identity)
    .mapvalues(_.length)

original

you appear to be counting adjacent pairs of words is a list of words. if so, something like this should work:

def createtuple(words: list[string]): map[tuple2[string, string], int] =
  words
    .sliding(2)
    .map(l => (l(0), l(1)))
    .tolist
    .groupby(identity)
    .mapvalues(_.length)

this works as follows

  1. sliding(2) creates a list of adjacent pairs of words
  2. map turns each pair from a list into a tuple
  3. groupby groups the tuples with the same value
  4. mapvalues counts the number of pairs with the same value for each pair

this may not be quite what you want, but hopefully it gives an idea of how it might be done.

as a general rule, don't iterate through a list using an index, but try to transform the list into something where you can iterate through the values.

try to not create maps element-by-element. use groupby or tomap.

score:1

your big problem is that words is a list, and yet you are indexing into it with words(i). that's slow. change it to be a vector or rework your algorithm to not use indexing.

also, paircounts.exists is slow, you should use contains whenever possible, as it is constant time on a map.

score:1

if we first reduce your code to essence:

def createtuple(words: list[string]): map[(string, string), int] = {
    val paircounts = collection.mutable.map[(string, string), int]()
    for (i <- 0 until words.length - 1) {
      val pair = (words(i), words(i + 1))
      paircounts += (pair  -> (paircounts.getorelse(pair, 0) + 1))
    }
    paircounts.tomap
  }

to improve speed, don't use indexing on list (as mentioned elsewhere):

def createtuple(words: list[string]): map[(string, string), int] = {
  val map = collection.mutable.map[(string, string), int]()
  words
    .zip(words.tail)
    .foreach{ pair => 
       map += (pair -> (map.getorelse((pair, 0) + 1)) }
  map.tomap
}

Related Query

More Query from same tag