Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: replace char at position i in String

I have an initial String (binary) looking like this :

val mask = "00000000000000000000000000000000" of length 32

Additionally, I have a list of positions i (0 <= i <= 31) at which I want the mask to have value 1.

For instance List(0,12,30,4) should give the following result :

mask = "10001000000010000000000000000010"

How can I do this efficiently in scala ?

Thank you

like image 297
Floran Gmehlin Avatar asked Sep 14 '25 15:09

Floran Gmehlin


1 Answers

A naive approach would be to fold over the positions with zero element 'mask' and successively update the char at the given position:

List(0,12,30,4).foldLeft(mask)((s, i) => s.updated(i, '1'))

- Daniel

like image 158
Daniel Dietrich Avatar answered Sep 17 '25 05:09

Daniel Dietrich