Title
k

karelpeeters

02/06/2019, 10:13 PM
You want to find
``toReplace``
in
``list``
and replace it with
``replacement``
? Because the code doesn't require an exact match right now.
d

Daniel

02/06/2019, 10:19 PM
Yep, this is only a very simplified example, you can be sure that
``toReplace``
is part of the
``list``
k

karelpeeters

02/06/2019, 10:21 PM
``replaceInList(listOf(1,2,1,5,2), listOf(1,5,2), listOf(6))``
d

Daniel

02/06/2019, 10:22 PM
The result would be listOf(1, 2, 6)
k

karelpeeters

02/06/2019, 10:23 PM
But that's not what your example code does, right?
d

Daniel

02/06/2019, 10:26 PM
I hope I got the example right, the first sublist would be
``1, 2``
, then
``+ 6``
and the last sublist, yeah would throw an index out of bounds exception, I simplified a bit too much, it seems. Thank you for your reply!
k

karelpeeters

02/06/2019, 10:27 PM
Ah I wasn't even thinking about that, the main problem is that it only looks at the first and last elements for a match. Even the size doesn't matter!
d

Daniel

02/06/2019, 10:30 PM
Maybe I am thinking wrong here, but the sizes shouln't matter. So you could go with
``listOf(1,2,3,4)``
replace
``listOf(2,3)``
with
``listOf(6,7,8)``
or
``listOf(6)``
and should end up with
``listOf(1,6,7,8,4)``
or
``listOf(1,6,4)``
so any replacement should be possible. For the
``toReplace``
you can be sure that it is part of the
``list``
k

karelpeeters

02/06/2019, 10:32 PM
Yes, but your code right now doesn't necessarily find the correct position for
``toReplace``
in
``list``
because it only checks the first and last positions. The size of
``toReplace``
and the matched part of
``list``
don't even have to match.
d

Daniel

02/06/2019, 10:54 PM
Ohhh, now I understand, sorry. In the original code the matching is done over identity. So you can be sure that the right element is found
n

nkiesel

02/07/2019, 12:43 AM
I think what you are trying to say is: "in the original code, the list does not contain any duplicate values". As soon as you have duplicates, the code might not do what you want. Consider original list is
``[1,1,1,2,2,2]``
and you want to replace
``[1,2]``
with
``[3]``
. I think you want
``[1,1,3,2,2]``
``[3,2,2]``
instead. But even that is not good enough because
``replaceInList(listOf(1,2,3,4,5), listOf(4,2), listOf(0))``
would produce
``[1,2,3,0,3,4,5]``
and
``replaceInList(listOf(1,2,3,4,5),listOf(1,5),listOf(0))``
would produce
``[0]``
a valid solution (assuming you only want to replace the fist match) would be
``````fun replaceInList(list: List<Int>, toReplace: List<Int>, replacement: List<Int>): List<Int> {
val i = list.windowed(toReplace.size).indexOfFirst { it == toReplace }
return if (i == -1) list else list.take(i) + replacement + list.drop(i + toReplace.size)
}``````