Hi, How can i fill `prevItems` and `nextItems` of...
# announcements
k
Hi, How can i fill
prevItems
and
nextItems
of below data class , i have tried
recursion
but it caused infinite loop because we have to find next and previous both but if i try with either previous or next then there is no infinite loop.
data class Root(val item: Int, val prevItems: List<Root>, val nextItems: List<Root>)
Suppose i have data for
item
is => 1,2,3,4,5 then result i wanted is =>
Copy code
Root(item: 1, prevItems: [], nextItems: [2,3,4,5])
Root(item: 2, prevItems: [1], nextItems: [3,4,5])
Root(item: 3, prevItems: [1,2], nextItems: [4,5])
Root(item: 4, prevItems: [1,2,3], nextItems: [5])
Root(item: 5, prevItems: [1,2,3,4], nextItems: [])
*for making it short i am using 1,2,3… in prevItems/nextItems instead of
Root
object
what approach should i use to calculate above? also is there any kotlin collection function can help here ?
c
I tried to, but honestly I don't think it's possible with immutable data, because if you copy() the node to edit the previous node, it has a different identity than previously so it breaks the chain.
If you accept mutable data, or if you accept a one-way tree, it becomes trivial.
b
Builder pattern that uses mutable structures and converts them to immutable ones on build
Or you can have it as doubly linked list node and convert prev and next to dynamically computed properties
c
@Big Chungus I don't think it's possible. Because you can build neither the previous nor the next.
k
@CLOVIS I have no issues in using mutable structure, can you help me to achieve it
r
My first question would be first: why you want to do this? Do you really need the whole list in each element of list? It really looks more like double linked list as Marty said above - you would use much less memory, but still be able to easily compute those lists properties on demand
s
@Roukanken this is probably for Zipper Data structure (https://en.wikipedia.org/wiki/Zipper_%28data_structure%29) It is useful in pure functional programming.
r
It's similar yes, but he wants to have all the "zippeers" at all times - eg, a list of lenght N, would be represented by at least N^2 amount of data... which is an obscenely large amount. (At least that's how I understood his request)
b
Yeah, I imagine that it's possible to do this sort of thing with a calculated field and a tricky implementation of a
DoubleLinkedList.subList(i, j)
to avoid N^2 memory usage.
n
I am still a bit unclear on the actual question. Do you want to have a function that creates a list of <n>
Root
objects out of a list of <n> items? Or do you want a function that creates a single
Root
object out of a list of items and a given item?