Pattern visualizer
Encode and Decode Strings
The instinct is to join with a separator, and it fails the moment a payload contains that separator — there is no character you can reserve, because the input is arbitrary. The fix is to stop marking boundaries and start counting: write each string as its length, a '#' to say where the length stops, then the raw bytes. The decoder reads a number, jumps exactly that far, and never has to interpret the payload at all — so a '#' inside a string is just data, and an empty string is still a real entry. Animated on: strs = ["hi", "a#b", "", "cat"] — encode the list into one string, then decode it back to exactly the same list..
Length prefix, so no character is ever reserved
4 strings have to survive a round trip through ONE flat string. Any separator you pick can also appear inside a payload — "a#b" already contains a '#' — so the join has to carry a count, not just a mark.
1FUNCTION encode(strs)2 out <- ""3 FOR k <- 0 TO LENGTH(strs) - 14 out <- out + LENGTH(strs[k]) + "#" + strs[k]5 RETURN out6FUNCTION decode(s)7 res <- EMPTY LIST8 i <- 09 WHILE i < LENGTH(s)10 j <- INDEX OF "#" IN s FROM i11 n <- NUMBER(s[i .. j - 1])12 APPEND s[j + 1 .. j + n] TO res13 i <- j + 1 + n14 RETURN res
← / → step · space play · Home restart