Dr John Stockton said:
Q1 :
Given an array such as might have been generated by
var A = [,,2,,,,4,,,6,,,8,,,]
is there a highly effective way of reducing it to [2,4,6,8] - i.e.
removing the undefineds and shifting the rest down?
You want something faster than running through the array with a for
loop and testing each element. That means that the iteration (which
must be performed somehow) must happen in the interpreter, not the
interpreted code.
Do you have an idea how long the array is, and how sparse?
Is the active elements all numbers, or can they be any object?
Are the active elements always sorted?
Since we know that we need to use a built-in iteration, we should look
at the methods of the array property. I can't find any that looks
promising. Only sort and join really traverse the array, and both have
serious problems.
A.sort().slice(0,n) // would do it, but sorts; and the number
of active elements must be known.
Sorting is a problem if the elements aren't already sorted and the
order must be maintained. The efficiency will drop violently if you
add your own comparison function, and the sorting algorithm isn't
even guaranteed to be stable, so I don't think there is a workaround.
Apart from that, the extra work needed to find the number of active
elements would only be proportional ot the number of active elements,
not the length of the array, so there might be a saving there if
sorting the elements is acceptable.
A.join('#').split(/#+/) // looks inefficient
It might be inneficient, but at least the iteration is performed by
efficient non-interpreted code. I won't wager on how efficient it is
without trying first.
However, it has problems. The first and last elements might become
empty strings (but that is easily checked for). Joining and splitting
turns all the active elements into strings. If one of them was the
empty string already, it will even fail.
If the elements are all numbers, it should work.
Q2 :
Is anything exact known about the internal mechanism of Math.random() ?
Do later browsers provide access to the seed value?
I don't know anything about the browsers' implementations. There is
nothing mandatory about it. Neither Javascript 1.5 nor ECMAScript
says anything except the range of the function. Quote from ECMA262:
---
random ( )
Returns a number value with positive sign, greater than or equal to 0
but less than 1, chosen randomly or pseudo randomly with
approximately uniform distribution over that range, using an
implementation-dependent algorithm or strategy. This function takes
no arguments.
---
Microsoft says that their Math.random is automatically seeded when
JScript is first loaded. Apart from that, there is very little
documentation.
<URL:
http://msdn.microsoft.com/library/en-us/script56/html/js56jsmthrandom.asp>
/L