Symmetric difference: Difference between revisions
m
First example shows symmetric difference w/o using `><` operator
m (→{{header|Phix}}: added example using the new buitin) |
m (First example shows symmetric difference w/o using `><` operator) |
||
(30 intermediate revisions by 19 users not shown) | |||
Line 24:
{{trans|Python}}
<
V setB = Set([‘Jim’, ‘Mary’, ‘John’, ‘Bob’])
print(setA.symmetric_difference(setB))
print(setA - setB)
print(setB - setA)</
{{out}}
Line 35:
Set([Serena])
Set([Jim])
</pre>
=={{header|Action!}}==
The user must type in the monitor the following command after compilation and before running the program!<pre>SET EndProg=*</pre>
{{libheader|Action! Tool Kit}}
<syntaxhighlight lang="action!">CARD EndProg ;required for ALLOCATE.ACT
INCLUDE "D2:ALLOCATE.ACT" ;from the Action! Tool Kit. You must type 'SET EndProg=*' from the monitor after compiling, but before running this program!
DEFINE PTR="CARD"
DEFINE NODE_SIZE="6"
TYPE SetNode=[PTR data,prv,nxt]
TYPE SetInfo=[PTR name,begin,end]
PROC PrintSet(SetInfo POINTER s)
SetNode POINTER n
CHAR ARRAY a
n=s.begin
PrintF("%S=(",s.name)
WHILE n
DO
Print(n.data)
a=n.data
IF n.nxt THEN
Print(", ")
FI
n=n.nxt
OD
PrintE(")")
RETURN
PROC CreateSet(SetInfo POINTER s CHAR ARRAY n)
s.name=n
s.begin=0
s.end=0
RETURN
PTR FUNC Find(SetInfo POINTER s CHAR ARRAY v)
SetNode POINTER n
n=s.begin
WHILE n
DO
IF SCompare(v,n.data)=0 THEN
RETURN (n)
FI
n=n.nxt
OD
RETURN (0)
BYTE FUNC Contains(SetInfo POINTER s CHAR ARRAY v)
SetNode POINTER n
n=Find(s,v)
IF n=0 THEN
RETURN (0)
FI
RETURN (1)
PROC Append(SetInfo POINTER s CHAR ARRAY v)
SetNode POINTER n,tmp
IF Contains(s,v) THEN RETURN FI
n=Alloc(NODE_SIZE)
n.data=v
n.prv=s.end
n.nxt=0
IF s.end THEN
tmp=s.end tmp.nxt=n
ELSE
s.begin=n
FI
s.end=n
RETURN
PROC Remove(SetInfo POINTER s CHAR ARRAY v)
SetNode POINTER n,prev,next
n=Find(s,v)
IF n=0 THEN RETURN FI
prev=n.prv
next=n.nxt
Free(n,NODE_SIZE)
IF prev THEN
prev.nxt=next
ELSE
s.begin=next
FI
IF next THEN
next.prv=prev
ELSE
s.end=prev
FI
RETURN
PROC AppendSet(SetInfo POINTER s,other)
SetNode POINTER n
n=other.begin
WHILE n
DO
Append(s,n.data)
n=n.nxt
OD
RETURN
PROC RemoveSet(SetInfo POINTER s,other)
SetNode POINTER n
n=other.begin
WHILE n
DO
Remove(s,n.data)
n=n.nxt
OD
RETURN
PROC Clear(SetInfo POINTER s)
SetNode POINTER n
DO
n=s.begin
IF n=0 THEN RETURN FI
Remove(s,n.data)
OD
RETURN
PROC Union(SetInfo POINTER a,b,res)
Clear(res)
AppendSet(res,a)
AppendSet(res,b)
RETURN
PROC Difference(SetInfo POINTER a,b,res)
Clear(res)
AppendSet(res,a)
RemoveSet(res,b)
RETURN
PROC SymmetricDifference(SetInfo POINTER a,b,res)
SetInfo tmp1,tmp2
CreateSet(tmp1,"")
CreateSet(tmp2,"")
Difference(a,b,tmp1)
Difference(b,a,tmp2)
Union(tmp1,tmp2,res)
Clear(tmp1)
Clear(tmp2)
RETURN
PROC TestSymmetricDifference(SetInfo POINTER a,b,res)
SymmetricDifference(a,b,res)
PrintF("%S XOR %S: ",a.name,b.name)
PrintSet(res)
RETURN
PROC TestDifference(SetInfo POINTER a,b,res)
Difference(a,b,res)
PrintF("%S-%S: ",a.name,b.name)
PrintSet(res)
RETURN
PROC Main()
SetInfo s1,s2,s3
Put(125) PutE() ;clear screen
AllocInit(0)
CreateSet(s1,"A")
CreateSet(s2,"B")
CreateSet(s3,"C")
Append(s1,"John") Append(s1,"Bob")
Append(s1,"Mary") Append(s1,"Serena")
Append(s2,"Jim") Append(s2,"Mary")
Append(s2,"John") Append(s2,"Bob")
PrintSet(s1) PrintSet(s2)
PutE()
TestSymmetricDifference(s1,s2,s3)
TestDifference(s1,s2,s3)
TestDifference(s2,s1,s3)
Clear(s1)
Clear(s2)
Clear(s3)
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Symmetric_difference.png Screenshot from Atari 8-bit computer]
<pre>
A=(John, Bob, Mary, Serena)
B=(Jim, Mary, John, Bob)
A XOR B: C=(Serena, Jim)
A-B: C=(Serena)
B-A: C=(Jim)
</pre>
=={{header|Ada}}==
Ada has the lattice operation '''xor''' predefined on Boolean, modular types, 1D arrays, set implementations from the standard library. The provided solution uses arrays:
<
procedure Test_XOR is
Line 65 ⟶ 268:
Put ("A - B = "); Put (A and not B); New_Line;
Put ("B - A = "); Put (B and not A); New_Line;
end Test_XOR;</
Sample output:
<pre>
Line 74 ⟶ 277:
=={{header|Aime}}==
<
{
record r;
Line 107 ⟶ 310:
0;
}</
{{out}}
<pre>Jim
Line 115 ⟶ 318:
{{works with|ALGOL 68G|Any - tested with release 2.8.3.win32}}
Uses the associative array implementations in ALGOL_68/prelude.
<
# include the associative array code for string keys and values #
PR read "aArray.a68" PR
Line 170 ⟶ 373:
e := NEXT c
OD;
print( ( newline ) )</
{{out}}
<pre>
Serena Jim
</pre>
=={{header|Amazing Hopper}}==
<syntaxhighlight lang="c">
#include <basico.h>
algoritmo
matrices (A, B)
"John", "Bob", "Mary", "Serena", enlistar en 'A'
"Jim", "Mary", "John", "Bob", enlistar en 'B'
" A XOR B: {", diferencia simétrica(A,B), "}\n"
" A \ B: {", diferencia(A,B), "}\n"
" B \ A: {", diferencia(B,A), "}\n"
imprimir
terminar
</syntaxhighlight>
{{out}}
<pre>
A XOR B: {Jim,Serena}
A \ B: {Serena}
B \ A: {Jim}
</pre>
=={{header|Apex}}==
<
Set<String> setB = new Set<String>{'Jim', 'Mary', 'John', 'Bob'};
Line 204 ⟶ 431:
System.debug('Not in set B: ' + notInSetB);
System.debug('Symmetric Difference: ' + symmetricDifference);
System.debug('Symmetric Difference 2: ' + symmetricDifference2);</
{{out}}
<pre>Not in set A: {Jim}
Line 210 ⟶ 437:
Symmetric Difference: {Jim, Serena}
Symmetric Difference 2: {Jim, Serena}</pre>
=={{header|APL}}==
{{works with|Dyalog APL}}
<syntaxhighlight lang="apl">symdiff ← ∪~∩</syntaxhighlight>
{{out}}
<pre> 'John' 'Bob' 'Mary' 'Serena' symdiff 'Jim' 'Mary' 'John' 'Bob'
Serena Jim </pre>
=={{header|AppleScript}}==
===Functional===
{{Trans|JavaScript}} (ES6 Functional JS)
<
-- symmetricDifference :: [a] -> [a] -> [a]
Line 324 ⟶ 559:
set sx to nub(xs)
sx & foldl(flipDelete, nub(ys), sx)
end union</
{{Out}}
<
===Some alternatives===
There are several ways to approach this problem. Vanilla AppleScript doesn't do sets, but the following returns the required results:
<syntaxhighlight lang="applescript">on symmetricDifference(a, b)
set output to {}
repeat 2 times
repeat with thisItem in a
set thisItem to thisItem's contents
tell {thisItem}
if (not ((it is in b) or (it is in output))) then set end of output to thisItem
end tell
end repeat
set {a, b} to {b, a}
end repeat
return output
end symmetricDifference
on task()
set a to {"John", "Serena", "Bob", "Mary", "Serena"}
set b to {"Jim", "Mary", "John", "Jim", "Bob"}
return symmetricDifference(a, b)
end task
task()</syntaxhighlight>
{{output}}
<syntaxhighlight lang="applescript">{"Serena", "Jim"}</syntaxhighlight>
AppleScriptObjC gives access to the Foundation framework's NSSet classes, whose mutable variety has relevant methods. A symmetricDifference() handler implementing (A ∖ B) ∪ (B ∖ A) might be:
<syntaxhighlight lang="applescript">use AppleScript version "2.4" -- OS X 10.10 (Yosemite) or later
use framework "Foundation"
on symmetricDifference(a, b)
set a to current application's class "NSSet"'s setWithArray:(a)
set b to current application's class "NSMutableSet"'s setWithArray:(b)
set output to a's mutableCopy()
tell output to minusSet:(b)
tell b to minusSet:(a)
tell output to unionSet:(b)
return output's allObjects() as list
end symmetricDifference</syntaxhighlight>
And for (A ∪ B) ∖ (A ∩ B):
<syntaxhighlight lang="applescript">use AppleScript version "2.4" -- OS X 10.10 (Yosemite) or later
use framework "Foundation"
on symmetricDifference(a, b)
set a to current application's class "NSSet"'s setWithArray:(a)
set b to current application's class "NSMutableSet"'s setWithArray:(b)
set output to a's mutableCopy()
tell output to unionSet:(b)
tell b to intersectSet:(a)
tell output to minusSet:(b)
return output's allObjects() as list
end symmetricDifference</syntaxhighlight>
It's also possible in ASObjC to filter arrays or sets if you're so inclined:
<syntaxhighlight lang="applescript">use AppleScript version "2.4" -- OS X 10.10 (Yosemite) or later
use framework "Foundation"
on symmetricDifference(a, b)
set unionArray to (current application's class "NSArray"'s arrayWithArray:({a, b}))'s ¬
valueForKeyPath:("@distinctUnionOfArrays.self")
set filter to current application's class "NSPredicate"'s ¬
predicateWithFormat_("!((self IN %@) && (self IN %@))", a, b)
return (unionArray's filteredArrayUsingPredicate:(filter)) as list
end symmetricDifference</syntaxhighlight>
=={{header|Arturo}}==
<
b: ["Jim" "Mary" "John" "Bob"]
print difference.symmetric a b</
{{out}}
Line 339 ⟶ 649:
=={{header|AutoHotkey}}==
<
setB = Jim, Mary, John, Bob
MsgBox,, Singles, % SymmetricDifference(setA, setB)
Line 361 ⟶ 671:
Result .= B_%A_Index% ", "
Return, SubStr(Result, 1, -2)
}</
Message boxes show:
<pre>Singles
Line 375 ⟶ 685:
=={{header|AWK}}==
<syntaxhighlight lang="awk">
# syntax: GAWK -f SYMMETRIC_DIFFERENCE.AWK
BEGIN {
Line 407 ⟶ 717:
printf("\n")
}
</syntaxhighlight>
<p>output:</p>
<pre>
Line 417 ⟶ 727:
=={{header|BBC BASIC}}==
Here sets are represented as integers, hence there are a maximum of 32 elements in a set.
<
list$() = "Bob", "Jim", "John", "Mary", "Serena"
Line 439 ⟶ 749:
IF set% AND 1 << i% o$ += list$(i%) + ", "
NEXT
= LEFT$(LEFT$(o$))</
'''Output:'''
<pre>
Line 453 ⟶ 763:
Walk through the concatenation of the two lists, using backtracking (forced by the ~ operator).
If an element is in both lists, or if the element already is in the accumulated result <code>symdiff</code>, continue. Otherwise add the element to <code>symdiff</code>. When all elements are done and backtracking therefore finally fails, return the contents of <code>symdiff</code>. The flag <code>%</code> in the pattern <code>%@?x</code> ensures that only nontrivial elements (i.e. non-empty strings in this case) are matched. The <code>@</code> flag ensures that at most one string is matched. Together these flags ensure that exactly one element is matched.
<
A B x symdiff
. !arg:(?A.?B)
Line 468 ⟶ 778:
?
| !symdiff
));</
Run:
<
Output:
<syntaxhighlight lang
=={{header|C}}==
Simple method:
<
#include <string.h>
Line 527 ⟶ 837:
return 0;
}</
<pre>
A \ B:
Line 540 ⟶ 850:
</pre>
If you prefer something elaborate:
<
#include <stdio.h>
#include <string.h>
Line 674 ⟶ 984:
return 0;
}</
Output
<pre>
Line 683 ⟶ 993:
=={{header|C sharp|C#}}==
<
using System.Collections.Generic;
using System.Linq;
Line 710 ⟶ 1,020:
}
}
}</
Output:
<pre>
Line 718 ⟶ 1,028:
=={{header|C++}}==
<
#include <set>
#include <algorithm>
Line 741 ⟶ 1,051:
cout << endl;
return 0;
}</
Output:
Line 747 ⟶ 1,057:
=={{header|Clojure}}==
<
(defn symmetric-difference [s1 s2]
(union (difference s1 s2) (difference s2 s1)))
(symmetric-difference #{:john :bob :mary :serena} #{:jim :mary :john :bob})</
=={{header|Common Lisp}}==
<
(remove-duplicates '(John Serena Bob Mary Serena))
(remove-duplicates '(Jim Mary John Jim Bob)))</
Output:
(JIM SERENA)
Line 763 ⟶ 1,073:
=={{header|D}}==
Generic version.
<
struct Set(T) {
Line 789 ⟶ 1,099:
writeln(" B\\A: ", (B - A).items);
writeln("A symdiff B: ", symmetricDifference(A, B).items);
}</
{{out}}
<pre> A\B: ["Serena"]
Line 796 ⟶ 1,106:
=={{header|Datalog}}==
Implemented using Souffle.
<
.decl B(text: symbol)
.decl SymmetricDifference(text: symbol)
Line 812 ⟶ 1,122:
SymmetricDifference(x) :- A(x), !B(x).
SymmetricDifference(x) :- B(x), !A(x).</
{{out}}
<pre>
Line 820 ⟶ 1,130:
part
of
</pre>
=={{header|Delphi}}==
{{libheader| System.Typinfo}}
{{Trans|Pascal}}
Small variation of pascal.
<syntaxhighlight lang="delphi">
PROGRAM Symmetric_difference;
uses
System.Typinfo;
TYPE
TName = (Bob, Jim, John, Mary, Serena);
TList = SET OF TName;
TNameHelper = record helper for TName
FUNCTION ToString(): string;
end;
{ TNameHlper }
FUNCTION TNameHelper.ToString: string;
BEGIN
Result := GetEnumName(TypeInfo(TName), Ord(self));
END;
PROCEDURE Put(txt: String; ResSet: TList);
VAR
I: TName;
BEGIN
Write(txt);
FOR I IN ResSet DO
Write(I.ToString, ' ');
WriteLn;
END;
VAR
ListA: TList = [John, Bob, Mary, Serena];
ListB: TList = [Jim, Mary, John, Bob];
BEGIN
Put('ListA -> ', ListA);
Put('ListB -> ', ListB);
Put('ListA >< ListB -> ', (ListA - ListB) + (ListB - ListA));
Put('ListA - ListB -> ', ListA - ListB);
Put('ListB - ListA -> ', ListB - ListA);
ReadLn;
END.</syntaxhighlight>
'''Delphi/Object Pascal actually has a 'Symmetric Difference' operator `> <`: '''
<syntaxhighlight lang="pascal">
program SymmetricDifference;
type
charSet = set of Char;
var
s1, s2, s3: charSet;
ch: char;
begin
s1 := ['a', 'b', 'c', 'd'];
s2 := ['c', 'd', 'e', 'f'];
s3 := s1 >< s2;
for ch in s3 do
write(ch, ' ');
writeLn;
end.
</syntaxhighlight>
Output:
<pre>
a b e f
</pre>
=={{header|Déjà Vu}}==
Déjà Vu has no real set type. Instead, it uses a dictionary whose keys are the set values. The <code>set{</code> constructor uses <code>true</code> as a dummy value, and sets <code>false</code> as a dummy value.
<
set :setB set{ :Jim :Mary :John :Bob }
Line 837 ⟶ 1,221:
set{
!. symmetric-difference setA setB</
{{out}}
<pre>set{ :Serena :Jim }</pre>
=={{header|E}}==
<
# value: <symmDiff>
? symmDiff(["John", "Bob", "Mary", "Serena"].asSet(), ["Jim", "Mary", "John", "Bob"].asSet())
# value: ["Jim", "Serena"].asSet()</
=={{header|EasyLang}}==
<syntaxhighlight>
a$[] = [ "John" "Bob" "Mary" "Serena" ]
b$[] = [ "Jim" "Mary" "John" "Bob" ]
#
for i to 2
for a$ in a$[]
for b$ in b$[]
if a$ = b$
a$ = ""
break 1
.
.
if a$ <> ""
c$[] &= a$
.
.
swap a$[] b$[]
.
print c$[]
</syntaxhighlight>
=={{header|Eiffel}}==
<syntaxhighlight lang="eiffel">note
description: "Summary description for {SYMETRIC_DIFFERENCE_EXAMPLE}."
URI: "http://rosettacode.org/wiki/Symmetric_difference"
Line 893 ⟶ 1,299:
end
end</
=={{header|Elixir}}==
{{works with|Elixir|1.2}}
<
#MapSet<["Bob", "John", "Mary", "Serena"]>
iex(2)> b = ~w[Jim Mary John Bob] |> MapSet.new
Line 904 ⟶ 1,310:
#Function<12.54118792/2 in :erl_eval.expr/5>
iex(4)> sym_dif.(a,b)
#MapSet<["Jim", "Serena"]></
=={{header|Erlang}}==
<
-module(symdiff).
-export([main/0]).
Line 918 ⟶ 1,324:
SymmDiffAB = sets:subtract(AUnionB,AIntersectionB),
sets:to_list(SymmDiffAB).
</syntaxhighlight>
{{out}}
Line 925 ⟶ 1,331:
=={{header|F Sharp|F#}}==
<
let b = set ["Jim"; "Mary"; "John"; "Bob"];;
Line 932 ⟶ 1,338:
> (a-b) + (b-a);;
val it : Set<string> = set ["Jim"; "Serena"]</
Or, if you don't like the infix operators:
<
val it : Set<string> = set ["Jim"; "Serena"]</
=={{header|Factor}}==
<
[ diff ] [ swap diff ] 2bi append ;
{ "John" "Bob" "Mary" "Serena" } { "Jim" "Mary" "John" "Bob" } symmetric-diff .</
=={{header|Forth}}==
GForth 0.7.0 tested.
<
[ cell 8 * 1- ] literal umin CREATE 1 swap lshift ,
DOES> ( -- 2^n ) @ ;
Line 968 ⟶ 1,374:
swap -1 xor and cr persons
cr bye
</syntaxhighlight>
Output:
<pre>
Line 980 ⟶ 1,386:
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
<
implicit none
Line 1,001 ⟶ 1,407:
end do outer2
end program</
Output
<pre>
Serena
Jim
</pre>
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">
redim shared as string Result(-1) 'represent our sets as strings;
'this'll do to illustrate the concept
sub sym( A() as string, B() as string )
dim as integer ai, bi, ri
dim as boolean add_it
for ai = lbound(A) to ubound(A)
add_it = true
for bi = lbound(B) to ubound(B)
if A(ai) = B(bi) then
add_it=false
exit for 'if item is common to both lists, don't include it
end if
next bi
if add_it then
for ri = 0 to ubound(Result)
if A(ai) = Result(ri) then
add_it=false
exit for
'if item is already in the result, don't include it again
end if
next ri
end if
if add_it then
redim preserve as string Result(0 to ubound(Result)+1)
Result(ubound(Result)) = A(ai)
end if
next ai
end sub
dim as string A(0 to 3) = {"John", "Bob", "Mary", "Serena"}
dim as string B(0 to 4) = {"Jim", "Mary", "John", "Bob", "Jim"}
'contains a double to show code can handle it
sym(A(), B())
sym(B(), A())
for i as uinteger = 0 to ubound(Result)
print Result(i)
next i
</syntaxhighlight>
{{out}}<pre>Serena
Jim
</pre>
=={{header|Frink}}==
<syntaxhighlight lang="frink">A = new set["John", "Bob", "Mary", "Serena"]
B = new set["Jim", "Mary", "John", "Bob"]
println["Symmetric difference: " + symmetricDifference[A,B]]
println["A - B : " + setDifference[A,B]]
println["B - A : " + setDifference[B,A]]</syntaxhighlight>
{{out}}
<pre>
Symmetric difference: [Jim, Serena]
A - B : [Serena]
B - A : [Jim]
</pre>
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
include "NSLog.incl"
local fn SymmetricDifferenceOfSets( setA as CFSetRef, setB as CFSetRef ) as CFSetRef
CFMutableSetRef notInSetA = fn MutableSetWithSet( setB )
MutableSetMinusSet( notInSetA, setA )
CFMutableSetRef notInSetB = fn MutableSetWithSet( setA )
MutableSetMinusSet( notInSetB, setB )
CFMutableSetRef symmetricDifference = fn MutableSetWithSet( notInSetA )
MutableSetUnionSet( symmetricDifference, notInSetB )
end fn = fn SetWithSet( symmetricDifference )
CFSetRef set1, set2
set1 = fn SetWithObjects( @"John", @"Serena", @"Bob", @"Mary", @"Serena", NULL )
set2 = fn SetWithObjects( @"Jim", @"Mary", @"John", @"Jim", @"Bob", NULL )
NSLog( @"Symmetric difference:\n%@", fn SymmetricDifferenceOfSets( set1, set2 ) )
HandleEvents
</syntaxhighlight>
{{output}}
<pre>
Symmetric difference:
{(
Jim,
Serena
)}
</pre>
=={{header|GAP}}==
<
return Union(Difference(a, b), Difference(b, a));
end;
Line 1,016 ⟶ 1,516:
b := ["Jim", "Mary", "John", "Jim", "Bob"];
SymmetricDifference(a,b);
[ "Jim", "Serena" ]</
=={{header|Go}}==
<
import "fmt"
Line 1,039 ⟶ 1,539:
}
fmt.Println(sd)
}</
Output:
<pre>
Line 1,045 ⟶ 1,545:
</pre>
Alternatively, the following computes destructively on a. The result is the same.
<
for e := range b {
delete(a, e)
}
fmt.Println(a)
}</
=={{header|Groovy}}==
Solution:
<
assert s1 != null
assert s2 != null
(s1 + s2) - (s1.intersect(s2))
}</
Test:
<
Set b = ['Jim', 'Mary', 'John', 'Jim', 'Bob']
Line 1,152 ⟶ 1,652:
ppm <> csny: ${PC}
ppm <> ppm: ${PP}
"""</
Output:
Line 1,196 ⟶ 1,696:
=={{header|Haskell}}==
<
a = fromList ["John", "Bob", "Mary", "Serena"]
Line 1,203 ⟶ 1,703:
(-|-) :: Ord a => Set a -> Set a -> Set a
x -|- y = (x \\ y) `union` (y \\ x)
-- Equivalently: (x `union` y) \\ (x `intersect` y)</
Symmetric difference:
<
fromList ["Jim","Serena"]</
Individual differences:
<
fromList ["Serena"]
*Main> b \\ a
fromList ["Jim"]</
=={{header|HicEst}}==
<
CALL SymmDiff("John,Bob,Mary,Serena,", "Jim,Mary,John,Bob,")
Line 1,233 ⟶ 1,733:
EDIT(Text=a, Option=1, SortDelDbls=a) ! Option=1: keep case; Serena,
differences = TRIM( differences ) // a
END</
=={{header|Icon}} and {{header|Unicon}}==
Set operations are built into Icon/Unicon.
<
a := set(["John", "Serena", "Bob", "Mary", "Serena"])
Line 1,255 ⟶ 1,755:
write("}")
return
end</
Sample output:
<pre>a = { Serena Mary Bob John }
Line 1,264 ⟶ 1,764:
=={{header|J}}==
<
B=: ~. ;:'Jim Mary John Jim Bob'
Line 1,274 ⟶ 1,774:
┌──────┬───┐
│Serena│Jim│
└──────┴───┘</
To illustrate some of the underlying mechanics used here:
<
┌──────┐
│Serena│
Line 1,287 ⟶ 1,787:
┌────┬──────┬───┬────┐
│John│Serena│Bob│Mary│
└────┴──────┴───┴────┘</
Here's an alternative implementation:
<
┌──────┬───┐
│Serena│Jim│
└──────┴───┘</
Here, <code>(,)</code> contains all items from A and B and <code>([ -. -.)</code> is the idiom for set intersection, and their difference is the symmetric difference. (Note: an individual word in a J sentence may be placed inside a parenthesis with no change in evaluation, and this can also be used for emphasis when a word might get lost.)
=={{header|Java}}==
<
import java.util.HashSet;
import java.util.Set;
Line 1,339 ⟶ 1,839:
System.out.println("Symmetric Difference 2: " + symmetricDifference2);
}
}</
Output:
<pre>In set A: [Mary, Bob, Serena, John]
Line 1,358 ⟶ 1,858:
Uses the Array function <code>unique()</code> defined [[Create a Sequence of unique elements#JavaScript|here]].
<
function relative_complement(A, B) {
return A.filter(function(elem) {return B.indexOf(elem) == -1});
Line 1,373 ⟶ 1,873:
print(a);
print(b);
print(symmetric_difference(a,b));</
outputs
<pre>Bob,John,Mary,Serena
Line 1,381 ⟶ 1,881:
'''Clear JavaScript'''
<
{
var a = A.length, b = B.length, c = 0, C = [];
Line 1,409 ⟶ 1,909:
Difference(B,A); // 'Jim'
SymmetricDifference(A,B); // 'Serena','Jim'
*/</
===ES6===
====Functional====
By composition of generic functions;
<
'use strict';
Line 1,477 ⟶ 1,977:
symmetricDifference(a, b)
);
})();</
{{Out}}
<
====Procedural ====
<syntaxhighlight lang="javascript">
const symmetricDifference = (...args) => {
let result = new Set();
Line 1,495 ⟶ 1,995:
console.log(symmetricDifference([1, 2, 5], [2, 3, 5], [3, 4, 5]));
</syntaxhighlight>
{{Out}}
<
[1, 4, 5]
</syntaxhighlight>
=={{header|jq}}==
Line 1,506 ⟶ 2,006:
given these assumptions, it is quite efficient. To workaround the
no-null requirement would be tedious but straightforward.
<
# elements of a (and of b) are unique and do not include null:
def intersection(a; b):
Line 1,516 ⟶ 2,016:
(a|unique) as $a | (b|unique) as $b
| (($a + $b) | unique) - (intersection($a;$b));
</syntaxhighlight>
Example:<
[1,3]</
=={{header|Julia}}==
{{works with|Julia|0.6}}
Built-in function.
<
B = ["Jim", "Mary", "John", "Bob"]
@show A B symdiff(A, B)</
{{out}}
Line 1,534 ⟶ 2,034:
=={{header|K}}==
<
B: ?("Jim";"Mary";"John";"Bob")
Line 1,543 ⟶ 2,043:
(A _dvl B;B _dvl A) / Symmetric difference
("Serena"
"Jim")</
=={{header|Kotlin}}==
<
fun main(args: Array<String>) {
Line 1,559 ⟶ 2,059:
val e = c.union(d)
println("A Δ B = $e")
}</
{{out}}
Line 1,569 ⟶ 2,069:
A Δ B = [Serena, Jim]
</pre>
=={{header|Ksh}}==
<syntaxhighlight lang="ksh">
#!/bin/ksh
# Symmetric difference - enumerate the items that are in A or B but not both.
# # Variables:
#
typeset -a A=( John Bob Mary Serena )
typeset -a B=( Jim Mary John Bob )
# # Functions:
#
# # Function _flattenarr(arr, sep) - flatten arr into string by separator sep
#
function _flattenarr {
typeset _arr ; nameref _arr="$1"
typeset _sep ; typeset -L1 _sep="$2"
typeset _buff
typeset _oldIFS=$IFS ; IFS="${_sep}"
_buff=${_arr[*]}
IFS="${_oldIFS}"
echo "${_buff}"
}
# # Function _notin(_arr1, _arr2) - elements in arr1 and not in arr2
#
function _notin {
typeset _ar1 ; nameref _ar1="$1"
typeset _ar2 ; nameref _ar2="$2"
typeset _i _buff _set ; integer _i
_buff=$(_flattenarr _ar2 \|)
for((_i=0; _i<${#_ar1[*]}; _i++)); do
[[ ${_ar1[_i]} != @(${_buff}) ]] && _set+="${_ar1[_i]} "
done
echo ${_set% *}
}
######
# main #
######
AnB=$(_notin A B) ; echo "A - B = ${AnB}"
BnA=$(_notin B A) ; echo "B - A = ${BnA}"
echo "A xor B = ${AnB} ${BnA}"</syntaxhighlight>
{{out}}<pre>A - B = Serena
B - A = Jim
A xor B = Serena Jim</pre>
=={{header|Lasso}}==
<
[
var(
Line 1,596 ⟶ 2,147:
]
</syntaxhighlight>
=={{header|Logo}}==
{{works with|UCB Logo}}
<
if empty? :a [output sentence :acc :b]
ifelse member? first :a :b ~
Line 1,610 ⟶ 2,161:
make "b [Jim Mary John Bob]
show diff :a :b ; [Serena Jim]</
=={{header|Lua}}==
<
B = { ["Jim"] = true, ["Mary"] = true, ["John"] = true, ["Bob"] = true }
Line 1,631 ⟶ 2,182:
for b_a in pairs(B_A) do
print( b_a )
end</
Object-oriented approach:
<
__index = {
union = function(self, other)
Line 1,690 ⟶ 2,241:
print("Intersection A∩B : " .. A:intersection(B))
print("Difference A\\B : " .. A:difference(B))
print("Difference B\\A : " .. B:difference(A))</
'''Output:'''
Line 1,705 ⟶ 2,256:
=={{header|Maple}}==
Maple has built-in support for set operations. Assign the sets A and B:
<
B := {Jim, Mary, John, Bob};</
Now compute the symmetric difference with the '''symmdiff''' command:
<syntaxhighlight lang
{{out}}
{Jim, Serena}
=={{header|Mathematica}}/{{header|Wolfram Language}}==
Mathematica has built-in support for operations on sets, using its generic symbolic lists. This function finds the entries in each list that are not present in the intersection of the two lists.
<
For large lists, some performance improvement could be made by caching the intersection of the two lists to avoid computing it twice:
<
Also, due to Mathematica's symbolic nature, these functions are automatically applicable to lists of any content, such as strings, integers, reals, graphics, or undefined generic symbols (e.g. unassigned variables).
=={{header|MATLAB}}==
If you are using a vector of numbers as the sets of which you like to find the symmetric difference, then there are already utilities that operate on these types of sets built into MATLAB. This code will take the symmetric difference of two vectors:
<
ans =
1 4</
On the other hand, if you are using cell-arrays as sets, there are no built-in set utilities to operate on those data structures, so you will have to program them yourself. Also, the only way to have a set of strings is to put each string in a cell of a cell array, trying to put them into a vector will cause all of the strings to concatenate.
This code will return the symmetric difference of two sets and will take both cell arrays and vectors (as in the above example) as inputs.
<
assert( ~xor(iscell(set1),iscell(set2)), 'Both sets must be of the same type, either cells or matricies, but not a combination of the two' );
Line 1,820 ⟶ 2,371:
resultantSet = unique(resultantSet); %Make sure there are not duplicates
end %symmetricDifference</
Solution Test:
<
A =
Line 1,844 ⟶ 2,395:
ans =
1 4 %Correct</
=={{header|Maxima}}==
<
symmdifference({"John", "Bob", "Mary", "Serena"},
{"Jim", "Mary", "John", "Bob"});
{"Jim", "Serena"}</
=={{header|Mercury}}==
<
:- interface.
Line 1,873 ⟶ 2,424:
print_set(Desc, Set, !IO) :-
to_sorted_list(Set, Elems),
io.format("%11s: %s\n", [s(Desc), s(string(Elems))], !IO).</
=={{header|MiniScript}}==
<syntaxhighlight lang="miniscript">
Set = new map
Set["set"] = {}
Set.init = function(items)
set = new Set
set.set = {}
for item in items
set.add(item)
end for
return set
end function
Set.contains = function(item)
return self.set.hasIndex(item)
end function
Set.items = function
return self.set.indexes
end function
Set.add = function(item)
self.set[item] = true
end function
Set.union = function(other)
result = Set.init
result.set = self.set + other.set
return result
end function
Set.difference = function(other)
result = Set.init
for item in self.items
if not other.contains(item) then result.add(item)
end for
return result
end function
Set.symmetricDifference = function(other)
diff1 = self.difference(other)
diff2 = other.difference(self)
return diff1.union(diff2)
end function
a = ["John", "Serena", "Bob", "Mary", "Serena"]
b = ["Jim", "Mary", "John", "Jim", "Bob"]
A1 = Set.init(a)
B1 = Set.init(b)
print "A XOR B " + A1.symmetricDifference(B1).items
print "A - B " + A1.difference(B1).items
print "B - A " + B1.difference(A1).items
</syntaxhighlight>
{{out}}
<pre>A XOR B ["Serena", "Jim"]
A - B ["Serena"]
B - A ["Jim"]
</pre>
=={{header|Miranda}}==
<syntaxhighlight lang="miranda>main :: [sys_message]
main = [Stdout (show (symdiff a b) ++ "\n")]
where a = ["John", "Serena", "Bob", "Mary", "Serena"]
b = ["Jim", "Mary", "John", "Jim", "Bob"]
symdiff :: [*]->[*]->[*]
symdiff a b = (a' -- b') ++ (b' -- a')
where a' = nub a
b' = nub b
nub :: [*]->[*]
nub = f []
where f acc [] = acc
f acc (a:as) = f acc as, if a $in acc
= f (a:acc) as, otherwise
in :: *->[*]->bool
in i [] = False
in i (a:as) = a == i \/ i $in as</syntaxhighlight>
{{out}}
<pre>["Serena","Jim"]</pre>
=={{header|Nim}}==
<
var setA = ["John", "Bob", "Mary", "Serena"].toHashSet
Line 1,882 ⟶ 2,518:
echo setA -+- setB # Symmetric difference
echo setA - setB # Difference
echo setB - setA # Difference</
Output:
<pre>{Serena, Jim}
Line 1,889 ⟶ 2,525:
=={{header|Objective-C}}==
<
int main(int argc, const char *argv[]) {
Line 1,918 ⟶ 2,554:
}
return 0;
}</
=={{header|OCaml}}==
<
let f lst x = if List.mem x lst then lst else x::lst in
List.rev (List.fold_left f [] lst)
Line 1,928 ⟶ 2,564:
unique (List.filter (fun v -> not (List.mem v b)) a)
let ( -|- ) a b = (b -| a) @ (a -| b)</
in the toplevel:
<
and b = [ "Jim"; "Mary"; "John"; "Bob" ]
;;
Line 1,943 ⟶ 2,579:
# b -| a ;;
- : string list = ["Jim"]</
=={{header|ooRexx}}==
<
b = .set~of("Jim", "Mary", "John", "Bob")
-- the xor operation is a symmetric difference
do item over a~xor(b)
say item
end</
Output:
<pre>
Line 1,960 ⟶ 2,596:
=={{header|Oz}}==
Oz does not have a general set data type. We can implement some basic set operations in terms of list functions and use them to define the symmetric difference:
<
fun {SymDiff A B}
{Union {Diff A B} {Diff B A}}
Line 1,991 ⟶ 2,627:
{Show {SymDiff
{MakeSet [john serena bob mary serena]}
{MakeSet [jim mary john jim bob]}}}</
Oz <em>does</em> have a type for finite sets of non-negative integers. This is part of the constraint programming support. For the given task, we could use it like this if we assume numbers instead of names:
<
fun {SymDiff A B}
{FS.union {FS.diff A B} {FS.diff B A}}
Line 2,001 ⟶ 2,637:
B = {FS.value.make [5 3 1 2]}
in
{Show {SymDiff A B}}</
=={{header|PARI/GP}}==
<
my(r=List());
u=vecsort(u,,8);
Line 2,012 ⟶ 2,648:
Vec(r)
};
sd(["John", "Serena", "Bob", "Mary", "Serena"],["Jim", "Mary", "John", "Jim", "Bob"])</
=={{header|Pascal}}==
{{works with|FPC 3.0.2}}
<
TYPE
Line 2,039 ⟶ 2,675:
Put('ListA -> ', ListA);
Put('ListB -> ', ListB);
Put('ListA >< ListB -> ', (ListA
Put('ListA - ListB -> ', ListA - ListB);
Put('ListB - ListA -> ', ListB - ListA);
ReadLn;
END.</
{{out}}
<pre>ListA -> Bob John Mary Serena
Line 2,050 ⟶ 2,686:
ListA - ListB -> Serena
ListB - ListA -> Jim</pre>
'''Object Pascal actually has a 'Symmetric Difference' operator `> <`: '''
<syntaxhighlight lang="pascal">
program SymmetricDifference;
type
charSet = set of Char;
var
s1, s2, s3: charSet;
ch: char;
begin
s1 := ['a', 'b', 'c', 'd'];
s2 := ['c', 'd', 'e', 'f'];
s3 := s1 >< s2;
for ch in s3 do
write(ch, ' ');
writeLn;
end.
</syntaxhighlight>
Output:
<pre>
a b e f
</pre>
=={{header|Perl}}==
<
# two lists passed in as references
my %in_a = map(($_=>1), @{+shift});
Line 2,068 ⟶ 2,729:
my ($a, $b, $s) = symm_diff(\@a, \@b);
print "A\\B: @$a\nB\\A: @$b\nSymm: @$s\n";</
{{out}}
<pre>A\B: Serena
Line 2,075 ⟶ 2,736:
=={{header|Phix}}==
<!--<
<span style="color: #008080;">function</span> <span style="color: #000000;">Union</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">sequence</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
Line 2,106 ⟶ 2,767:
<span style="color: #0000FF;">?</span><span style="color: #000000;">Symmetric_Difference</span><span style="color: #0000FF;">(</span><span style="color: #000000;">b</span><span style="color: #0000FF;">,</span><span style="color: #000000;">a</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">Symmetric_Difference</span><span style="color: #0000FF;">(</span><span style="color: #000000;">b</span><span style="color: #0000FF;">,</span><span style="color: #000000;">b</span><span style="color: #0000FF;">)</span>
<!--</
{{Out}}
<pre>
Line 2,115 ⟶ 2,776:
</pre>
You can also use the builtin (which defaults to symmetic differences), though it will crash if you pass it "sets" with duplicate elements.
<!--<
<span style="color: #008080;">include</span> <span style="color: #000000;">sets</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">a</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #008000;">"John"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"Serena"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"Bob"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"Mary"</span><span style="color: #0000FF;">},</span>
Line 2,123 ⟶ 2,784:
<span style="color: #0000FF;">?</span><span style="color: #000000;">difference</span><span style="color: #0000FF;">(</span><span style="color: #000000;">b</span><span style="color: #0000FF;">,</span><span style="color: #000000;">a</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">difference</span><span style="color: #0000FF;">(</span><span style="color: #000000;">b</span><span style="color: #0000FF;">,</span><span style="color: #000000;">b</span><span style="color: #0000FF;">)</span>
<!--</
Same output as above
=={{header|PHP}}==
<
$a = array('John', 'Bob', 'Mary', 'Serena');
$b = array('Jim', 'Mary', 'John', 'Bob');
Line 2,148 ⟶ 2,809:
"\nB \\ A: ", implode(', ', $b_minus_a),
"\nSymmetric difference: ", implode(', ', $symmetric_difference), "\n";
?></
This outputs:
<pre>List A: John, Bob, Mary, Serena
Line 2,155 ⟶ 2,816:
B \ A: Jim
Symmetric difference: Serena, Jim</pre>
=={{header|Picat}}==
Using the <code>ordset</code> module.
<syntaxhighlight lang="picat">import ordset.
go =>
A = ["John", "Serena", "Bob", "Mary", "Serena"].new_ordset(),
B = ["Jim", "Mary", "John", "Jim", "Bob"].new_ordset(),
println(symmetric_difference=symmetric_difference(A,B)),
println(symmetric_difference2=symmetric_difference2(A,B)),
println(subtractAB=subtract(A,B)),
println(subtractBA=subtract(B,A)),
println(union=union(A,B)),
println(intersection=intersection(A,B)),
nl.
symmetric_difference(A,B) = union(subtract(A,B), subtract(B,A)).
% variant
symmetric_difference2(A,B) = subtract(union(A,B), intersection(B,A)).</syntaxhighlight>
{{out}}
<pre>symmetric_difference = [Jim,Serena]
symmetric_difference2 = [Jim,Serena]
subtractAB = [Serena]
subtractBA = [Jim]
union = [Bob,Jim,John,Mary,Serena]
intersection = [Bob,John,Mary]</pre>
=={{header|PicoLisp}}==
<
(uniq (conc (diff A B) (diff B A))) )</
Output:
<pre>(symdiff '(John Serena Bob Mary Serena) '(Jim Mary John Jim Bob))
Line 2,165 ⟶ 2,856:
=={{header|Pike}}==
The set type in Pike is 'multiset', that is, a value may appear multiple times and the difference operator only removes equal amounts of duplicates.
<
> multiset(string) B = (< "Jim", "Mary", "Mary", "John", "Bob", "Jim" >);
> A^B;
Result: (< "Bob", "Serena", "Serena", "Mary", "Jim", "Jim" >)</
The <code>^</code> operator treats arrays like multisets.
<
> array(string) B = ({ "Jim", "Mary", "John", "Jim", "Bob", "Mary" });
> A^B;
Line 2,177 ⟶ 2,868:
> Array.uniq((A-B)+(B-A));
Result: ({ "Serena", "Jim" })</
Set operations are also possible with mappings. Here the difference operator works as expected:
<
> mapping(string:int) B = ([ "Jim":1, "Mary":1, "John":1, "Bob":1 ]);
> A^B;
Result: ([ "Jim": 1, "Serena": 1 ])</
Lastly, there is a Set class.
<
> ADT.Set B = ADT.Set((< "Jim", "Mary", "John", "Jim", "Bob", "Mary" >));
> (A-B)+(B-A);
Result: ADT.Set({ "Serena", "Jim" })</
=={{header|PL/I}}==
<
* 17.08.2013 Walter Pachl
**********************************************************************/
Line 2,211 ⟶ 2,902:
End;
End;
End;</
Output:
<pre>
Line 2,219 ⟶ 2,910:
=={{header|PowerShell}}==
<
"Bob"
"Mary"
Line 2,239 ⟶ 2,930:
# B - A
Compare $A $B | Where SideIndicator -eq "=>" | Select -ExpandProperty InputObject</
{{out}}
<pre>InputObject SideIndicator
Line 2,257 ⟶ 2,948:
=={{header|Prolog}}==
{{Works with|SWI-Prolog}}
<
A = ['John', 'Serena', 'Bob', 'Mary', 'Serena'],
B = ['Jim', 'Mary', 'John', 'Jim', 'Bob'],
Line 2,271 ⟶ 2,962:
format('difference B\\A : ~w~n', [DBA]),
union(DAB, DBA, Diff),
format('symetric difference : ~w~n', [Diff]).</
output :
<pre>A : [John,Serena,Bob,Mary,Serena]
Line 2,284 ⟶ 2,975:
=={{header|PureBasic}}==
===Simple approach===
<
Dim B.s(3)
Line 2,308 ⟶ 2,999:
EndIf
Next a
Next b</
===Solution using lists===
<
SetA:
Data.i 4
Line 2,382 ⟶ 3,073:
Input()
CloseConsole()
EndIf</
Sample output:
<pre>Set A: John, Bob, Mary, Serena
Line 2,393 ⟶ 3,084:
'''Python 3.x''' and '''Python 2.7''' have syntax for set literals:
<
>>> setB = {"Jim", "Mary", "John", "Bob"}
>>> setA ^ setB # symmetric difference of A and B
Line 2,404 ⟶ 3,095:
{'John', 'Bob', 'Jim', 'Serena', 'Mary'}
>>> setA & setB # elements in both A and B (intersection)
{'Bob', 'John', 'Mary'}</
Note that the order of set elements is undefined.
Line 2,410 ⟶ 3,101:
Earlier versions of Python:
<
>>> setB = set(["Jim", "Mary", "John", "Bob"])
>>> setA ^ setB # symmetric difference of A and B
Line 2,416 ⟶ 3,107:
>>> setA - setB # elements in A that are not in B
set(['Serena'])
>>> # and so on...</
There is also a method call interface for these operations. In contrast to the operators above, they accept any iterables as arguments not just sets.
<
{'Jim', 'Serena'}
>>> setA.difference(setB)
Line 2,429 ⟶ 3,120:
{'Jim', 'Mary', 'Serena', 'John', 'Bob'}
>>> setA.intersection(setB)
{'Mary', 'John', 'Bob'}</
=={{header|Quackery}}==
<
( i.e. using the Quackery code for sets at
Line 2,453 ⟶ 3,144:
say "Using built-in symmetric difference: "
A B symmdiff echoset cr </
{{out}}
Line 2,465 ⟶ 3,156:
=={{header|R}}==
<
b <- c( "Jim", "Mary", "John", "Bob" )
c(setdiff(b, a), setdiff(a, b))
Line 2,471 ⟶ 3,162:
a <- c("John", "Serena", "Bob", "Mary", "Serena")
b <- c("Jim", "Mary", "John", "Jim", "Bob")
c(setdiff(b, a), setdiff(a, b)) </
In both cases answer is:
<
=={{header|Racket}}==
<
#lang racket
(define A (set "John" "Bob" "Mary" "Serena"))
Line 2,485 ⟶ 3,176:
(set-subtract A B)
(set-subtract B A)
</syntaxhighlight>
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku"
my \B = set <Jim Mary John Jim Bob>;
Line 2,495 ⟶ 3,186:
say B ∖ A; # Set subtraction
say (A ∪ B) ∖ (A ∩ B); # Symmetric difference, via basic set operations
say A ⊖ B; # Symmetric difference, via dedicated operator</
{{out}}
<pre>set(Serena)
Line 2,503 ⟶ 3,194:
=={{header|REBOL}}==
<
b: [Jim Mary John Jim Bob]
difference a b</
Result is
<pre>
Line 2,511 ⟶ 3,202:
</pre>
=={{header|Refal}}==
<syntaxhighlight lang="refal">$ENTRY Go {
, John Bob Mary Serena: e.A
, Jim Mary John Bob: e.B
= <Prout <Symdiff (e.A) (e.B)>>;
};
Symdiff {
(e.1) (e.2), <Diff (<Set e.1>) (<Set e.2>)>: e.3
, <Diff (<Set e.2>) (<Set e.1>)>: e.4
= <Union (e.3) (e.4)>;
};
Set {
= ;
s.1 e.1 s.1 e.2 = <Set e.1 s.1 e.2>;
s.1 e.1 = s.1 <Set e.1>;
};
Union {
(e.1) (e.2) = <Set e.1 e.2>;
};
Diff {
() (e.1) = ;
(e.1) () = e.1;
(s.1 e.1) (e.2 s.1 e.3) = <Diff (e.1) (e.2 e.3)>;
(s.1 e.1) (e.2) = s.1 <Diff (e.1) (e.2)>;
};</syntaxhighlight>
{{out}}
<pre>Serena Jim</pre>
=={{header|REXX}}==
===version 1===
Line 2,518 ⟶ 3,240:
The '''set''' elements may contain any character permitted with a REXX literal, including the literal character itself (expressed as a double literal delimiter), blanks, brackets, commas, and also a ''null'' value.
<
a= '["John", "Serena", "Bob", "Mary", "Serena"]' /*note the duplicate element: Serena */
b= '["Jim", "Mary", "John", "Jim", "Bob"]' /* " " " " Jim */
Line 2,554 ⟶ 3,276:
say /* [↓] SA ≡ symmetric AND. */
SA= "["strip( strip(SA), 'T', ",")']' /*clean up and add brackets [ ] to it.*/
say ' symmetric AND =' SA /*stick a fork in it, we're all done. */</
{{out|output|text= when using the in-program lists:}}
<pre>
Line 2,567 ⟶ 3,289:
===version 1.5===
This REXX version shows the symmetric difference and symmetric AND between two lists, the lists have items that have imbedded blanks in them as well as some punctuation, and also a ''null'' element.
<
a.=0 /*falsify the booleans*/
a= '["Zahn", "Yi", "Stands with a Fist", "", "Hungry Wolf", "Yi"]'
Line 2,573 ⟶ 3,295:
∙
∙
∙</
{{out|output|text= when using the in-program lists (which has imbedded blanks):}}
<pre>
Line 2,585 ⟶ 3,307:
===version 2===
<
* 14.12.2013 Walter Pachl a short solution
* 16.12.2013 fix duplicate element problem in input
Line 2,609 ⟶ 3,331:
out: parse Arg e
If wordpos(e,res)=0 Then res=res e
Return</
Output:
<pre>Serena Jim</pre>
=={{header|Ring}}==
<
alist = []
blist = []
Line 2,644 ⟶ 3,366:
see "b-a :" see nl
see blist2 see nl
</syntaxhighlight>
=={{header|RPL}}==
<code>DIFFL</code> is defined at [[Set#RPL|Set]]
{{works with|Halcyon Calc|4.2.9}}
≪ DUP2 <span style="color:blue>DIFFL</span>
ROT ROT SWAP <span style="color:blue>DIFFL</span> +
≫ ≫ '<span style="color:blue>SYMDIFF</span>' STO
{"John" "Bob" "Mary" "Serena"} {"Jim" "Mary" "John" "Bob"} <span style="color:blue>SYMDIFF</span>
{{out}}
<pre>
1: {"Jim" "Serena"}
</pre>
=={{header|Ruby}}==
With arrays:
<
b = ["Jim", "Mary", "John", "Jim", "Bob"]
# the union minus the intersection:
p sym_diff = (a | b)-(a & b) # => ["Serena", "Jim"]</
Class Set has a symmetric difference operator built-in:
<
a = Set["John", "Serena", "Bob", "Mary", "Serena"] #Set removes duplicates
b = Set["Jim", "Mary", "John", "Jim", "Bob"]
p sym_diff = a ^ b # => #<Set: {"Jim", "Serena"}></
=={{header|Run BASIC}}==
<
setA$ = "John,Bob,Mary,Serena"
setB$ = "Jim,Mary,John,Bob"
Line 2,679 ⟶ 3,414:
i = i + 1
wend
end function</
<pre>
Jim
Line 2,690 ⟶ 3,425:
Both set types in the std-lib -- <b>HashSet</b> and <b>BTreeSet</b> -- implement a symmetric_difference method.
<
fn main() {
Line 2,703 ⟶ 3,438:
println!("{:?}", diff);
}
</syntaxhighlight>
{{out}}
Line 2,711 ⟶ 3,446:
=={{header|Scala}}==
<
s1: scala.collection.immutable.Set[java.lang.String] = Set(John, Serena, Bob, Mary)
Line 2,718 ⟶ 3,453:
scala> (s1 diff s2) union (s2 diff s1)
res46: scala.collection.immutable.Set[java.lang.String] = Set(Serena, Jim)</
=={{header|Scheme}}==
Line 2,726 ⟶ 3,461:
In pure Scheme, to illustrate implementation of the algorithms:
<
(import (scheme base)
(scheme write))
Line 2,757 ⟶ 3,492:
(display (symmetric-difference '(John Serena Bob Mary Serena)
'(Jim Mary John Jim Bob))) (newline)
</syntaxhighlight>
{{out}}
Line 2,773 ⟶ 3,508:
SRFI 1 is one of the most popular SRFIs. It deals with lists, but also has functions treating lists as sets. The lset functions assume the inputs are sets, so we must delete duplicates if this property is not guaranteed on input.
<
(import (scheme base)
(scheme write)
Line 2,799 ⟶ 3,534:
(display (symmetric-difference '(John Serena Bob Mary Serena)
'(Jim Mary John Jim Bob))) (newline)
</syntaxhighlight>
=={{header|Seed7}}==
<
const type: striSet is set of string;
Line 2,814 ⟶ 3,549:
begin
writeln(setA >< setB);
end func;</
Output:
Line 2,820 ⟶ 3,555:
{Jim, Serena}
</pre>
=={{header|SETL}}==
<syntaxhighlight lang="setl">program symmetric_difference;
A := {"John", "Bob", "Mary", "Serena"};
B := {"Jim", "Mary", "John", "Bob"};
print("A - B:", A - B);
print("B - A:", B - A);
print("Symmetric difference:", (A-B) + (B-A));
end program;</syntaxhighlight>
{{out}}
<pre>A - B: {Serena}
B - A: {Jim}
Symmetric difference: {Jim Serena}</pre>
=={{header|Sidef}}==
<
var b = ["Jim", "Mary", "John", "Jim", "Bob"];
a ^ b -> unique.dump.say;</
{{out}}
<pre>
Line 2,831 ⟶ 3,580:
=={{header|Smalltalk}}==
<
A := Set new.
B := Set new.
Line 2,837 ⟶ 3,586:
B addAll: #( 'Jim' 'Mary' 'John' 'Bob' ).
( (A - B) + (B - A) ) displayNl.</
Output is
<pre>
Line 2,844 ⟶ 3,593:
=={{header|SQL}}/{{header|PostgreSQL}}==
<
select ARRAY(
(
Line 2,857 ⟶ 3,606:
)
)
$$ language sql strict immutable;</
Usage:
<
Output:
<pre>
Line 2,870 ⟶ 3,619:
Swift's <code>Set</code> type supports difference as well as symmetric difference operators.
{{works with|Swift|1.2+}}
<
let setB : Set<String> = ["Jim", "Mary", "John", "Bob"]
println(setA.exclusiveOr(setB)) // symmetric difference of A and B
println(setA.subtract(setB)) // elements in A that are not in B</
{{out}}
<pre>
Line 2,883 ⟶ 3,632:
It's common to represent sets as an unordered list of elements. (It is also the most efficient representation.) The <code>struct::set</code> package contains operations for working on such sets-as-lists.
{{tcllib|struct::set}}
<
set A {John Bob Mary Serena}
Line 2,897 ⟶ 3,646:
# Of course, the library already has this operation directly...
puts "Direct Check: [struct::set symdiff $A $B]"</
Produces this output:<pre>
A\B = Serena
Line 2,906 ⟶ 3,655:
=={{header|TUSCRIPT}}==
<
a="John'Bob'Mary'Serena"
b="Jim'Mary'John'Bob"
Line 2,927 ⟶ 3,676:
LOOP n=names,v=val
PRINT n," in: ",v
ENDLOOP</
Output:
<pre>
Line 2,941 ⟶ 3,690:
=={{header|UNIX Shell}}==
{{works with|Bash}}
<
u=("$@")
for ((i=0;i<${#u[@]};i++)); do
Line 2,983 ⟶ 3,732:
echo "A - B = ${ab[@]}"
echo "B - A = ${ba[@]}"
echo "Symmetric difference = ${sd[@]}"</
Output:
<pre>Set A = John Serena Bob Mary Serena
Line 2,994 ⟶ 3,743:
=={{header|Ursala}}==
<
b = <'Jim','Mary','John','Bob'>
Line 3,006 ⟶ 3,755:
'a not b': ~&j/a b,
'b not a': ~&j/b a,
'symmetric difference': ~&jrljTs/a b></
output:
<pre><
Line 3,014 ⟶ 3,763:
'b not a': <'Jim'>,
'symmetric difference': <'Jim','Serena'>></pre>
=={{header|V (Vlang)}}==
<syntaxhighlight lang="v (vlang)">
const
(
alist = ["john", "bob", "mary", "serena"]
blist = ["jim", "mary", "john", "bob"]
)
fn main() {
mut rlist := []string{}
for elem in alist {
if blist.any(it == elem) == false {
println("a - b = $elem")
rlist << elem
}
}
for elem in blist {
if alist.any(it == elem) == false {
println("b - a = $elem")
rlist << elem
}
}
println("symmetric difference: $rlist")
}
</syntaxhighlight>
{{out}}
<pre>
a - b = serena
b - a = jim
symmetric difference: ['serena', 'jim']
</pre>
=={{header|Wren}}==
{{libheader|Wren-set}}
<
var symmetricDifference = Fn.new { |a, b| a.except(b).union(b.except(a)) }
Line 3,027 ⟶ 3,809:
System.print("A - B = %(a.except(b))")
System.print("B - A = %(b.except(a))")
System.print("A △ B = %(symmetricDifference.call(a, b))")</
{{out}}
Line 3,042 ⟶ 3,824:
operations can represent union, intersection, and difference.
<
proc SetOut(S); \Output the elements in set
Line 3,061 ⟶ 3,843:
Text(0, "B\A = "); SetOut(B & ~A);
Text(0, "A\B U B\A = "); SetOut(A&~B ! B&~A);
]</
{{out}}
Line 3,072 ⟶ 3,854:
=={{header|Yabasic}}==
<
lista2$ = "Jim Mary John Jim Bob"
Line 3,116 ⟶ 3,898:
wend
end sub
</syntaxhighlight>
=={{header|zkl}}==
<
fcn sdiff(list1,list2)
{ list1.extend(list2).copy().removeEach(setCommon(list1,list2)) }</
<
b:=T("Jim","Mary","John","Bob");
sdiff(a,b).println();</
To deal with duplicates, use [[Remove duplicate elements#zkl]]:
<
b:=T("Jim", "Mary", "John", "Jim", "Bob");
sdiff(a,b) : Utils.Helpers.listUnique(_).println();</
{{out}}
<pre>
|