DoSofRedRiver
DoSofRedRiver

Reputation: 420

Best way to fill an array with elements from another array, scala

I got two array of characters, looking like this:

a, b, c, d, e, f, g

k, e, y

and im need to associate each element from first array to elements from second, like this:

a->k,

b->e,

c->y,

d->k,

e->e,

f->y,

g->k

but dont know how to implement this in functional style. Any help will be appreciated!

Upvotes: 0

Views: 431

Answers (1)

Marth
Marth

Reputation: 24812

You could zip the first Array with a continuous Stream :

scala> val a1 = Array('a,'b,'c,'d,'e,'f,'g)
a1: Array[Symbol] = Array('a, 'b, 'c, 'd, 'e, 'f, 'g)

scala> val a2 = Array('k,'e,'y)
a2: Array[Symbol] = Array('k, 'e, 'y)

scala> val a3 = a1 zip (Stream.continually(a2).flatten)
a3: Array[(Symbol, Symbol)] = Array(('a,'k), ('b,'e), ('c,'y), ('d,'k),
                                    ('e,'e), ('f,'y), ('g,'k))

Upvotes: 7

Related Questions