JavaScript
function intersection( arrs, limit ) {
var result = [], posns = [];
var j, v, next, n = arrs.length, count = 1;
if( !n || limit <= 0 ) {
return result; // nothing to do
}
if( n === 1 ) {
// special case needed because main loop cannot handle this
for( j = 0; j < arrs[0].length && result.length < limit; ++ j ) {
v = arrs[0][j];
if( v === v ) {
result.push( v );
}
}
return result;
}
for( j = 0; j < n; ++ j ) {
if( !arrs[j].length ) {
return result; // no intersection
}
posns[j] = 0;
}
next = arrs[n-1][0];
++ posns[n-1];
while( true ) {
for( j = 0; j < n; ++ j ) {
do {
if( posns[j] >= arrs[j].length ) {
return result; // ran out of values
}
v = arrs[j][posns[j]++];
} while( v < next || v !== v );
if( v !== next ) {
count = 1;
next = v;
} else if( (++ count) >= n ) {
result.push( next );
if( result.length >= limit ) {
return result; // limit reached
}
if( posns[j] >= arrs[j].length ) {
return result; // ran out of values
}
next = arrs[j][posns[j]++];
count = 1;
}
}
}
}
function display( arrs, limit ) {
var o = document.createElement( 'div' );
o.innerText = '> ' + intersection(arrs,limit).join( ',' );
document.body.appendChild( o );
}
display([[0, 3, 8, 11], [1, 3, 11, 15]], 0);
display([[0, 3, 8, 11], [1, 3, 11, 15]], 1);
display([[0, 3, 8, 11], [1, 3, 11, 15]], 2);
display([[0, 3, 8, 11], [1, 3, 11, 15]], 3);
display([[0, 3, 8, 11], [1, 3, 11, 15]], 8);
display([[0, 3, 8, 11], [1, 3, 11, 15]], 20);
display([[3,6,7,7,11], [3,6,7,7,11]],...