Data commit

This commit is contained in:
Ingy döt Net 2023-07-01 11:58:00 -04:00
parent 7387c8f97b
commit cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions

View file

@ -0,0 +1,3 @@
---
from: http://rosettacode.org/wiki/Symmetric_difference
note: Discrete math

View file

@ -0,0 +1,20 @@
;Task
Given two [[set]]s ''A'' and ''B'', compute <math>(A \setminus B) \cup (B \setminus A).</math>
That is, enumerate the items that are in ''A'' or ''B'' but not both. This set is called the [[wp:Symmetric difference|symmetric difference]] of ''A'' and ''B''.
In other words: <math>(A \cup B) \setminus (A \cap B)</math> (the set of items that are in at least one of ''A'' or ''B'' minus the set of items that are in both ''A'' and ''B'').
Optionally, give the individual differences (<math>A \setminus B</math> and <math>B \setminus A</math>) as well.
;Test cases
A = {John, Bob, Mary, Serena}
B = {Jim, Mary, John, Bob}
;Notes
# If your code uses lists of items to represent sets then ensure duplicate items in lists are correctly handled. For example two lists representing sets of <code>a = ["John", "Serena", "Bob", "Mary", "Serena"]</code> and <code>b = ["Jim", "Mary", "John", "Jim", "Bob"]</code> should produce the result of just two strings: <code>["Serena", "Jim"]</code>, in any order.
# In the mathematical notation above <code>A \ B</code> gives the set of items in A that are not in B; <code>A B</code> gives the set of items in both A and B, (their ''union''); and <code>A ∩ B</code> gives the set of items that are in both A and B (their ''intersection'').
<br><br>

View file

@ -0,0 +1,5 @@
V setA = Set([John, Bob, Mary, Serena])
V setB = Set([Jim, Mary, John, Bob])
print(setA.symmetric_difference(setB))
print(setA - setB)
print(setB - setA)

View file

@ -0,0 +1,56 @@
# symetric difference using associative arrays to represent the sets #
# include the associative array code for string keys and values #
PR read "aArray.a68" PR
# adds the elements of s to the associative array a, #
# the elements will have empty strings for values #
OP // = ( REF AARRAY a, []STRING s )REF AARRAY:
BEGIN
FOR s pos FROM LWB s TO UPB s DO
a // s[ s pos ] := ""
OD;
a
END # // # ;
# returns an AARRAY containing the elements of a that aren't in b #
OP - = ( REF AARRAY a, REF AARRAY b )REF AARRAY:
BEGIN
REF AARRAY result := INIT HEAP AARRAY;
REF AAELEMENT e := FIRST a;
WHILE e ISNT nil element DO
IF NOT ( b CONTAINSKEY key OF e ) THEN
result // key OF e := value OF e
FI;
e := NEXT a
OD;
result
END # - # ;
# returns an AARRAY containing the elements of a and those of b #
# i.e. in set terms a UNION b #
OP + = ( REF AARRAY a, REF AARRAY b )REF AARRAY:
BEGIN
REF AARRAY result := INIT HEAP AARRAY;
REF AAELEMENT e := FIRST a;
WHILE e ISNT nil element DO
result // key OF e := value OF e;
e := NEXT a
OD;
e := FIRST b;
WHILE e ISNT nil element DO
result // key OF e := value OF e;
e := NEXT b
OD;
result
END # + # ;
# construct the associative arrays for the task #
REF AARRAY a := INIT LOC AARRAY;
REF AARRAY b := INIT LOC AARRAY;
a // []STRING( "John", "Bob", "Mary", "Serena" );
b // []STRING( "Jim", "Mary", "John", "Bob" );
# find and show the symetric difference of a and b #
REF AARRAY c := ( a - b ) + ( b - a );
REF AAELEMENT e := FIRST c;
WHILE e ISNT nil element DO
print( ( " ", key OF e ) );
e := NEXT c
OD;
print( ( newline ) )

View file

@ -0,0 +1 @@
symdiff ~

View file

@ -0,0 +1,31 @@
# syntax: GAWK -f SYMMETRIC_DIFFERENCE.AWK
BEGIN {
load("John,Bob,Mary,Serena",A)
load("Jim,Mary,John,Bob",B)
show("A \\ B",A,B)
show("B \\ A",B,A)
printf("symmetric difference: ")
for (i in C) {
if (!(i in A && i in B)) {
printf("%s ",i)
}
}
printf("\n")
exit(0)
}
function load(str,arr, i,n,temp) {
n = split(str,temp,",")
for (i=1; i<=n; i++) {
arr[temp[i]]
C[temp[i]]
}
}
function show(str,a,b, i) {
printf("%s: ",str)
for (i in a) {
if (!(i in b)) {
printf("%s ",i)
}
}
printf("\n")
}

View file

@ -0,0 +1,189 @@
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

View file

