| Bytes | Lang | Time | Link |
|---|---|---|---|
| 065 | Tcl | 180506T234843Z | sergiol |
| 115 | Type The TS Type system | 250424T213723Z | General |
| 140 | APLNARS | 250424T194420Z | Rosario |
| 042 | Haskell | 160305T201326Z | nimi |
| nan | R | 190402T044206Z | d.b |
| 077 | PHP | 190402T172917Z | 640KB |
| 009 | Husk | 190401T214012Z | Unrelate |
| 051 | Python3 | 180507T060221Z | PieCot |
| 012 | Jelly | 171106T151632Z | hyperneu |
| 257 | Axiom | 171105T113905Z | user5898 |
| 411 | Axiom | 171105T101600Z | user5898 |
| 099 | Jq 1.5 | 171104T201119Z | jq170727 |
| 063 | Retina | 160308T230400Z | mbomb007 |
| 011 | Pyth | 160306T002314Z | izzyg |
| 037 | Perl 6 | 160305T232158Z | Hotkeys |
| 013 | Jelly | 160305T192237Z | Dennis |
| 184 | bash + GNU coreutils | 160305T223708Z | rexkogit |
| 066 | JavaScript ES6 | 160305T204537Z | Neil |
| 068 | golflua | 160305T194547Z | Kyle Kan |
| 018 | MATL | 160305T191211Z | Luis Men |
TypeScript (The TS Type system), 115
Non-strict mode compliant:
type X<A,B,C=B[any],D=[]>=A extends[infer F,...infer R]?F extends C?X<R,B,Exclude<C,F>,[...D,F]>:X<R,B,C,[...D]>:D;
Strict mode compliant (143):
type I<A,B extends any[],C=B[any],D extends any[]=[]>=A extends[infer F,...infer R]?F extends C?I<R,B,Exclude<C,F>,[...D,F]>:I<R,B,C,[...D]>:D;
Ungolfed:
type Intersection<
A,
B extends any[],
C = B[number],
D extends any[] = []
> = A extends [infer F, ...infer R]
? F extends C
? Intersection<R, B, Exclude<C, F>, [...D, F]>
: Intersection<R, B, C, [...D]>
: D;
// Usage
type F = [1,4,3,9,8,8,3,7,0]
type S = [10,1,4,4,8,-1]
type ungolfed = Intersection<F, S>
type strictGolfed = I<F, S>
type noStrictGolfed = X<F, S>
TS Playground - Hover over type to see intersection.
APL(NARS), 140 chars
r←a I b;i;j;d;l;k;x
l←≢a⋄d←≢b⋄i←1⋄r←⍬⋄k←0
→0×⍳i>l⋄x←a[i]⋄i+←1⋄j←1
→4×⍳j>k⋄→2×⍳x=r[j]⋄j+←1⋄→3
j←1
→2×⍳j>d⋄→6×⍳x=b[j]⋄j+←1⋄→5
r,←b[j]⋄k+←1⋄→2
// 20+22+24+27+4+27+16=140
they would be 3 loops, one main loop and 2 little loops in it, one for see if element of "a" is already found in the list/set of the result "r" (if it is found try one other element of "a"), and one other for see if that element in the list "b" (if it is in the list "b", add that element to the list result "r").
test:
(,1000) I ⍬
┌0─┐
│ 0│
└~─┘
⍬ I ,1000
┌0─┐
│ 0│
└~─┘
3 1 2 4 3 1 1 1 1 3 I 3 1 ¯1 0 8 3 3 1
┌2───┐
│ 3 1│
└~───┘
1 2 1 I 3 3 4
┌0─┐
│ 0│
└~─┘
Haskell, 45 42 bytes
y#(e:s)=[e|any(==e)y,all(/=e)s]++y#s
_#x=x
Edit: -2 bytes thanks to @Ørjan Johansen, -1 byte thanks to @dfeuer.
R, 141 83 bytes
l=sapply(strsplit(readLines(file("stdin"))," "),as.numeric)
r=rle(sort(unlist(l)))[[2]]
r[sapply(r,function(x)any(x==l[[1]])&any(x==l[[2]]))]
Improved by Giuseppe
function(a,b){r=rle(sort(c(a,b)))[[2]];r[sapply(r,function(x)any(x==a)&any(x==b))]}
PHP, 78, 77 bytes
function($a,$b){foreach($a as$x)foreach($b as$y)$x==$y?$c[$x]=$x:0;return$c;}
No frills, but rule-compliant (I think).
Output
[], []
[]
[1000], []
[]
[3,1,2,4,3,1,1,1,1,3], [3,1,-1,0,8,3,3,1]
[3,1]
[1,2,1], [3,3,4]
[]
Husk, 9 bytes
mo←←kIfE*
m Map
o←← taking the first element from the first element
kI over lists of identical values from
* the Cartesian product of the two input lists
f filtered by
E both elements of a pair being equal.
Looking in Husk's source code on GitHub, k ("keyon") is implemented as the composition of sorting the list and grouping adjacent values, so although I can't actually find the implementation of "groupOn" it's probably safe to assume that it doesn't do anything setty, since Haskell is a functional language and grouping adjacent equal values is a pretty straightforward reduce-over-a-linked-list operation. (I can find the implementation of k's other type signature "keyby", which I could use here by changing I to =, but I don't know Haskell so I can't tell how exactly it works.)
Also, a nice little Brachylog answer I came up with before I realized set operations of all sorts were disallowed: ⟨∋∈⟩ᵘ
Python3, 51 bytes
lambda a,b:[v for v in a if{n:1 for n in b}.get(v)]
If the input lists can contain duplicates:
Python3, 67 bytes
lambda a,b:list({v:1 for v in a if {n:1 for n in b}.get(v)}.keys())
Axiom, 257 bytes
W(x,y)==>while x repeat y;f(a,b)==(r:List INT:=[];#a*#b=0=>r;x:=sort(a);y:=sort(b);i:=1;j:=1;repeat(j>#y=>break;W(i<=#x and x.i<y.j,i:=i+1);i>#x=>break;W(j<=#y and y.j<x.i,j:=j+1);j>#y=>break;v:=y.j;if x.i=v then(r:=concat(r,v);W(j<=#y and y.j=v,j:=j+1)));r)
This without the use of binsearch... But i don't know the big O... Unglofed and results:
--N*log(N)+n*log(n)+???
ListIntersection(a:List INT,b:List INT):List INT==
r:List INT:=[];#a*#b=0=>r
x:=sort(a);y:=sort(b)
i:=1;j:=1
repeat
j>#y=>break
while i<=#x and x.i<y.j repeat i:=i+1
i>#x=>break
while j<=#y and y.j<x.i repeat j:=j+1
j>#y=>break
v:=y.j;if x.i=v then
r:=concat(r,v)
while j<=#y and y.j=v repeat j:=j+1
r
(3) -> f([3,1,2,4,3,1,1,1,1,3],[3,1,-1,0,8,3,3,1])
(3) [1,3]
Type: List Integer
(4) -> f([],[])
(4) []
Type: List Integer
(5) -> f([1,2,1],[3,3,4])
(5) []
Type: List Integer
Not executed many tests so could be bugged...
Axiom, 411 bytes
b(x,v)==(l:=1;h:=#v;repeat(l>h=>break;m:=(l+h)quo 2;x<v.m=>(h:=m-1);x>v.m=>(l:=m+1);return m);0);g(a,b)==(if #a>#b then(v:=a;w:=b)else(v:=b;w:=a);c:=sort(v);for x in w repeat(if binSearch(x,c)~=0 then return 1);0)
f(a:List INT,b:List INT):List INT==(r:List INT:=[];#a*#b=0=>r;x:=sort(a);y:=sort(b);i:=1;repeat(i>#x=>break;v:=x.i;binSearch(v,y)=0=>(i:=i+1);r:=concat(r,v);while i<=#x and x.i=v repeat i:=i+1);r)
ungolf and test
--suppose v.1<=v.2<=....<=v.#v as the default function sort() produce
-- binary serch of x in v, return the index i with v.i==x
-- return 0 if that index not exist
--traslated in Axiom from C book
--Il Linguaggio C, II Edizione
--Brian W.Kerninghan, Dennis M.Ritchie
binSearch(x,v)==
l:=1;h:=#v
repeat
l>h=>break
m:=(l+h)quo 2
x<v.m=>(h:=m-1)
x>v.m=>(l:=m+1)
return m
0
--N*log(N)+n*log(n)+N*n*log(n) so it is N*n*log(n) or n*N*log(N)
ListIntersection(a:List INT,b:List INT):List INT==
r:List INT:=[];#a*#b=0=>r
x:=sort(a);y:=sort(b)
i:=1
repeat
i>#x=>break
v:=x.i
binSearch(v,y)=0=>(i:=i+1)
r:=concat(r,v)
while i<=#x and x.i=v repeat i:=i+1
r
(5) -> f([],[])
(5) []
Type: List Integer
(6) -> f([1000],[])
(6) []
Type: List Integer
(7) -> f([3,1,2,4,3,1,1,1,1,3],[3,1,-1,0,8,3,3,1])
(7) [1,3]
Type: List Integer
(8) -> f([1,2,1],[3,3,4])
(8) []
Type: List Integer
Jq 1.5, 99 bytes
def f(a;b):(a+b|min)as$m|[range($m;a+b|max)|[]]|.[a[]-$m][0]=1|.[b[]-$m][1]=1|.[[[1,1]]]|map(.+$m);
Expanded
def f(a;b):
(a+b|min) as $m # find smallest value in either array
| [range($m;a+b|max)|[]] # create array of [] for indices [min,max]
| .[ a[]-$m ][0]=1 # store 1 in [0] at corresponding indices of a
| .[ b[]-$m ][1]=1 # store 1 in [1] at corresponding indices of b
| .[[[1,1]]] # find all the indices where we stored a 1 for a and b
| map(.+$m) # convert back from indices to values
;
This avoids using {} objects and since jq does not have bit operations this emulates them with an array.
Retina, 63 bytes
The last two lines remove duplicates. The input is two space-delimited lists separated by a comma. The output is whitespace-delimited.
+`( -?\d+)\b(.*,.*)\1\b
$1_$2
-?\d+\b|_|,
+`(-?\d+)(.*)\1
$1$2
If duplicates in the output are allowed, my program would be 42 bytes.
Pyth, 12 11 bytes
eMrSsq#RQE8
Explanation:
eMrSsq#RQE8
Implicit: Q is one of the lists.
q#RQE For every element in the first list, filter the second list on
equality with that element.
s Concatenate. We now have the intersection, with duplicates.
rS 8 Sort and run length encode, giving counts and elements.
eM Take just the elements.
Perl 6, 26 37 bytes
{%(@^a.grep(any(@^b)):p.invert).keys}
usage
> my &f = {%(@^a.grep(any(@^b)):p.invert).keys}
-> @a, @b { #`(Block|559823336) ... }
> f([3,1,2,4,3,1,1,1,1,3], [3,1,-1,0,8,3,3,1])
(1 3)
Cheeky non-competing answer
> [3,1,2,4,3,1,1,1,1,3] ∩ [3,1,-1,0,8,3,3,1]
set(3, 1)
or if you like it in a boring ol' f function
> my &f = &infix:<∩>
sub infix:<∩> (|p is raw) { #`(Sub+{<anon|130874592>}+{Precedence}|102325600) ... }
> f([3,1,2,4,3,1,1,1,1,3], [3,1,-1,0,8,3,3,1])
set(3, 1)
Jelly, 13 bytes
=S¥Ðf
ṂrṀ{ç³ç
How it works
ṂrṀ{ç³ç Main link. Arguments: A (list 1), B (list 2)
Ṃ Yield m, the minimum of A.
Ṁ{ Yield M, the maxmimum of A.
r Create an inclusive range from m to M.
f³ Apply the helper link with right argument A.
f Apply the helper link with right argument B.
=S¥Ðf Helper link. Arguments: n (integer in range), L (list, A or B)
= Test all elements of L for equality with n.
S Add the results.
¥ Combine the two previous links into a dyadic chain.
Ðf Filter by the result of the sums.
bash + GNU coreutils, 184 Bytes
[ -z "$1" ] && exit
p='{if(a[$0]++==0)print $0}'
while read A; do
while read B; do
[ $A = $B ] && echo $A
done < <(grep -oP '\d*'<<<$1|awk "$p")
done < <(grep -oP '\d*'<<<$2|awk "$p")
Invocation:
./codegolf.sh '12 4 654 12 3 56' '4 4 56 33 3 3 3'
Output:
4
56
3
No output if intersection is empty. This script does not sort and makes sanity check if first set is empty. Explanation:
[ -z "$1" ] && exit # Exit if first set is empty
p='{if(a[$0]++==0)print $0}' # The AWK program we will use
while read A; do # read the list with two
while read B; do # encapsulated loops
[ $A = $B ] && echo $A # if they match, then print
done < <(grep -oP '\d*'<<<$1|awk "$p")
done < <(grep -oP '\d*'<<<$2|awk "$p")
# the process substitution greps the numbers and pipes them to awk. Our awk program makes them unique without sorting; it uses associative arrays with index names same as lines (our numbers here).
Bonus to know: You could change to grep -o . to do this with random strings instead of numbers.
JavaScript (ES6), 66 bytes
(a,b)=>a.filter((e,i)=>b.some(f=>e==f)&a.slice(0,i).every(f=>e-f))
Without using indexOf, as I'm not convinced that it's permitted.
golflua, 68 chars
\f(a,b)k={}~@_,v p(a)~@_,w p(b)?w==v k[w]=w$$$~@_,v p(k)I.w(v," ")$$
which is called as
> f({1,2,3,4},{3,4,5})
3 4
> f({3,1,2,4,3,1,1,1,1,3},{3,1,-1,0,8,3,3,1})
3 1
In regular Lua, this would be
function foo(a,b)
local k={}
for i,v in pairs(a)
for j,w in pairs(b)
if v==w then
k[v] = v
end
end
end
for i,v in pairs(k)
print(v," ")
end
end
So basically I'm iterating over the each element of the two tables and only storing the equivalent values. By using the value as the key (k[w]=w), I'm eliminating all duplicates. We then output the new table by iterating over the index & value of pairs
MATL, 18 bytes
YY_iti!=Xa)hStdfQ)
This works in two steps. First the intersection is computed, possibly with duplicates. This is based on comparing all elements of one array with all elements of the other, and keeping elements of the first that are present in the second.
Then duplicates are removed. For this, the array from the previous step is sorted, and entries are kept if different from the preceding. A -inf value is prepended so that the first (i.e. lowest) value is not lost.
YY_ % push -infinity
it % take first input. Duplicate
i! % take second input. Transpose
= % test all combinations of elements of the two inputs for equality
Xa % row vector that contains true for elements of first array that
% are present in the second, possibly duplicated
) % index into first array to keep only those elements. Now we need
% to remove duplicates
h % append -infinity
S % sort
tdf % duplicate. Find entries that differ from the preceding
Q) % add 1 and index into array to keep only non-duplicates