Symmetric difference: Difference between revisions
m
sntax highlighting fixup automation
m (→{{header|Picat}}: code tag) |
Thundergnat (talk | contribs) m (sntax highlighting fixup automation) |
||
Line 24:
{{trans|Python}}
<
V setB = Set([‘Jim’, ‘Mary’, ‘John’, ‘Bob’])
print(setA.symmetric_difference(setB))
print(setA - setB)
print(setB - setA)</
{{out}}
Line 40:
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}}
<
INCLUDE "D2:ALLOCATE.ACT" ;from the Action! Tool Kit. You must type 'SET EndProg=*' from the monitor after compiling, but before running this program!
Line 228:
Clear(s2)
Clear(s3)
RETURN</
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Symmetric_difference.png Screenshot from Atari 8-bit computer]
Line 242:
=={{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 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 277:
=={{header|Aime}}==
<
{
record r;
Line 310:
0;
}</
{{out}}
<pre>Jim
Line 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 373:
e := NEXT c
OD;
print( ( newline ) )</
{{out}}
<pre>
Line 380:
=={{header|Apex}}==
<
Set<String> setB = new Set<String>{'Jim', 'Mary', 'John', 'Bob'};
Line 407:
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 416:
=={{header|APL}}==
{{works with|Dyalog APL}}
<syntaxhighlight lang
{{out}}
<pre> 'John' 'Bob' 'Mary' 'Serena' symdiff 'Jim' 'Mary' 'John' 'Bob'
Line 423:
=={{header|AppleScript}}==
{{Trans|JavaScript}} (ES6 Functional JS)
<
-- symmetricDifference :: [a] -> [a] -> [a]
Line 534:
set sx to nub(xs)
sx & foldl(flipDelete, nub(ys), sx)
end union</
{{Out}}
<
=={{header|Arturo}}==
<
b: ["Jim" "Mary" "John" "Bob"]
print difference.symmetric a b</
{{out}}
Line 549:
=={{header|AutoHotkey}}==
<
setB = Jim, Mary, John, Bob
MsgBox,, Singles, % SymmetricDifference(setA, setB)
Line 571:
Result .= B_%A_Index% ", "
Return, SubStr(Result, 1, -2)
}</
Message boxes show:
<pre>Singles
Line 585:
=={{header|AWK}}==
<syntaxhighlight lang="awk">
# syntax: GAWK -f SYMMETRIC_DIFFERENCE.AWK
BEGIN {
Line 617:
printf("\n")
}
</syntaxhighlight>
<p>output:</p>
<pre>
Line 627:
=={{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 649:
IF set% AND 1 << i% o$ += list$(i%) + ", "
NEXT
= LEFT$(LEFT$(o$))</
'''Output:'''
<pre>
Line 663:
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 678:
?
| !symdiff
));</
Run:
<
Output:
<syntaxhighlight lang
=={{header|C}}==
Simple method:
<
#include <string.h>
Line 737:
return 0;
}</
<pre>
A \ B:
Line 750:
</pre>
If you prefer something elaborate:
<
#include <stdio.h>
#include <string.h>
Line 884:
return 0;
}</
Output
<pre>
Line 893:
=={{header|C sharp|C#}}==
<
using System.Collections.Generic;
using System.Linq;
Line 920:
}
}
}</
Output:
<pre>
Line 928:
=={{header|C++}}==
<
#include <set>
#include <algorithm>
Line 951:
cout << endl;
return 0;
}</
Output:
Line 957:
=={{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 973:
=={{header|D}}==
Generic version.
<
struct Set(T) {
Line 999:
writeln(" B\\A: ", (B - A).items);
writeln("A symdiff B: ", symmetricDifference(A, B).items);
}</
{{out}}
<pre> A\B: ["Serena"]
Line 1,006:
=={{header|Datalog}}==
Implemented using Souffle.
<
.decl B(text: symbol)
.decl SymmetricDifference(text: symbol)
Line 1,022:
SymmetricDifference(x) :- A(x), !B(x).
SymmetricDifference(x) :- B(x), !A(x).</
{{out}}
<pre>
Line 1,036:
{{Trans|Pascal}}
Small variation of pascal.
<syntaxhighlight lang="delphi">
PROGRAM Symmetric_difference;
Line 1,079:
Put('ListB - ListA -> ', ListB - ListA);
ReadLn;
END.</
=={{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 1,096:
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|Eiffel}}==
<syntaxhighlight lang="eiffel">note
description: "Summary description for {SYMETRIC_DIFFERENCE_EXAMPLE}."
URI: "http://rosettacode.org/wiki/Symmetric_difference"
Line 1,152:
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 1,163:
#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 1,177:
SymmDiffAB = sets:subtract(AUnionB,AIntersectionB),
sets:to_list(SymmDiffAB).
</syntaxhighlight>
{{out}}
Line 1,184:
=={{header|F Sharp|F#}}==
<
let b = set ["Jim"; "Mary"; "John"; "Bob"];;
Line 1,191:
> (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 1,227:
swap -1 xor and cr persons
cr bye
</syntaxhighlight>
Output:
<pre>
Line 1,239:
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
<
implicit none
Line 1,260:
end do outer2
end program</
Output
<pre>
Line 1,268:
=={{header|FreeBASIC}}==
<
redim shared as string Result(-1) 'represent our sets as strings;
'this'll do to illustrate the concept
Line 1,311:
print Result(i)
next i
</syntaxhighlight>
{{out}}<pre>Serena
Jim
Line 1,317:
=={{header|Frink}}==
<
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]]</
{{out}}
<pre>
Line 1,331:
=={{header|GAP}}==
<
return Union(Difference(a, b), Difference(b, a));
end;
Line 1,338:
b := ["Jim", "Mary", "John", "Jim", "Bob"];
SymmetricDifference(a,b);
[ "Jim", "Serena" ]</
=={{header|Go}}==
<
import "fmt"
Line 1,361:
}
fmt.Println(sd)
}</
Output:
<pre>
Line 1,367:
</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,474:
ppm <> csny: ${PC}
ppm <> ppm: ${PP}
"""</
Output:
Line 1,518:
=={{header|Haskell}}==
<
a = fromList ["John", "Bob", "Mary", "Serena"]
Line 1,525:
(-|-) :: 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,555:
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,577:
write("}")
return
end</
Sample output:
<pre>a = { Serena Mary Bob John }
Line 1,586:
=={{header|J}}==
<
B=: ~. ;:'Jim Mary John Jim Bob'
Line 1,596:
┌──────┬───┐
│Serena│Jim│
└──────┴───┘</
To illustrate some of the underlying mechanics used here:
<
┌──────┐
│Serena│
Line 1,609:
┌────┬──────┬───┬────┐
│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,661:
System.out.println("Symmetric Difference 2: " + symmetricDifference2);
}
}</
Output:
<pre>In set A: [Mary, Bob, Serena, John]
Line 1,680:
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,695:
print(a);
print(b);
print(symmetric_difference(a,b));</
outputs
<pre>Bob,John,Mary,Serena
Line 1,703:
'''Clear JavaScript'''
<
{
var a = A.length, b = B.length, c = 0, C = [];
Line 1,731:
Difference(B,A); // 'Jim'
SymmetricDifference(A,B); // 'Serena','Jim'
*/</
===ES6===
====Functional====
By composition of generic functions;
<
'use strict';
Line 1,799:
symmetricDifference(a, b)
);
})();</
{{Out}}
<
====Procedural ====
<syntaxhighlight lang="javascript">
const symmetricDifference = (...args) => {
let result = new Set();
Line 1,817:
console.log(symmetricDifference([1, 2, 5], [2, 3, 5], [3, 4, 5]));
</syntaxhighlight>
{{Out}}
<
[1, 4, 5]
</syntaxhighlight>
=={{header|jq}}==
Line 1,828:
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,838:
(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,856:
=={{header|K}}==
<
B: ?("Jim";"Mary";"John";"Bob")
Line 1,865:
(A _dvl B;B _dvl A) / Symmetric difference
("Serena"
"Jim")</
=={{header|Kotlin}}==
<
fun main(args: Array<String>) {
Line 1,881:
val e = c.union(d)
println("A Δ B = $e")
}</
{{out}}
Line 1,893:
=={{header|Ksh}}==
<
#!/bin/ksh
Line 1,938:
AnB=$(_notin A B) ; echo "A - B = ${AnB}"
BnA=$(_notin B A) ; echo "B - A = ${BnA}"
echo "A xor B = ${AnB} ${BnA}"</
{{out}}<pre>A - B = Serena
B - A = Jim
Line 1,944:
=={{header|Lasso}}==
<
[
var(
Line 1,969:
]
</syntaxhighlight>
=={{header|Logo}}==
{{works with|UCB Logo}}
<
if empty? :a [output sentence :acc :b]
ifelse member? first :a :b ~
Line 1,983:
make "b [Jim Mary John Bob]
show diff :a :b ; [Serena Jim]</
=={{header|Lua}}==
<
B = { ["Jim"] = true, ["Mary"] = true, ["John"] = true, ["Bob"] = true }
Line 2,004:
for b_a in pairs(B_A) do
print( b_a )
end</
Object-oriented approach:
<
__index = {
union = function(self, other)
Line 2,063:
print("Intersection A∩B : " .. A:intersection(B))
print("Difference A\\B : " .. A:difference(B))
print("Difference B\\A : " .. B:difference(A))</
'''Output:'''
Line 2,078:
=={{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}
Line 2,087:
=={{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 2,193:
resultantSet = unique(resultantSet); %Make sure there are not duplicates
end %symmetricDifference</
Solution Test:
<
A =
Line 2,217:
ans =
1 4 %Correct</
=={{header|Maxima}}==
<
symmdifference({"John", "Bob", "Mary", "Serena"},
{"Jim", "Mary", "John", "Bob"});
{"Jim", "Serena"}</
=={{header|Mercury}}==
<
:- interface.
Line 2,246:
print_set(Desc, Set, !IO) :-
to_sorted_list(Set, Elems),
io.format("%11s: %s\n", [s(Desc), s(string(Elems))], !IO).</
=={{header|Nim}}==
<
var setA = ["John", "Bob", "Mary", "Serena"].toHashSet
Line 2,255:
echo setA -+- setB # Symmetric difference
echo setA - setB # Difference
echo setB - setA # Difference</
Output:
<pre>{Serena, Jim}
Line 2,262:
=={{header|Objective-C}}==
<
int main(int argc, const char *argv[]) {
Line 2,291:
}
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 2,301:
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 2,316:
# 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 2,333:
=={{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 2,364:
{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,374:
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,385:
Vec(r)
};
sd(["John", "Serena", "Bob", "Mary", "Serena"],["Jim", "Mary", "John", "Jim", "Bob"])</
=={{header|Pascal}}==
{{works with|FPC 3.0.2}}
<
TYPE
Line 2,416:
Put('ListB - ListA -> ', ListB - ListA);
ReadLn;
END.</
{{out}}
<pre>ListA -> Bob John Mary Serena
Line 2,425:
=={{header|Perl}}==
<
# two lists passed in as references
my %in_a = map(($_=>1), @{+shift});
Line 2,441:
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,448:
=={{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,479:
<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,488:
</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,496:
<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,521:
"\nB \\ A: ", implode(', ', $b_minus_a),
"\nSymmetric difference: ", implode(', ', $symmetric_difference), "\n";
?></
This outputs:
<pre>List A: John, Bob, Mary, Serena
Line 2,531:
=={{header|Picat}}==
Using the <code>ordset</code> module.
<
go =>
Line 2,549:
symmetric_difference(A,B) = union(subtract(A,B), subtract(B,A)).
% variant
symmetric_difference2(A,B) = subtract(union(A,B), intersection(B,A)).</
{{out}}
Line 2,560:
=={{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,568:
=={{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,580:
> 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,614:
End;
End;
End;</
Output:
<pre>
Line 2,622:
=={{header|PowerShell}}==
<
"Bob"
"Mary"
Line 2,642:
# B - A
Compare $A $B | Where SideIndicator -eq "=>" | Select -ExpandProperty InputObject</
{{out}}
<pre>InputObject SideIndicator
Line 2,660:
=={{header|Prolog}}==
{{Works with|SWI-Prolog}}
<
A = ['John', 'Serena', 'Bob', 'Mary', 'Serena'],
B = ['Jim', 'Mary', 'John', 'Jim', 'Bob'],
Line 2,674:
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,687:
=={{header|PureBasic}}==
===Simple approach===
<
Dim B.s(3)
Line 2,711:
EndIf
Next a
Next b</
===Solution using lists===
<
SetA:
Data.i 4
Line 2,785:
Input()
CloseConsole()
EndIf</
Sample output:
<pre>Set A: John, Bob, Mary, Serena
Line 2,796:
'''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,807:
{'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,813:
Earlier versions of Python:
<
>>> setB = set(["Jim", "Mary", "John", "Bob"])
>>> setA ^ setB # symmetric difference of A and B
Line 2,819:
>>> 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,832:
{'Jim', 'Mary', 'Serena', 'John', 'Bob'}
>>> setA.intersection(setB)
{'Mary', 'John', 'Bob'}</
=={{header|Quackery}}==
<
( i.e. using the Quackery code for sets at
Line 2,856:
say "Using built-in symmetric difference: "
A B symmdiff echoset cr </
{{out}}
Line 2,868:
=={{header|R}}==
<
b <- c( "Jim", "Mary", "John", "Bob" )
c(setdiff(b, a), setdiff(a, b))
Line 2,874:
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,888:
(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,898:
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,906:
=={{header|REBOL}}==
<
b: [Jim Mary John Jim Bob]
difference a b</
Result is
<pre>
Line 2,921:
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,957:
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,970:
===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,976:
∙
∙
∙</
{{out|output|text= when using the in-program lists (which has imbedded blanks):}}
<pre>
Line 2,988:
===version 2===
<
* 14.12.2013 Walter Pachl a short solution
* 16.12.2013 fix duplicate element problem in input
Line 3,012:
out: parse Arg e
If wordpos(e,res)=0 Then res=res e
Return</
Output:
<pre>Serena Jim</pre>
=={{header|Ring}}==
<
alist = []
blist = []
Line 3,047:
see "b-a :" see nl
see blist2 see nl
</syntaxhighlight>
=={{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 3,082:
i = i + 1
wend
end function</
<pre>
Jim
Line 3,093:
Both set types in the std-lib -- <b>HashSet</b> and <b>BTreeSet</b> -- implement a symmetric_difference method.
<
fn main() {
Line 3,106:
println!("{:?}", diff);
}
</syntaxhighlight>
{{out}}
Line 3,114:
=={{header|Scala}}==
<
s1: scala.collection.immutable.Set[java.lang.String] = Set(John, Serena, Bob, Mary)
Line 3,121:
scala> (s1 diff s2) union (s2 diff s1)
res46: scala.collection.immutable.Set[java.lang.String] = Set(Serena, Jim)</
=={{header|Scheme}}==
Line 3,129:
In pure Scheme, to illustrate implementation of the algorithms:
<
(import (scheme base)
(scheme write))
Line 3,160:
(display (symmetric-difference '(John Serena Bob Mary Serena)
'(Jim Mary John Jim Bob))) (newline)
</syntaxhighlight>
{{out}}
Line 3,176:
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 3,202:
(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 3,217:
begin
writeln(setA >< setB);
end func;</
Output:
Line 3,225:
=={{header|Sidef}}==
<
var b = ["Jim", "Mary", "John", "Jim", "Bob"];
a ^ b -> unique.dump.say;</
{{out}}
<pre>
Line 3,234:
=={{header|Smalltalk}}==
<
A := Set new.
B := Set new.
Line 3,240:
B addAll: #( 'Jim' 'Mary' 'John' 'Bob' ).
( (A - B) + (B - A) ) displayNl.</
Output is
<pre>
Line 3,247:
=={{header|SQL}}/{{header|PostgreSQL}}==
<
select ARRAY(
(
Line 3,260:
)
)
$$ language sql strict immutable;</
Usage:
<
Output:
<pre>
Line 3,273:
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 3,286:
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 3,300:
# 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 3,309:
=={{header|TUSCRIPT}}==
<
a="John'Bob'Mary'Serena"
b="Jim'Mary'John'Bob"
Line 3,330:
LOOP n=names,v=val
PRINT n," in: ",v
ENDLOOP</
Output:
<pre>
Line 3,344:
=={{header|UNIX Shell}}==
{{works with|Bash}}
<
u=("$@")
for ((i=0;i<${#u[@]};i++)); do
Line 3,386:
echo "A - B = ${ab[@]}"
echo "B - A = ${ba[@]}"
echo "Symmetric difference = ${sd[@]}"</
Output:
<pre>Set A = John Serena Bob Mary Serena
Line 3,397:
=={{header|Ursala}}==
<
b = <'Jim','Mary','John','Bob'>
Line 3,409:
'a not b': ~&j/a b,
'b not a': ~&j/b a,
'symmetric difference': ~&jrljTs/a b></
output:
<pre><
Line 3,420:
=={{header|Wren}}==
{{libheader|Wren-set}}
<
var symmetricDifference = Fn.new { |a, b| a.except(b).union(b.except(a)) }
Line 3,430:
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,445:
operations can represent union, intersection, and difference.
<
proc SetOut(S); \Output the elements in set
Line 3,464:
Text(0, "B\A = "); SetOut(B & ~A);
Text(0, "A\B U B\A = "); SetOut(A&~B ! B&~A);
]</
{{out}}
Line 3,475:
=={{header|Yabasic}}==
<
lista2$ = "Jim Mary John Jim Bob"
Line 3,519:
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>
|