Take the 2-minute tour ×
Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

You are given an array of strings , you have to construct a single array containing all of them so that the same array of strings can be reconstructed from the large array. The strings may contain any ASCII character. How to determine length of the single large array?

Example= let a = ["asd";"dfg";"rew"]. Problem is to combine them in a single string in such a way that it can reconstructed. How to figure out the size of the string which will store the concatenation ?

share|improve this question
    
Why is it even an array? Shouldn’t the result just be one string? –  minitech Jul 6 '13 at 20:59
    
Simple - since ASCII is only 7 bits you can just use a value > 127 as a separator character between strings and some other value > 127 as a final terminator. –  Paul R Jul 6 '13 at 21:17
    
What are you actually asking for? A program? A mathematical expression of the output size as a function of input size? (The latter would seem to be ill-defined, because there are an infinite number of injections from arrays of strings to strings). –  Peter Taylor Jul 6 '13 at 21:50
add comment

2 Answers

JavaScript, 6

This evaluates to a function. Works in Firefox.

uneval
share|improve this answer
    
More portably: JSON.stringify –  recursive Oct 30 '13 at 1:40
    
@recursive: Oh, I missed that this wasn’t code golf. –  minitech Oct 30 '13 at 1:41
add comment

This was a very common in style in Apple ][ binaries. The high bit of the first character of each word was set. You know you can do this since ASCII was specifically mentioned and the high bit is never set for ASCII. This technique relies on strings that know their own length. We can assume this is the case, since the strings can "contain any ASCII" characters, so C style (null terminated) strings can't work.

For your example, using Python

>>> a = ["asd", "dfg", "rew"]
>>> ''.join(chr((ord(s[0])) | 128) + s[1:] for s in a)
'\xe1sd\xe4fg\xf2ew'

converting back to the original list

>>> (''.join('\x80'+chr((ord(c)) & 127) if c>'\x7f' else c for c in '\xe1sd\xe4fg\xf2ew')).split('\x80')[1:]
['asd', 'dfg', 'rew']
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.