views:

104

answers:

4

I have a huge "binary" string, like: 1110 0010 1000 1111 0000 1100 1010 0111....

It's length is 0 modulo 4, and may reach 500,000.

I have also a corresponding array: {14, 2, 8, 15, 0, 12, 10, 7, ...}

(every number in the array corresponds to 4 bits in the string)

Given this string, this array, and a number N, I need to calculate the following substring string.substr(4*N, 4), i.e.:

for N=0 the result should be 1110

for N=1 the result should be 0010

I need to perform this task many many times, and my question is what would be the fastest method to calculate this substring ?

One method is to calculate the substring straight forward: string.substr(4*N, 4). I'm afraid this one is not efficient for such huge strings.

Another method is to use array[N].toString(2) and then wrap the result with zeros if needed. I'm not sure how fast is this.

May be you have any other ideas ?

+1  A: 

You could consider representing your huge string as a Rope data structure. A rope is basically a binary tree whose leaves are arrays of characters. A node in the tree has a left child and a right child, the left child being the first part of the string, while the right child the final part.

By using a rope, substring operations become logarithmic in complexity, rather then linear, as they are for regular strings.

luvieere
If he's going to split up the string like that, why not just split it up into a flat array? Then his lookups are **constant time** and not even logarithmic.
Pointy
@Pointy Had he an array, and not a string, that would work. But splitting the string into an array still requires calling substring to get the individual sections.
luvieere
+2  A: 
Pointy
Thanks @luvieere!
Pointy
lookup array.... genious ! Thanks !
Misha Moroshko
+1  A: 

If you want it padded, you could do this:

var elem = array[N]
var str = "" + ((elem>>3)&1) + ((elem>>2)&1) + ((elem>>1)&1) + (elem&1);
Eric
?? He said he's got a *string*, not an array. Your code assumes an array of numbers. Also, you get the binary strings backwards.
Pointy
`I have also a corresponding array ...`. Good point about the direction of the bits though.
Eric
@Pointy Strings *are* arrays...
Josh Stodola
@Josh no, in Javascript they're not exactly arrays. They don't have the methods that arrays have.
Pointy
However, the OP said he has an array as well as a string.
Eric
@Pointy True, but I don't see how that is relevant to the concerns of the OP
Josh Stodola
It isn't, but someday somebody else may be reading this page!
Pointy
+1  A: 

The array already has exactly what you need, does it not, save that you need to print it in binary format. Fortunately, sprintf for javascript is available.

mpez0