You want to find `toReplace` in `list` and replace...
# announcements
k
You want to find
toReplace
in
list
and replace it with
replacement
? Because the code doesn't require an exact match right now.
d
Yep, this is only a very simplified example, you can be sure that
toReplace
is part of the
list
k
Copy code
replaceInList(listOf(1,2,1,5,2), listOf(1,5,2), listOf(6))
d
The result would be listOf(1, 2, 6)
k
But that's not what your example code does, right?
d
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
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
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
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
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
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]
but your code would produce
[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
Copy code
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)
}