Reputation: 445
I tried executing the below code in Scala shell:
var chars = ('a' to 'z').toArray.zipWithIndex
chars: Array[(Char, Int)] = Array((a,0), (b,1), (c,2), (d,3), (e,4), (f,5), (g,6),
(h,7), (i,8), (j,9), (k,10), (l,11), (m,12), (n,13), (o,14), (p,15), (q,16),
(r,17), (s,18), (t,19), (u,20), (v,21), (w,22), (x,23), (y,24), (z,25))
Now I want the index of every character in the array of tuples mentioned above to be updated by 1 i.e. 'a' at index 1 and z at index 26. How do I achieve this using the map function ?
Upvotes: 0
Views: 647
Reputation: 1099
Use,
var chars = ('a' to 'z').toArray.zipWithIndex
chars: Array[(Char, Int)] = Array((a,0), (b,1), (c,2), (d,3), (e,4), (f,5), (g,6),
(h,7), (i,8), (j,9), (k,10), (l,11), (m,12), (n,13), (o,14), (p,15), (q,16),
(r,17), (s,18), (t,19), (u,20), (v,21), (w,22), (x,23), (y,24), (z,25))
chars.map(x=>{val (a,b)=x;(a,b+1)}) // Here x is each `tuple` in `chars` array.
// `var (a,b) = x` de-structures(extracts) the tuple into `a and b` where `b`
// starts from `0`. To make it start from `1`, we use `b+1` for `each tuple` in
// `map` function
Or
val alpha = 'a' to 'z'
val s1 = alpha.zip(1 to alpha.size)
Upvotes: 1
Reputation: 22439
You could also do this:
('a' to 'z') zip (Stream from 1)
which would produce a Vector
. If you want an Array, simply apply toArray
as well.
Upvotes: 1
Reputation: 8711
Use zip instead of zipWithIndex. sample below
scala> var chars = ('a' to 'z').toArray.zip(Stream from 1)
chars: Array[(Char, Int)] = Array((a,1), (b,2), (c,3), (d,4), (e,5), (f,6), (g,7), (h,8), (i,9), (j,10), (k,11), (l,12), (m,13), (n,14), (o,15), (p,16), (q,17), (r,18), (s,19), (t,20), (u,21), (v,22), (w,23), (x,24), (y,25), (z,26))
scala>
scala> var chars = ('a' to 'z').toArray.zip(Stream from 100)
chars: Array[(Char, Int)] = Array((a,100), (b,101), (c,102), (d,103), (e,104), (f,105), (g,106), (h,107), (i,108), (j,109), (k,110), (l,111), (m,112), (n,113), (o,114), (p,115), (q,116), (r,117), (s,118), (t,119), (u,120), (v,121), (w,122), (x,123), (y,124), (z,125))
scala>
Upvotes: 1
Reputation: 2582
Like this
('a' to 'z').toArray.zipWithIndex.map(t => (t._1, t._2 + 1))
Upvotes: 1