@ -0,0 +1,27 @@
with Ada.Text_IO; use Ada.Text_IO;
procedure Test_XOR is
type Person is (John, Bob, Mary, Serena, Jim);
type Group is array (Person) of Boolean;
procedure Put (Set : Group) is
First : Boolean := True;
begin
for I in Set'Range loop
if Set (I) then
if First then
First := False;
else
Put (',');
end if;
Put (Person'Image (I));
end if;
end loop;
end Put;
A : Group := (John | Bob | Mary | Serena => True, others => False);
B : Group := (Jim | Mary | John | Bob => True, others => False);
begin
Put ("A xor B = "); Put (A xor B); New_Line;
Put ("A - B = "); Put (A and not B); New_Line;
Put ("B - A = "); Put (B and not A); New_Line;
end Test_XOR;

View file

@ -0,0 +1,34 @@
show_sdiff(record u, x)
{
record r;
text s;
r.copy(u);
for (s in x) {
if (r.key(s)) {
r.delete(s);
} else {
r.p_integer(s, 0);
}
}
r.vcall(o_, 0, "\n");
}
new_set(...)
{
record r;
ucall(r_p_integer, 1, r, 0);
r;
}
main(void)
{
show_sdiff(new_set("John", "Bob", "Mary", "Serena"),
new_set("Jim", "Mary", "John", "Bob"));
0;
}

View file

@ -0,0 +1,28 @@
Set<String> setA = new Set<String>{'John', 'Bob', 'Mary', 'Serena'};
Set<String> setB = new Set<String>{'Jim', 'Mary', 'John', 'Bob'};
// Option 1
Set<String> notInSetA = setB.clone();
notInSetA.removeAll(setA);
Set<String> notInSetB = setA.clone();
notInSetB.removeAll(setB);
Set<String> symmetricDifference = new Set<String>();
symmetricDifference.addAll(notInSetA);
symmetricDifference.addAll(notInSetB);
// Option 2
Set<String> union = setA.clone();
union.addAll(setB);
Set<String> intersection = setA.clone();
intersection.retainAll(setB);
Set<String> symmetricDifference2 = union.clone();
symmetricDifference2.removeAll(intersection);
System.debug('Not in set A: ' + notInSetA);
System.debug('Not in set B: ' + notInSetB);
System.debug('Symmetric Difference: ' + symmetricDifference);
System.debug('Symmetric Difference 2: ' + symmetricDifference2);

View file

@ -0,0 +1,112 @@
-- SYMMETRIC DIFFERENCE -------------------------------------------
-- symmetricDifference :: [a] -> [a] -> [a]
on symmetricDifference(xs, ys)
union(difference(xs, ys), difference(ys, xs))
end symmetricDifference
-- TEST -----------------------------------------------------------
on run
set a to ["John", "Serena", "Bob", "Mary", "Serena"]
set b to ["Jim", "Mary", "John", "Jim", "Bob"]
symmetricDifference(a, b)
--> {"Serena", "Jim"}
end run
-- GENERIC FUNCTIONS ----------------------------------------------
-- delete :: Eq a => a -> [a] -> [a]
on |delete|(x, xs)
set mbIndex to elemIndex(x, xs)
set lng to length of xs
if mbIndex is not missing value then
if lng > 1 then
if mbIndex = 1 then
items 2 thru -1 of xs
else if mbIndex = lng then
items 1 thru -2 of xs
else
tell xs to items 1 thru (mbIndex - 1) & ¬
items (mbIndex + 1) thru -1
end if
else
{}
end if
else
xs
end if
end |delete|
-- difference :: [a] -> [a] -> [a]
on difference(xs, ys)
script
on |λ|(a, y)
if a contains y then
my |delete|(y, a)
else
a
end if
end |λ|
end script
foldl(result, xs, ys)
end difference
-- elemIndex :: a -> [a] -> Maybe Int
on elemIndex(x, xs)
set lng to length of xs
repeat with i from 1 to lng
if x = (item i of xs) then return i
end repeat
return missing value
end elemIndex
-- foldl :: (a -> b -> a) -> a -> [b] -> a
on foldl(f, startValue, xs)
tell mReturn(f)
set v to startValue
set lng to length of xs
repeat with i from 1 to lng
set v to |λ|(v, item i of xs, i, xs)
end repeat
return v
end tell
end foldl
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
if class of f is script then
f
else
script
property |λ| : f
end script
end if
end mReturn
-- nub :: [a] -> [a]
on nub(xs)
if (length of xs) > 1 then
set x to item 1 of xs
[x] & nub(|delete|(x, items 2 thru -1 of xs))
else
xs
end if
end nub
-- union :: [a] -> [a] -> [a]
on union(xs, ys)
script flipDelete
on |λ|(xs, x)
my |delete|(x, xs)
end |λ|
end script
set sx to nub(xs)
sx & foldl(flipDelete, nub(ys), sx)
end union

View file

@ -0,0 +1 @@
{"Serena", "Jim"}

View file

@ -0,0 +1,22 @@
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()

View file

@ -0,0 +1 @@
{"Serena", "Jim"}

View file

@ -0,0 +1,14 @@
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

View file

@ -0,0 +1,14 @@
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

View file

@ -0,0 +1,11 @@
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

View file

@ -0,0 +1,4 @@
a: ["John" "Bob" "Mary" "Serena"]
b: ["Jim" "Mary" "John" "Bob"]
print difference.symmetric a b

View file

@ -0,0 +1,23 @@
setA = John, Bob, Mary, Serena
setB = Jim, Mary, John, Bob
MsgBox,, Singles, % SymmetricDifference(setA, setB)
setA = John, Serena, Bob, Mary, Serena
setB = Jim, Mary, John, Jim, Bob
MsgBox,, Duplicates, % SymmetricDifference(setA, setB)
;---------------------------------------------------------------------------
SymmetricDifference(A, B) { ; returns the symmetric difference of A and B
;---------------------------------------------------------------------------
StringSplit, A_, A, `,, %A_Space%
Loop, %A_0%
If Not InStr(B, A_%A_Index%)
And Not InStr(Result, A_%A_Index%)
Result .= A_%A_Index% ", "
StringSplit, B_, B, `,, %A_Space%
Loop, %B_0%
If Not InStr(A, B_%A_Index%)
And Not InStr(Result, B_%A_Index%)
Result .= B_%A_Index% ", "
Return, SubStr(Result, 1, -2)
}

View file

@ -0,0 +1,23 @@
DIM list$(4)
list$() = "Bob", "Jim", "John", "Mary", "Serena"
setA% = %11101
PRINT "Set A: " FNlistset(list$(), setA%)
setB% = %01111
PRINT "Set B: " FNlistset(list$(), setB%)
REM Compute symmetric difference:
setC% = setA% EOR setB%
PRINT '"Symmetric difference: " FNlistset(list$(), setC%)
REM Optional:
PRINT "Set A \ Set B: " FNlistset(list$(), setA% AND NOT setB%)
PRINT "Set B \ Set A: " FNlistset(list$(), setB% AND NOT setA%)
END
DEF FNlistset(list$(), set%)
LOCAL i%, o$
FOR i% = 0 TO 31
IF set% AND 1 << i% o$ += list$(i%) + ", "
NEXT
= LEFT$(LEFT$(o$))

View file

@ -0,0 +1,16 @@
(SymmetricDifference=
A B x symdiff
. !arg:(?A.?B)
& :?symdiff
& ( !A !B
: ?
( %@?x
& ( !A:? !x ?&!B:? !x ?
| !symdiff:? !x ?
| !symdiff !x:?symdiff
)
& ~
)
?
| !symdiff
));

View file

@ -0,0 +1 @@
SymmetricDifference$(john serena bob mary serena.jim mary john jim bob)

View file

@ -0,0 +1 @@
serena jim

View file

@ -0,0 +1,24 @@
#include <iostream>
#include <set>
#include <algorithm>
#include <iterator>
#include <string>
using namespace std;
int main( ) {
string setA[] = { "John", "Bob" , "Mary", "Serena" };
string setB[] = { "Jim" , "Mary", "John", "Bob" };
set<string>
firstSet( setA , setA + 4 ),
secondSet( setB , setB + 4 ),
symdiff;
set_symmetric_difference( firstSet.begin(), firstSet.end(),
secondSet.begin(), secondSet.end(),
inserter( symdiff, symdiff.end() ) );
copy( symdiff.begin(), symdiff.end(), ostream_iterator<string>( cout , " " ) );
cout << endl;
return 0;
}

View file

@ -0,0 +1,28 @@
using System;
using System.Collections.Generic;
using System.Linq;
namespace RosettaCode.SymmetricDifference
{
public static class IEnumerableExtension
{
public static IEnumerable<T> SymmetricDifference<T>(this IEnumerable<T> @this, IEnumerable<T> that)
{
return @this.Except(that).Concat(that.Except(@this));
}
}
class Program
{
static void Main()
{
var a = new[] { "John", "Bob", "Mary", "Serena" };
var b = new[] { "Jim", "Mary", "John", "Bob" };
foreach (var element in a.SymmetricDifference(b))
{
Console.WriteLine(element);
}
}
}
}

View file

@ -0,0 +1,52 @@
#include <stdio.h>
#include <string.h>
const char *A[] = { "John", "Serena", "Bob", "Mary", "Serena" };
const char *B[] = { "Jim", "Mary", "John", "Jim", "Bob" };
#define LEN(x) sizeof(x)/sizeof(x[0])
/* null duplicate items */
void uniq(const char *x[], int len)
{
int i, j;
for (i = 0; i < len; i++)
for (j = i + 1; j < len; j++)
if (x[j] && x[i] && !strcmp(x[i], x[j])) x[j] = 0;
}
int in_set(const char *const x[], int len, const char *match)
{
int i;
for (i = 0; i < len; i++)
if (x[i] && !strcmp(x[i], match))
return 1;
return 0;
}
/* x - y */
void show_diff(const char *const x[], int lenx, const char *const y[], int leny)
{
int i;
for (i = 0; i < lenx; i++)
if (x[i] && !in_set(y, leny, x[i]))
printf(" %s\n", x[i]);
}
/* X ^ Y */
void show_sym_diff(const char *const x[], int lenx, const char *const y[], int leny)
{
show_diff(x, lenx, y, leny);
show_diff(y, leny, x, lenx);
}
int main()
{
uniq(A, LEN(A));
uniq(B, LEN(B));
printf("A \\ B:\n"); show_diff(A, LEN(A), B, LEN(B));
printf("\nB \\ A:\n"); show_diff(B, LEN(B), A, LEN(A));
printf("\nA ^ B:\n"); show_sym_diff(A, LEN(A), B, LEN(B));
return 0;
}

View file

@ -0,0 +1,135 @@
#include <assert.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
const char *mary="Mary";
const char *bob="Bob";
const char *jim="Jim";
const char *john="John";
const char *serena="Serena";
const char *setA[] = {john,bob,mary,serena};
const char *setB[] = {jim,mary,john,bob};
#define XSET(j) j, (sizeof(j)/sizeof(*j))
#define TALLOC(n,typ) malloc(n*sizeof(typ))
typedef enum {
esdDIFFERENCE,
esdSYMMETRIC } EsdFunction;
/** * * * * * * * * * * * * * * * * * * * *
* return value is difference or symmetric difference set
* its size is returned in sym_size
* f determinse whether it is a symmetric difference, or normal difference
* * * * * * * * * * * * * * * * * * * * **/
const char ** symmdiff( int *sym_size, EsdFunction f, const char *setA[], int setAsize, const char *setB[], int setBsize)
{
int union_size;
int max_union_size;
int diff_size;
const char **union_set;
const char **diff_set;
int *union_xor;
int ix, ixu;
max_union_size = setAsize + setBsize;
union_set = TALLOC(max_union_size, const char *);
union_xor = TALLOC(max_union_size, int);
/* I'm assuming here that setA has no duplicates,
* i.e. is a set in mathematical sense */
for (ix=0; ix<setAsize; ix++) {
union_set[ix] = setA[ix];
union_xor[ix] = 1;
}
diff_size = union_size = setAsize;
for (ix=0; ix<setBsize; ix++) {
for (ixu=0; ixu<union_size; ixu++) {
if (union_set[ixu] == setB[ix]) break;
}
if (ixu < union_size) { /* already in union */
union_xor[ixu] = 1-union_xor[ixu];
diff_size--;
}
else { /* not already in union -add */
if (f == esdSYMMETRIC) {
union_set[ixu] = setB[ix];
union_xor[ixu] = 1;
union_size++;
diff_size++;
}
}
}
/* Put results in symdiff set */
diff_set = TALLOC(diff_size, const char *);
ix = 0;
for (ixu=0; ixu<union_size; ixu++) {
if (union_xor[ixu]) {
if (ix == diff_size) {
printf("Short of space in diff_set\n");
exit(1);
}
diff_set[ix] = union_set[ixu];
ix++;
}
}
*sym_size = diff_size;
free(union_xor);
free(union_set);
return diff_set;
}
/* isSet tests that elements of list are unique, that is, that the list is a
* mathematical set. The uniqueness test implemented here is strcmp. */
int isSet(const char *list[], int lsize)
{
int i, j;
const char *e;
if (lsize == 0) {
return 1;
}
for (i = lsize-1; i>0; i--) {
e = list[i];
for (j = i-1; j>=0; j--) {
if (strcmp(list[j], e) == 0) {
return 0;
}
}
}
return 1;
}
void printSet (const char *set[], int ssize)
{
int ix;
printf(" = {");
for (ix=0;ix<ssize; ix++) {
printf( "%s ", set[ix]);
}
printf("}\n");
}
int main()
{
const char **symset;
int sysize;
/* Validate precondition stated by task, that inputs are sets. */
assert(isSet(XSET(setA)));
assert(isSet(XSET(setB)));
printf ("A symmdiff B");
symset = symmdiff( &sysize, esdSYMMETRIC, XSET(setA), XSET(setB));
printSet(symset, sysize);
free(symset);
printf ("A - B");
symset = symmdiff( &sysize, esdDIFFERENCE, XSET(setA), XSET(setB));
printSet(symset, sysize);
printf ("B - A");
symset = symmdiff( &sysize, esdDIFFERENCE, XSET(setB), XSET(setA));
printSet(symset, sysize);
free(symset);
return 0;
}

View file

@ -0,0 +1,6 @@
(use '[clojure.set])
(defn symmetric-difference [s1 s2]
(union (difference s1 s2) (difference s2 s1)))
(symmetric-difference #{:john :bob :mary :serena} #{:jim :mary :john :bob})

View file

@ -0,0 +1,3 @@
(set-exclusive-or
(remove-duplicates '(John Serena Bob Mary Serena))
(remove-duplicates '(Jim Mary John Jim Bob)))

View file

@ -0,0 +1,27 @@
import std.stdio, std.algorithm, std.array;
struct Set(T) {
immutable T[] items;
Set opSub(in Set other) const pure nothrow {
return items.filter!(x => !other.items.canFind(x)).array.Set;
}
Set opAdd(in Set other) const pure nothrow {
return Set(this.items ~ (other - this).items);
}
}
Set!T symmetricDifference(T)(in Set!T left, in Set!T right)
pure nothrow {
return (left - right) + (right - left);
}
void main() {
immutable A = ["John", "Bob", "Mary", "Serena"].Set!string;
immutable B = ["Jim", "Mary", "John", "Bob"].Set!string;
writeln(" A\\B: ", (A - B).items);
writeln(" B\\A: ", (B - A).items);
writeln("A symdiff B: ", symmetricDifference(A, B).items);
}

View file

@ -0,0 +1,17 @@
.decl A(text: symbol)
.decl B(text: symbol)
.decl SymmetricDifference(text: symbol)
.output SymmetricDifference
A("this").
A("is").
A("a").
A("test").
B("also").
B("part").
B("of").
B("a").
B("test").
SymmetricDifference(x) :- A(x), !B(x).
SymmetricDifference(x) :- B(x), !A(x).

View file

@ -0,0 +1,43 @@
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.

View file

@ -0,0 +1,5 @@
? def symmDiff(a, b) { return (a &! b) | (b &! a) }
# value: <symmDiff>
? symmDiff(["John", "Bob", "Mary", "Serena"].asSet(), ["Jim", "Mary", "John", "Bob"].asSet())
# value: ["Jim", "Serena"].asSet()

View file

@ -0,0 +1,23 @@
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$
break 1
.
.
if a$ <> b$
for c$ in c$[]
if c$ = a$
break 1
.
.
if c$ <> a$
c$[] &= a$
.
.
.
swap a$[] b$[]
.
print c$[]

View file

@ -0,0 +1,45 @@
note
description: "Summary description for {SYMETRIC_DIFFERENCE_EXAMPLE}."
URI: "http://rosettacode.org/wiki/Symmetric_difference"
class
SYMETRIC_DIFFERENCE_EXAMPLE
create
make
feature {NONE} -- Initialization
make
local
a,a1,b,b1: ARRAYED_SET [STRING]
do
create a.make (4)
create b.make (4)
a.compare_objects
b.compare_objects
a.put ("John")
a.put ("Bob")
a.put ("Mary")
a.put ("Serena")
create a1.make (4)
a1.copy (a)
b.put ("Jim")
b.put ("Mary")
b.put ("John")
b.put ("Bob")
create b1.make (4)
b1.copy (b)
a1.subtract (b1)
b.subtract (a)
a1.merge (b)
across a1 as c loop
print (" " + c.item)
end
end
end

View file

@ -0,0 +1,8 @@
iex(1)> a = ~w[John Bob Mary Serena] |> MapSet.new
#MapSet<["Bob", "John", "Mary", "Serena"]>
iex(2)> b = ~w[Jim Mary John Bob] |> MapSet.new
#MapSet<["Bob", "Jim", "John", "Mary"]>
iex(3)> sym_dif = fn(a,b) -> MapSet.difference(MapSet.union(a,b), MapSet.intersection(a,b)) end
#Function<12.54118792/2 in :erl_eval.expr/5>
iex(4)> sym_dif.(a,b)
#MapSet<["Jim", "Serena"]>

View file

@ -0,0 +1,11 @@
%% Implemented by Arjun Sunel
-module(symdiff).
-export([main/0]).
main() ->
SetA = sets:from_list(["John","Bob","Mary","Serena"]),
SetB = sets:from_list(["Jim","Mary","John","Bob"]),
AUnionB = sets:union(SetA,SetB),
AIntersectionB = sets:intersection(SetA,SetB),
SymmDiffAB = sets:subtract(AUnionB,AIntersectionB),
sets:to_list(SymmDiffAB).

View file

@ -0,0 +1,8 @@
> let a = set ["John"; "Bob"; "Mary"; "Serena"]
let b = set ["Jim"; "Mary"; "John"; "Bob"];;
val a : Set<string> = set ["Bob"; "John"; "Mary"; "Serena"]
val b : Set<string> = set ["Bob"; "Jim"; "John"; "Mary"]
> (a-b) + (b-a);;
val it : Set<string> = set ["Jim"; "Serena"]

View file

@ -0,0 +1,2 @@
> Set.union (Set.difference a b) (Set.difference b a);;
val it : Set<string> = set ["Jim"; "Serena"]

View file

@ -0,0 +1,4 @@
: symmetric-diff ( a b -- c )
[ diff ] [ swap diff ] 2bi append ;
{ "John" "Bob" "Mary" "Serena" } { "Jim" "Mary" "John" "Bob" } symmetric-diff .

View file

@ -0,0 +1,23 @@
: elm ( n -- ; one cell per set )
[ cell 8 * 1- ] literal umin CREATE 1 swap lshift ,
DOES> ( -- 2^n ) @ ;
: universe ( u "name" -- )
dup 0 DO I elm latest swap LOOP
CREATE dup , 0 DO , LOOP
DOES> ( n a -- ) dup @ tuck cells +
swap 0
DO ( n a' )
over I rshift 1 AND
IF dup @ name>string space type THEN
1 cells -
LOOP 2drop ;
5 universe john bob mary serena jim persons
john bob mary serena or or or
jim mary john bob or or or
2dup xor persons
2dup -1 xor and cr persons
swap -1 xor and cr persons
cr bye

View file

@ -0,0 +1,22 @@
program Symmetric_difference
implicit none
character(6) :: a(4) = (/ "John ", "Bob ", "Mary ", "Serena" /)
character(6) :: b(4) = (/ "Jim ", "Mary ", "John ", "Bob " /)
integer :: i, j
outer1: do i = 1, size(a)
do j = 1, i-1
if(a(i) == a(j)) cycle outer1 ! Do not check duplicate items
end do
if(.not. any(b == a(i))) write(*,*) a(i)
end do outer1
outer2: do i = 1, size(b)
do j = 1, i-1
if(b(i) == b(j)) cycle outer2 ! Do not check duplicate items
end do
if(.not. any(a == b(i))) write(*,*) b(i)
end do outer2
end program

View file

@ -0,0 +1,42 @@
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

View file

@ -0,0 +1,6 @@
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]]

View file

@ -0,0 +1,8 @@
SymmetricDifference := function(a, b)
return Union(Difference(a, b), Difference(b, a));
end;
a := ["John", "Serena", "Bob", "Mary", "Serena"];
b := ["Jim", "Mary", "John", "Jim", "Bob"];
SymmetricDifference(a,b);
[ "Jim", "Serena" ]

View file

@ -0,0 +1,21 @@
package main
import "fmt"
var a = map[string]bool{"John": true, "Bob": true, "Mary": true, "Serena": true}
var b = map[string]bool{"Jim": true, "Mary": true, "John": true, "Bob": true}
func main() {
sd := make(map[string]bool)
for e := range a {
if !b[e] {
sd[e] = true
}
}
for e := range b {
if !a[e] {
sd[e] = true
}
}
fmt.Println(sd)
}

View file

@ -0,0 +1,6 @@
func main() {
for e := range b {
delete(a, e)
}
fmt.Println(a)
}

View file

@ -0,0 +1,5 @@
def symDiff = { Set s1, Set s2 ->
assert s1 != null
assert s2 != null
(s1 + s2) - (s1.intersect(s2))
}

View file

@ -0,0 +1,93 @@
Set a = ['John', 'Serena', 'Bob', 'Mary', 'Serena']
Set b = ['Jim', 'Mary', 'John', 'Jim', 'Bob']
assert a.size() == 4
assert a == (['Bob', 'John', 'Mary', 'Serena'] as Set)
assert b.size() == 4
assert b == (['Bob', 'Jim', 'John', 'Mary'] as Set)
def aa = symDiff(a, a)
def ab = symDiff(a, b)
def ba = symDiff(b, a)
def bb = symDiff(b, b)
assert aa.empty
assert bb.empty
assert ab == ba
assert ab == (['Jim', 'Serena'] as Set)
assert ab == (['Serena', 'Jim'] as Set)
println """
a: ${a}
b: ${b}
Symmetric Differences
=====================
a <> a: ${aa}
a <> b: ${ab}
b <> a: ${ba}
b <> b: ${bb}
"""
Set apostles = ['Matthew', 'Mark', 'Luke', 'John', 'Peter', 'Paul', 'Silas']
Set beatles = ['John', 'Paul', 'George', 'Ringo', 'Peter', 'Stuart']
Set csny = ['Crosby', 'Stills', 'Nash', 'Young']
Set ppm = ['Peter', 'Paul', 'Mary']
def AA = symDiff(apostles, apostles)
def AB = symDiff(apostles, beatles)
def AC = symDiff(apostles, csny)
def AP = symDiff(apostles, ppm)
def BA = symDiff(beatles, apostles)
def BB = symDiff(beatles, beatles)
def BC = symDiff(beatles, csny)
def BP = symDiff(beatles, ppm)
def CA = symDiff(csny, apostles)
def CB = symDiff(csny, beatles)
def CC = symDiff(csny, csny)
def CP = symDiff(csny, ppm)
def PA = symDiff(ppm, apostles)
def PB = symDiff(ppm, beatles)
def PC = symDiff(ppm, csny)
def PP = symDiff(ppm, ppm)
assert AB == BA
assert AC == CA
assert AP == PA
assert BC == CB
assert BP == PB
assert CP == PC
println """
apostles: ${apostles}
beatles: ${beatles}
csny: ${csny}
ppm: ${ppm}
Symmetric Differences
=====================
apostles <> apostles: ${AA}
apostles <> beatles: ${AB}
apostles <> csny: ${AC}
apostles <> ppm: ${AP}
beatles <> apostles: ${BA}
beatles <> beatles: ${BB}
beatles <> csny: ${BC}
beatles <> ppm: ${BP}
csny <> apostles: ${CA}
csny <> beatles: ${CB}
csny <> csny: ${CC}
csny <> ppm: ${CP}
ppm <> apostles: ${PA}
ppm <> beatles: ${PB}
ppm <> csny: ${PC}
ppm <> ppm: ${PP}
"""

View file

@ -0,0 +1,8 @@
import Data.Set
a = fromList ["John", "Bob", "Mary", "Serena"]
b = fromList ["Jim", "Mary", "John", "Bob"]
(-|-) :: Ord a => Set a -> Set a -> Set a
x -|- y = (x \\ y) `union` (y \\ x)
-- Equivalently: (x `union` y) \\ (x `intersect` y)

View file

@ -0,0 +1,2 @@
*Main> a -|- b
fromList ["Jim","Serena"]

View file

@ -0,0 +1,5 @@
*Main> a \\ b
fromList ["Serena"]
*Main> b \\ a
fromList ["Jim"]

View file

@ -0,0 +1,19 @@
CALL SymmDiff("John,Serena,Bob,Mary,Serena,", "Jim,Mary,John,Jim,Bob,")
CALL SymmDiff("John,Bob,Mary,Serena,", "Jim,Mary,John,Bob,")
SUBROUTINE SymmDiff(set1, set2)
CHARACTER set1, set2, answer*50
answer = " "
CALL setA_setB( set1, set2, answer )
CALL setA_setB( set2, set1, answer )
WRITE(Messagebox,Name) answer ! answer = "Serena,Jim," in both cases
END
SUBROUTINE setA_setB( set1, set2, differences )
CHARACTER set1, set2, differences, a*100
a = set1
EDIT(Text=a, $inLeXicon=set2) ! eg a <= $John,Serena,$Bob,$Mary,Serena,
EDIT(Text=a, Right="$", Mark1, Right=",", Mark2, Delete, DO) ! Serena,Serena,
EDIT(Text=a, Option=1, SortDelDbls=a) ! Option=1: keep case; Serena,
differences = TRIM( differences ) // a
END

View file

@ -0,0 +1,19 @@
procedure main()
a := set(["John", "Serena", "Bob", "Mary", "Serena"])
b := set(["Jim", "Mary", "John", "Jim", "Bob"])
showset("a",a)
showset("b",b)
showset("(a\\b) \xef (b\\a)",(a -- b) ++ (b -- a))
showset("(a\\b)",a -- b)
showset("(b\\a)",b -- a)
end
procedure showset(n,x)
writes(n," = { ")
every writes(!x," ")
write("}")
return
end

View file

@ -0,0 +1,11 @@
A=: ~.;:'John Serena Bob Mary Serena'
B=: ~. ;:'Jim Mary John Jim Bob'
(A-.B) , (B-.A) NB. Symmetric Difference
┌──────┬───┐
│Serena│Jim│
└──────┴───┘
A (-. , -.~) B NB. Tacit equivalent
┌──────┬───┐
│Serena│Jim│
└──────┴───┘

View file

@ -0,0 +1,12 @@
A -. B NB. items in A but not in B
┌──────┐
│Serena│
└──────┘
A -.~ B NB. items in B but not in A
┌───┐
│Jim│
└───┘
A NB. A is a sequence without duplicates
┌────┬──────┬───┬────┐
│John│Serena│Bob│Mary│
└────┴──────┴───┴────┘

View file

@ -0,0 +1,4 @@
A (, -. [ -. -.) B
┌──────┬───┐
│Serena│Jim│
└──────┴───┘

View file

@ -0,0 +1,44 @@
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class SymmetricDifference {
public static void main(String[] args) {
Set<String> setA = new HashSet<String>(Arrays.asList("John", "Serena", "Bob", "Mary", "Serena"));
Set<String> setB = new HashSet<String>(Arrays.asList("Jim", "Mary", "John", "Jim", "Bob"));
// Present our initial data set
System.out.println("In set A: " + setA);
System.out.println("In set B: " + setB);
// Option 1: union of differences
// Get our individual differences.
Set<String> notInSetA = new HashSet<String>(setB);
notInSetA.removeAll(setA);
Set<String> notInSetB = new HashSet<String>(setA);
notInSetB.removeAll(setB);
// The symmetric difference is the concatenation of the two individual differences
Set<String> symmetricDifference = new HashSet<String>(notInSetA);
symmetricDifference.addAll(notInSetB);
// Option 2: union minus intersection
// Combine both sets
Set<String> union = new HashSet<String>(setA);
union.addAll(setB);
// Get the intersection
Set<String> intersection = new HashSet<String>(setA);
intersection.retainAll(setB);
// The symmetric difference is the union of the 2 sets minus the intersection
Set<String> symmetricDifference2 = new HashSet<String>(union);
symmetricDifference2.removeAll(intersection);
// Present our results
System.out.println("Not in set A: " + notInSetA);
System.out.println("Not in set B: " + notInSetB);
System.out.println("Symmetric Difference: " + symmetricDifference);
System.out.println("Symmetric Difference 2: " + symmetricDifference2);
}
}

View file

@ -0,0 +1,16 @@
// in A but not in B
function relative_complement(A, B) {
return A.filter(function(elem) {return B.indexOf(elem) == -1});
}
// in A or in B but not in both
function symmetric_difference(A,B) {
return relative_complement(A,B).concat(relative_complement(B,A));
}
var a = ["John", "Serena", "Bob", "Mary", "Serena"].unique();
var b = ["Jim", "Mary", "John", "Jim", "Bob"].unique();
print(a);
print(b);
print(symmetric_difference(a,b));

View file

@ -0,0 +1,29 @@
function Difference(A,B)
{
var a = A.length, b = B.length, c = 0, C = [];
for (var i = 0; i < a; i++)
{ var j = 0, k = 0;
while (j < b && B[j] !== A[i]) j++;
while (k < c && C[k] !== A[i]) k++;
if (j == b && k == c) C[c++] = A[i];
}
return C;
}
function SymmetricDifference(A,B)
{
var D1 = Difference(A,B), D2 = Difference(B,A),
a = D1.length, b = D2.length;
for (var i = 0; i < b; i++) D1[a++] = D2[i];
return D1;
}
/* Example
A = ['John', 'Serena', 'Bob', 'Mary', 'Serena'];
B = ['Jim', 'Mary', 'John', 'Jim', 'Bob'];
Difference(A,B); // 'Serena'
Difference(B,A); // 'Jim'
SymmetricDifference(A,B); // 'Serena','Jim'
*/

View file

@ -0,0 +1,64 @@
(() => {
'use strict';
const symmetricDifference = (xs, ys) =>
union(difference(xs, ys), difference(ys, xs));
// GENERIC FUNCTIONS ------------------------------------------------------
// First instance of x (if any) removed from xs
// delete_ :: Eq a => a -> [a] -> [a]
const delete_ = (x, xs) => {
const i = xs.indexOf(x);
return i !== -1 ? (xs.slice(0, i)
.concat(xs.slice(i, -1))) : xs;
};
// (\\) :: (Eq a) => [a] -> [a] -> [a]
const difference = (xs, ys) =>
ys.reduce((a, x) => filter(z => z !== x, a), xs);
// filter :: (a -> Bool) -> [a] -> [a]
const filter = (f, xs) => xs.filter(f);
// flip :: (a -> b -> c) -> b -> a -> c
const flip = f => (a, b) => f.apply(null, [b, a]);
// foldl :: (b -> a -> b) -> b -> [a] -> b
const foldl = (f, a, xs) => xs.reduce(f, a);
// nub :: [a] -> [a]
const nub = xs => {
const mht = unconsMay(xs);
return mht.nothing ? xs : (
([h, t]) => [h].concat(nub(t.filter(s => s !== h)))
)(mht.just);
};
// show :: a -> String
const show = x => JSON.stringify(x, null, 2);
// unconsMay :: [a] -> Maybe (a, [a])
const unconsMay = xs => xs.length > 0 ? {
just: [xs[0], xs.slice(1)],
nothing: false
} : {
nothing: true
};
// union :: [a] -> [a] -> [a]
const union = (xs, ys) => {
const sx = nub(xs);
return sx.concat(foldl(flip(delete_), nub(ys), sx));
};
// TEST -------------------------------------------------------------------
const
a = ["John", "Serena", "Bob", "Mary", "Serena"],
b = ["Jim", "Mary", "John", "Jim", "Bob"];
return show(
symmetricDifference(a, b)
);
})();

View file

@ -0,0 +1 @@
["Serena", "Jim"]

View file

@ -0,0 +1,12 @@
const symmetricDifference = (...args) => {
let result = new Set();
for (const x of args)
for (const e of new Set(x))
if (result.has(e)) result.delete(e)
else result.add(e);
return [...result];
}
// TEST -------------------------------------------------------------------
console.log(symmetricDifference(["Jim", "Mary", "John", "Jim", "Bob"],["John", "Serena", "Bob", "Mary", "Serena"]));
console.log(symmetricDifference([1, 2, 5], [2, 3, 5], [3, 4, 5]));

View file

@ -0,0 +1,2 @@
["Jim", "Serena"]
[1, 4, 5]

View file

@ -0,0 +1,10 @@
# The following implementation of intersection (but not symmetric_difference) assumes that the
# elements of a (and of b) are unique and do not include null:
def intersection(a; b):
reduce ((a + b) | sort)[] as $i
([null, []]; if .[0] == $i then [null, .[1] + [$i]] else [$i, .[1]] end)
| .[1] ;
def symmetric_difference(a;b):
(a|unique) as $a | (b|unique) as $b
| (($a + $b) | unique) - (intersection($a;$b));

View file

@ -0,0 +1,2 @@
symmetric_difference( [1,2,1,2]; [2,3] )
[1,3]

View file

@ -0,0 +1,3 @@
A = ["John", "Bob", "Mary", "Serena"]
B = ["Jim", "Mary", "John", "Bob"]
@show A B symdiff(A, B)

View file

@ -0,0 +1,10 @@
A: ?("John";"Bob";"Mary";"Serena")
B: ?("Jim";"Mary";"John";"Bob")
A _dvl B / in A but not in B
"Serena"
B _dvl A / in B but not in A
"Jim"
(A _dvl B;B _dvl A) / Symmetric difference
("Serena"
"Jim")

View file

@ -0,0 +1,14 @@
// version 1.1.2
fun main(args: Array<String>) {
val a = setOf("John", "Bob", "Mary", "Serena")
val b = setOf("Jim", "Mary", "John", "Bob")
println("A = $a")
println("B = $b")
val c = a - b
println("A \\ B = $c")
val d = b - a
println("B \\ A = $d")
val e = c.union(d)
println("A Δ B = $e")
}

View file

@ -0,0 +1,45 @@
#!/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}"

View file

@ -0,0 +1,24 @@
[
var(
'a' = array(
'John'
,'Bob'
,'Mary'
,'Serena'
)
,'b' = array
);
$b->insert( 'Jim' ); // Alternate method of populating array
$b->insert( 'Mary' );
$b->insert( 'John' );
$b->insert( 'Bob' );
$a->sort( true ); // arrays must be sorted (true = ascending) for difference to work
$b->sort( true );
$a->difference( $b )->union( $b->difference( $a ) );
]

View file

@ -0,0 +1,11 @@
to diff :a :b [:acc []]
if empty? :a [output sentence :acc :b]
ifelse member? first :a :b ~
[output (diff butfirst :a remove first :a :b :acc)] ~
[output (diff butfirst :a :b lput first :a :acc)]
end
make "a [John Bob Mary Serena]
make "b [Jim Mary John Bob]
show diff :a :b ; [Serena Jim]

View file

@ -0,0 +1,19 @@
A = { ["John"] = true, ["Bob"] = true, ["Mary"] = true, ["Serena"] = true }
B = { ["Jim"] = true, ["Mary"] = true, ["John"] = true, ["Bob"] = true }
A_B = {}
for a in pairs(A) do
if not B[a] then A_B[a] = true end
end
B_A = {}
for b in pairs(B) do
if not A[b] then B_A[b] = true end
end
for a_b in pairs(A_B) do
print( a_b )
end
for b_a in pairs(B_A) do
print( b_a )
end

View file

@ -0,0 +1,56 @@
SetPrototype = {
__index = {
union = function(self, other)
local res = Set{}
for k in pairs(self) do res[k] = true end
for k in pairs(other) do res[k] = true end
return res
end,
intersection = function(self, other)
local res = Set{}
for k in pairs(self) do res[k] = other[k] end
return res
end,
difference = function(self, other)
local res = Set{}
for k in pairs(self) do
if not other[k] then res[k] = true end
end
return res
end,
symmetric_difference = function(self, other)
return self:difference(other):union(other:difference(self))
end
},
-- return string representation of set
__tostring = function(self)
-- list to collect all elements from the set
local l = {}
for k in pairs(self) do l[#l+1] = k end
return "{" .. table.concat(l, ", ") .. "}"
end,
-- allow concatenation with other types to yield string
__concat = function(a, b)
return (type(a) == 'string' and a or tostring(a)) ..
(type(b) == 'string' and b or tostring(b))
end
}
function Set(items)
local _set = {}
setmetatable(_set, SetPrototype)
for _, item in ipairs(items) do _set[item] = true end
return _set
end
A = Set{"John", "Serena", "Bob", "Mary", "Serena"}
B = Set{"Jim", "Mary", "John", "Jim", "Bob"}
print("Set A: " .. A)
print("Set B: " .. B)
print("\nSymm. difference (A\\B)(B\\A): " .. A:symmetric_difference(B))
print("Union AB : " .. A:union(B))
print("Intersection A∩B : " .. A:intersection(B))
print("Difference A\\B : " .. A:difference(B))
print("Difference B\\A : " .. B:difference(A))

View file

@ -0,0 +1,5 @@
>> [setdiff([1 2 3],[2 3 4]) setdiff([2 3 4],[1 2 3])]
ans =
1 4

View file

@ -0,0 +1,91 @@
function resultantSet = symmetricDifference(set1,set2)
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' );
%% Helper function definitions
%Define what set equality means for cell arrays
function trueFalse = equality(set1,set2)
if xor(iscell(set1),iscell(set2)) %set1 or set2 is a set and the other isn't
trueFalse = false;
return
elseif ~(iscell(set1) || iscell(set2)) %set1 and set2 are not sets
if ischar(set1) && ischar(set2) %set1 and set2 are chars or strings
trueFalse = strcmp(set1,set2);
elseif xor(ischar(set1),ischar(set2)) %set1 or set2 is a string but the other isn't
trueFalse = false;
else %set1 and set2 are not strings
if numel(set1) == numel(set2) %Since they must be matricies if the are of equal cardinality then they can be compaired
trueFalse = all((set1 == set2));
else %If they aren't of equal cardinality then they can't be equal
trueFalse = false;
end
end
return
else %set1 and set2 are both sets
for x = (1:numel(set1))
trueFalse = false;
for y = (1:numel(set2))
%Compair the current element of set1 with every element
%in set2
trueFalse = equality(set1{x},set2{y});
%If the element of set1 is equal to the current element
%of set2 remove that element from set2 and break out of
%this inner loop
if trueFalse
set2(y) = [];
break
end
end
%If the loop completes without breaking then the current
%element of set1 is not contained in set2 therefore the two
%sets are not equal and we can return an equality of false
if (~trueFalse)
return
end
end
%If, after checking every element in both sets, there are still
%elements in set2 then the two sets are not equivalent
if ~isempty(set2)
trueFalse = false;
end
%If the executation makes it here without the previous if
%statement evaluating to true, then this function will return
%true.
end
end %equality
%Define the relative complement for cell arrays
function set1 = relativeComplement(set1,set2)
for k = (1:numel(set2))
if numel(set1) == 0
return
end
j = 1;
while j <= numel(set1)
if equality(set1{j},set2{k})
set1(j) = [];
j = j-1;
end
j = j+1;
end
end
end %relativeComplement
%% The Symmetric Difference Algorithm
if iscell(set1) && iscell(set2)
resultantSet = [relativeComplement(set1,set2) relativeComplement(set2,set1)];
else
resultantSet = [setdiff(set1,set2) setdiff(set2,set1)];
end
resultantSet = unique(resultantSet); %Make sure there are not duplicates
end %symmetricDifference

View file

@ -0,0 +1,23 @@
>> A = {'John','Bob','Mary','Serena'}
A =
'John' 'Bob' 'Mary' 'Serena'
>> B = {'Jim','Mary','John','Bob'}
B =
'Jim' 'Mary' 'John' 'Bob'
>> symmetricDifference(A,B)
ans =
'Serena' 'Jim' %Correct
>> symmetricDifference([1 2 3],[2 3 4])
ans =
1 4 %Correct

View file

@ -0,0 +1,2 @@
A := {John, Bob, Mary, Serena};
B := {Jim, Mary, John, Bob};

View file

@ -0,0 +1 @@
symmdiff(A, B);

View file

@ -0,0 +1 @@
SymmetricDifference[x_List,y_List] := Join[Complement[x,Intersection[x,y]],Complement[y,Intersection[x,y]]]

View file

@ -0,0 +1 @@
CachedSymmetricDifference[x_List,y_List] := Module[{intersect=Intersection[x,y]},Join[Complement[x,intersect],Complement[y,intersect]]]

View file

@ -0,0 +1,4 @@
/* builtin */
symmdifference({"John", "Bob", "Mary", "Serena"},
{"Jim", "Mary", "John", "Bob"});
{"Jim", "Serena"}

View file

@ -0,0 +1,21 @@
:- module symdiff.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.
:- implementation.
:- import_module list, set, string.
main(!IO) :-
A = set(["John", "Bob", "Mary", "Serena"]),
B = set(["Jim", "Mary", "John", "Bob"]),
print_set("A\\B", DiffAB @ (A `difference` B), !IO),
print_set("B\\A", DiffBA @ (B `difference` A), !IO),
print_set("A symdiff B", DiffAB `union` DiffBA, !IO).
:- pred print_set(string::in, set(T)::in, io::di, io::uo) is det.
print_set(Desc, Set, !IO) :-
to_sorted_list(Set, Elems),
io.format("%11s: %s\n", [s(Desc), s(string(Elems))], !IO).

View file

@ -0,0 +1,7 @@
import sets
var setA = ["John", "Bob", "Mary", "Serena"].toHashSet
var setB = ["Jim", "Mary", "John", "Bob"].toHashSet
echo setA -+- setB # Symmetric difference
echo setA - setB # Difference
echo setB - setA # Difference

View file

@ -0,0 +1,8 @@
let unique lst =
let f lst x = if List.mem x lst then lst else x::lst in
List.rev (List.fold_left f [] lst)
let ( -| ) a b =
unique (List.filter (fun v -> not (List.mem v b)) a)
let ( -|- ) a b = (b -| a) @ (a -| b)

View file

@ -0,0 +1,14 @@
# let a = [ "John"; "Bob"; "Mary"; "Serena" ]
and b = [ "Jim"; "Mary"; "John"; "Bob" ]
;;
val a : string list = ["John"; "Bob"; "Mary"; "Serena"]
val b : string list = ["Jim"; "Mary"; "John"; "Bob"]
# a -|- b ;;
- : string list = ["Jim"; "Serena"]
# a -| b ;;
- : string list = ["Serena"]
# b -| a ;;
- : string list = ["Jim"]

View file

@ -0,0 +1,30 @@
#import <Foundation/Foundation.h>
int main(int argc, const char *argv[]) {
@autoreleasepool {
NSSet* setA = [NSSet setWithObjects:@"John", @"Serena", @"Bob", @"Mary", @"Serena", nil];
NSSet* setB = [NSSet setWithObjects:@"Jim", @"Mary", @"John", @"Jim", @"Bob", nil];
// Present our initial data set
NSLog(@"In set A: %@", setA);
NSLog(@"In set B: %@", setB);
// Get our individual differences.
NSMutableSet* notInSetA = [NSMutableSet setWithSet:setB];
[notInSetA minusSet:setA];
NSMutableSet* notInSetB = [NSMutableSet setWithSet:setA];
[notInSetB minusSet:setB];
// The symmetric difference is the concatenation of the two individual differences
NSMutableSet* symmetricDifference = [NSMutableSet setWithSet:notInSetA];
[symmetricDifference unionSet:notInSetB];
// Present our results
NSLog(@"Not in set A: %@", notInSetA);
NSLog(@"Not in set B: %@", notInSetB);
NSLog(@"Symmetric Difference: %@", symmetricDifference);
}
return 0;
}

View file

@ -0,0 +1,6 @@
a = .set~of("John", "Bob", "Mary", "Serena")
b = .set~of("Jim", "Mary", "John", "Bob")
-- the xor operation is a symmetric difference
do item over a~xor(b)
say item
end

View file

@ -0,0 +1,32 @@
declare
fun {SymDiff A B}
{Union {Diff A B} {Diff B A}}
end
%% implement sets in terms of lists
fun {MakeSet Xs}
set({Nub2 Xs nil})
end
fun {Diff set(A) set(B)}
set({FoldL B List.subtract A})
end
fun {Union set(A) set(B)}
set({Append A B})
end
%% --
fun {Nub2 Xs Ls}
case Xs of nil then nil
[] X|Xr andthen {Member X Ls} then {Nub2 Xr Ls}
[] X|Xr then X|{Nub2 Xr X|Ls}
end
end
in
{Show {SymDiff
{MakeSet [john bob mary serena]}
{MakeSet [jim mary john bob]}}}
{Show {SymDiff
{MakeSet [john serena bob mary serena]}
{MakeSet [jim mary john jim bob]}}}

View file

@ -0,0 +1,9 @@
declare
fun {SymDiff A B}
{FS.union {FS.diff A B} {FS.diff B A}}
end
A = {FS.value.make [1 2 3 4]}
B = {FS.value.make [5 3 1 2]}
in
{Show {SymDiff A B}}

View file

@ -0,0 +1,9 @@
sd(u,v)={
my(r=List());
u=vecsort(u,,8);
v=vecsort(v,,8);
for(i=1,#u,if(!setsearch(v,u[i]),listput(r,u[i])));
for(i=1,#v,if(!setsearch(u,v[i]),listput(r,v[i])));
Vec(r)
};
sd(["John", "Serena", "Bob", "Mary", "Serena"],["Jim", "Mary", "John", "Jim", "Bob"])

View file

@ -0,0 +1,22 @@
<?php
$a = array('John', 'Bob', 'Mary', 'Serena');
$b = array('Jim', 'Mary', 'John', 'Bob');
// Remove any duplicates
$a = array_unique($a);
$b = array_unique($b);
// Get the individual differences, using array_diff()
$a_minus_b = array_diff($a, $b);
$b_minus_a = array_diff($b, $a);
// Simply merge them together to get the symmetric difference
$symmetric_difference = array_merge($a_minus_b, $b_minus_a);
// Present our results.
echo 'List A: ', implode(', ', $a),
"\nList B: ", implode(', ', $b),
"\nA \\ B: ", implode(', ', $a_minus_b),
"\nB \\ A: ", implode(', ', $b_minus_a),
"\nSymmetric difference: ", implode(', ', $symmetric_difference), "\n";
?>

View file

@ -0,0 +1,21 @@
/* PL/I ***************************************************************
* 17.08.2013 Walter Pachl
**********************************************************************/
*process source attributes xref;
sd: Proc Options(main);
Dcl a(4) Char(20) Var Init('John','Bob','Mary','Serena');
Dcl b(4) Char(20) Var Init('Jim','Mary','John','Bob');
Call match(a,b);
Call match(b,a);
match: Proc(x,y);
Dcl (x(*),y(*)) Char(*) Var;
Dcl (i,j) Bin Fixed(31);
Do i=1 To hbound(x);
Do j=1 To hbound(y);
If x(i)=y(j) Then Leave;
End;
If j>hbound(y) Then
Put Edit(x(i))(Skip,a);
End;
End;
End;

View file

@ -0,0 +1,28 @@
PROGRAM Symmetric_difference;
TYPE
TName = (Bob, Jim, John, Mary, Serena);
TList = SET OF TName;
PROCEDURE Put(txt : String; ResSet : TList);
VAR
I : TName;
BEGIN
Write(txt);
FOR I IN ResSet DO Write(I,' ');
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);
Put('ListA - ListB -> ', ListA - ListB);
Put('ListB - ListA -> ', ListB - ListA);
ReadLn;
END.

View file

@ -0,0 +1,17 @@
sub symm_diff {
# two lists passed in as references
my %in_a = map(($_=>1), @{+shift});
my %in_b = map(($_=>1), @{+shift});
my @a = grep { !$in_b{$_} } keys %in_a;
my @b = grep { !$in_a{$_} } keys %in_b;
# return A-B, B-A, A xor B as ref to lists
return \@a, \@b, [ @a, @b ]
}
my @a = qw(John Serena Bob Mary Serena);
my @b = qw(Jim Mary John Jim Bob );
my ($a, $b, $s) = symm_diff(\@a, \@b);
print "A\\B: @$a\nB\\A: @$b\nSymm: @$s\n";

View file

@ -0,0 +1,32 @@
(phixonline)-->
<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>
<span style="color: #008080;">if</span> <span style="color: #008080;">not</span> <span style="color: #7060A8;">find</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">],</span><span style="color: #000000;">b</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">b</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">append</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: #000000;">i</span><span style="color: #0000FF;">])</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">b</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">Difference</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: #004080;">sequence</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</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>
<span style="color: #008080;">if</span> <span style="color: #008080;">not</span> <span style="color: #7060A8;">find</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">],</span><span style="color: #000000;">b</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">and</span> <span style="color: #008080;">not</span> <span style="color: #7060A8;">find</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">],</span><span style="color: #000000;">res</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">append</span><span style="color: #0000FF;">(</span><span style="color: #000000;">res</span><span style="color: #0000FF;">,</span><span style="color: #000000;">a</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">])</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">res</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">Symmetric_Difference</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;">return</span> <span style="color: #000000;">Union</span><span style="color: #0000FF;">(</span><span style="color: #000000;">Difference</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">b</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;">a</span><span style="color: #0000FF;">))</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</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> <span style="color: #008000;">"Serena"</span><span style="color: #0000FF;">},</span>
<span style="color: #000000;">b</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #008000;">"Jim"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"Mary"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"John"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"Jim"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"Bob"</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;">a</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;">a</span><span style="color: #0000FF;">,</span><span style="color: #000000;">b</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;">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>
<!--

View file

@ -0,0 +1,9 @@
(phixonline)-->
<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>
<span style="color: #000000;">b</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #008000;">"Jim"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"Mary"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"John"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"Bob"</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;">a</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;">a</span><span style="color: #0000FF;">,</span><span style="color: #000000;">b</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;">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>
<!--

View file

@ -0,0 +1,19 @@
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)).

View file

@ -0,0 +1,2 @@
(de symdiff (A B)
(uniq (conc (diff A B) (diff B A))) )

View file

@ -0,0 +1,5 @@
> multiset(string) A = (< "John", "Serena", "Bob", "Mary", "Bob", "Serena" >);
> multiset(string) B = (< "Jim", "Mary", "Mary", "John", "Bob", "Jim" >);
> A^B;
Result: (< "Bob", "Serena", "Serena", "Mary", "Jim", "Jim" >)

Some files were not shown because too many files have changed in this diff Show more