patch - Scala: subtract index of odd values -
for practical exercise need define function changes index of every value in odd index in list, this:
changepairs(list(1,2,3,4,5,6,7,8,9,10,11)) //> res62: list[int] = list(2, 1, 4, 3, 6, 5, 8, 7, 10, 9, 11) changepairs(list(2,2,30,4,50,6,7,80,9,100)) //> res63: list[int] = list(2, 2, 4, 30, 6, 50, 80, 7, 100, 9)
so need swap places of each odd-even pair, , in case i'm left single odd element @ last index (11 in first example), leave is.
i have it's not working, , i'm not sure why.
def changepairs(a: list[int]) = a.zipwithindex.map { case (s,i) => if (i % 2 != 0) a.patch(i,seq(s),1); a.patch(i-2,seq(s),0); }
here's 1 way:
def changepairs(a: list[int]) = a.grouped(2).flatmap { case list(a, b) => list(b, a) case => }.tolist changepairs(list(1, 2, 3, 4, 5, 6, 7)) // list(2, 1, 4, 3, 6, 5, 7)
main idea gets going once think of grouping list sublists of 2 elements, grouped(2)
does. on it's easy ride - describe 2 cases, 1 2 elements (in case flip them) , 1 1 element, such 7 in example, in case leave be. use flatmap
flatten resulting list of 2-element lists 1 big list, , .tolist
out of iterator got grouped
.
edit:
i saw a.grouped(2).map(_.reverse).flatten.tolist
in comments. yeah, works too, it's same less verbose since instead of "manually" swapping elements, reverse
on each sublist.
Comments
Post a Comment