use strict;
use warnings;
use ntheory <nth_prime is_prime>;

my($n, $s, $limit, @sums) = (0, 0, 1000);
do {
    push @sums, sprintf '%3d %8d', $n, $s if is_prime($s += nth_prime ++$n)
} until $n >= $limit;

print "Of the first $limit primes: @{[scalar @sums]} cumulative prime sums:\n", join "\n", @sums;


function sp(integer n) return is_prime(sum(get_primes(-n))) end function
sequence res = apply(filter(tagset(length(get_primes_le(1000))),sp),sprint)
printf(1,"Found %d of em: %s\n",{length(res),join(shorten(res,"",5),", ")})


'''Prime sums of primes up to 1000'''

from itertools import accumulate, chain, takewhile

# primeSums :: [(Int, (Int, Int))]
def primeSums():
    '''Non finite stream of enumerated tuples,
       in which the first value is a prime,
       and the second the sum of that prime and all
       preceding primes.
    '''
    return (
        x for x in enumerate(
            accumulate(
                chain([(0, 0)], primes()),
                lambda a, p: (p, p + a[1])
            )
        ) if isPrime(x[1][1])
    )

# ------------------------- TEST -------------------------
# main :: IO ()
def main():
    '''Prime sums of primes below 1000'''
    for x in takewhile(
            lambda t: 1000 > t[1][0],
            primeSums()
    ):
        print(f'{x[0]} -> {x[1][1]}')

# ----------------------- GENERIC ------------------------

# isPrime :: Int -> Bool
def isPrime(n):
    '''True if n is prime.'''
    if n in (2, 3):
        return True
    if 2 > n or 0 == n % 2:
        return False
    if 9 > n:
        return True
    if 0 == n % 3:
        return False

    def p(x):
        return 0 == n % x or 0 == n % (2 + x)

    return not any(map(p, range(5, 1 + int(n ** 0.5), 6)))

# primes :: [Int]
def primes():
    ''' Non finite sequence of prime numbers.
    '''
    n = 2
    dct = {}
    while True:
        if n in dct:
            for p in dct[n]:
                dct.setdefault(n + p, []).append(p)
            del dct[n]
        else:
            yield n
            dct[n * n] = [n]
        n = 1 + n

# MAIN ---
if __name__ == '__main__':
    main()


use Lingua::EN::Numbers;

my @primes    = grep *.is-prime, ^Inf;
my @primesums = [\+] @primes;
say "{.elems} cumulative prime sums:\n",
    .map( -> $p {
        sprintf "The sum of the first %3d (up to {@primes[$p]}) is prime: %s",
        1 + $p, comma @primesums[$p]
      }
    ).join("\n")
    given grep { @primesums[$_].is-prime }, ^1000;


/*REXX pgm finds summation primes P,  primes which the sum of primes up to P are prime. */
parse arg hi .                                   /*obtain optional argument from the CL.*/
if hi=='' | hi==","  then hi= 1000               /*Not specified?  Then use the default.*/
call genP                                        /*build array of semaphores for primes.*/
w= 30;     w2= w*2%3;      pad= left('',w-w2)    /*the width of the columns two & three.*/
title= ' summation primes which the sum of primes up to  P  is also prime,  P  < '  ,
                                    commas(hi)
say ' index │' center(subword(title, 1, 2), w)  center('prime sum', w)  /*display title.*/
say '───────┼'center(""   , 1 + (w+1)*2,  '─')                          /*   "    sep.  */
found= 0                                         /*initialize # of summation primes.    */
                                      $= 0       /*sum of primes up to the current prime*/
          do j=1  for hi-1;  p= @.j;  $= $ + p   /*find summation primes within range.  */
          if \!.$  then iterate                  /*Is sum─of─primes a prime?  Then skip.*/
          found= found + 1                       /*bump the number of summation primes. */
          say right(j, 6) '│'strip( right(commas(p), w2)pad || right(commas($), w2), "T")
          end   /*j*/

say '───────┴'center(""   , 1 + (w+1)*2,  '─')   /*display foot separator after output. */
say
say 'Found '       commas(found)      title
exit 0                                           /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
commas: parse arg ?;  do jc=length(?)-3  to 1  by -3; ?=insert(',', ?, jc); end;  return ?
/*──────────────────────────────────────────────────────────────────────────────────────*/
genP: !.= 0;  sP= 0                              /*prime semaphores;  sP= sum of primes.*/
      @.1=2;  @.2=3;  @.3=5;  @.4=7;  @.5=11     /*define some low primes.              */
      !.2=1;  !.3=1;  !.5=1;  !.7=1;  !.11=1     /*   "     "   "    "     flags.       */
                        #=5;  sq.#= @.# **2      /*number of primes so far;     prime². */
                                                 /* [↓]  generate more  primes  ≤  high.*/
        do [email protected].#+2  by 2  until @.#>=hi & @.#>sP /*find odd primes where  P≥hi and P>sP.*/
        parse var j '' -1 _; if _==5  then iterate            /*J ÷ by 5?  (right digit)*/
        if j//3==0  then iterate;  if j//7==0  then iterate   /*J ÷ by 3?;   J ÷ by 7?  */
               do k=5  while sq.k<=j             /* [↓]  divide by the known odd primes.*/
               if j // @.k == 0  then iterate j  /*Is  J ÷ X?  Then not prime.     ___  */
               end   /*k*/                       /* [↑]  only process numbers  ≤  √ J   */
        #= #+1;    @.#= j;   sq.#= j*j;   !.j= 1 /*bump # Ps; assign next P; P square; P*/
        if @.#<hi  then sP= sP + @.#             /*maybe add this prime to sum─of─primes*/
        end          /*j*/;               return


load "stdlib.ring"
see "working..." + nl
see "Summarize primes:" + nl
see "n sum" + nl
row = 0
sum = 0
limit = 1000
Primes = []

for n = 2 to limit
    if isprime(n)
       add(Primes,n)
    ok
next

for n = 1 to len(Primes)
    sum = sum + Primes[n]
    if isprime(sum)
       row = row + 1
       see "" + n + " " + sum + nl
    ok
next

see "Found " + row + " numbers" + nl
see "done..." + nl


def isPrime(n)
    if n < 2 then
        return false
    end

    if n % 2 == 0 then
        return n == 2
    end
    if n % 3 == 0 then
        return n == 3
    end

    i = 5
    while i * i <= n
        if n % i == 0 then
            return false
        end
        i += 2

        if n % i == 0 then
            return false
        end
        i += 4
    end
    return true
end

START = 1
STOP = 1000

sum = 0
count = 0
sc = 0

for p in START .. STOP
    if isPrime(p) then
        count += 1
        sum += p
        if isPrime(sum) then
            print "The sum of %3d primes in [2, %3d] is %5d which is also prime\n" % [count, p, sum]
            sc += 1
        end
    end
end
print "There are %d summerized primes in [%d, %d]\n" % [sc, START, STOP]


// [dependencies]
// primal = "0.3"

fn main() {
    let limit = 1000;
    let mut sum = 0;
    println!("count  prime      sum");
    for (n, p) in primal::Sieve::new(limit)
        .primes_from(2)
        .take_while(|x| *x < limit)
        .enumerate()
    {
        sum += p;
        if primal::is_prime(sum as u64) {
            println!("  {:>3}    {:>3}    {:>5}", n + 1, p, sum);
        }
    }
}


1000.primes.map_reduce {|a,b| a + b }.map_kv {|k,v|
    [k+1, prime(k+1), v]
}.grep { .tail.is_prime }.prepend(
    ['count', 'prime', 'sum']
).each_2d {|n,p,s|
    printf("%5s %6s %8s\n", n, p, s)
}


import "/math" for Int
import "/fmt" for Fmt

var primes = Int.primeSieve(999)
var sum = 0
var n = 0
var c = 0
System.print("Summing the first n primes (<1,000) where the sum is itself prime:")
System.print("  n  cumulative sum")
for (p in primes) {
    n = n + 1
    sum = sum + p
    if (Int.isPrime(sum)) {
        c = c + 1
        Fmt.print("$3d   $,6d", n, sum)
    }
}
System.print("\n%(c) such prime sums found")


func IsPrime(N);        \Return 'true' if N is a prime number
int  N, I;
[if N <= 1 then return false;
for I:= 2 to sqrt(N) do
    if rem(N/I) = 0 then return false;
return true;
];

int Count, N, Sum, Prime;
[Text(0, "Prime Prime
count   sum
");
Count:= 0;  N:= 0;  Sum:= 0;
for Prime:= 2 to 1000-1 do
    if IsPrime(Prime) then
        [N:= N+1;
        Sum:= Sum + Prime;
        if IsPrime(Sum) then
            [Count:= Count+1;
            IntOut(0, N);
            ChOut(0, 9\tab\);
            IntOut(0, Sum);
            CrLf(0);
            ];
        ];
IntOut(0, Count);
Text(0, " prime sums of primes found below 1000.
");
]


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)


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;


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;
}


# 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 ) )


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);


-- 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


a: ["John" "Bob" "Mary" "Serena"]
b: ["Jim" "Mary" "John" "Bob"]

print difference.symmetric a b


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)
}


# 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")
}


      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$))


(SymmetricDifference=
  A B x symdiff
.   !arg:(?A.?B)
  & :?symdiff
  & (   !A !B
      :   ?
          ( %@?x
          & ( !A:? !x ?&!B:? !x ?
            | !symdiff:? !x ?
            | !symdiff !x:?symdiff
            )
          & ~
          )
          ?
    | !symdiff
    ));


#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;
}


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);
            }
        }
    }
}


#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;
}


(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})


(set-exclusive-or
  (remove-duplicates '(John Serena Bob Mary Serena))
  (remove-duplicates '(Jim Mary John Jim Bob)))


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);
}


.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).


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.


set :setA set{ :John :Bob :Mary :Serena }
set :setB set{ :Jim :Mary :John :Bob }

symmetric-difference A B:
	}
	for a in keys A:
		if not has B a:
			a
	for b in keys B:
		if not has A b:
			b
	set{

!. symmetric-difference setA setB


? 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()


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


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"]>


%% 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).


> 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"]


: symmetric-diff ( a b -- c )
    [ diff ] [ swap diff ] 2bi append ;

{ "John" "Bob" "Mary" "Serena" } { "Jim" "Mary" "John" "Bob" } symmetric-diff .


: 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


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


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


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]]


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" ]


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)
}


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


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)


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


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


   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│
└──────┴───┘


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);
    }
}


V rd = [‘22’, ‘333’, ‘4444’, ‘55555’, ‘666666’, ‘7777777’, ‘88888888’, ‘999999999’]

L(ii) 2..7
   print(‘First 10 super-#. numbers:’.format(ii))
   V count = 0

   BigInt j = 3
   L
      V k = ii * j^ii
      I rd[ii - 2] C String(k)
         count++
         print(j, end' ‘ ’)
         I count == 10
            print("\n")
            L.break
      j++


// 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));


# 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));


A = ["John", "Bob", "Mary", "Serena"]
B = ["Jim", "Mary", "John", "Bob"]
@show A B symdiff(A, B)


using System;
using System.Collections.Generic;
using BI = System.Numerics.BigInteger;
using lbi = System.Collections.Generic.List<System.Numerics.BigInteger[]>;
using static System.Console;

class Program {

    // provides 320 bits (90 decimal digits)
    struct LI { public UInt64 lo, ml, mh, hi, tp; }

    const UInt64 Lm = 1_000_000_000_000_000_000UL;
    const string Fm = "D18";

    static void inc(ref LI d, LI s) { // d += s
        d.lo += s.lo; while (d.lo >= Lm) { d.ml++; d.lo -= Lm; }
        d.ml += s.ml; while (d.ml >= Lm) { d.mh++; d.ml -= Lm; }
        d.mh += s.mh; while (d.mh >= Lm) { d.hi++; d.mh -= Lm; }
        d.hi += s.hi; while (d.hi >= Lm) { d.tp++; d.hi -= Lm; }
        d.tp += s.tp;
    }

    static void set(ref LI d, UInt64 s) { // d = s
        d.lo = s; d.ml = d.mh = d.hi = d.tp = 0;
    }

    const int ls = 10;

    static lbi co = new lbi { new BI[] { 0 } }; // for BigInteger addition
    static List<LI[]> Co = new List<LI[]> { new LI[1] }; // for UInt64 addition

    static Int64 ipow(Int64 bas, Int64 exp) { // Math.Pow()
        Int64 res = 1; while (exp != 0) {
            if ((exp & 1) != 0) res *= bas; exp >>= 1; bas *= bas;
        }
        return res;
    }

    // finishes up, shows performance value
    static void fin() { WriteLine("{0}s", (DateTime.Now - st).TotalSeconds.ToString().Substring(0, 5)); }

    static void funM(int d) { // straightforward BigInteger method, medium performance
        string s = new string(d.ToString()[0], d); Write("{0}: ", d);
        for (int i = 0, c = 0; c < ls; i++)
            if ((BI.Pow((BI)i, d) * d).ToString().Contains(s))
                Write("{0} ", i, ++c);
        fin();
    }

    static void funS(int d) { // BigInteger "mostly adding" method, low performance
        BI[] m = co[d];
        string s = new string(d.ToString()[0], d); Write("{0}: ", d);
        for (int i = 0, c = 0; c < ls; i++) {
            if ((d * m[0]).ToString().Contains(s))
                Write("{0} ", i, ++c);
            for (int j = d, k = d - 1; j > 0; j = k--) m[k] += m[j];
        }
        fin();
    }

    static string scale(uint s, ref LI x) { // performs a small multiply and returns a string value
        ulong Lo = x.lo * s, Ml = x.ml * s, Mh = x.mh * s, Hi = x.hi * s, Tp = x.tp * s;
        while (Lo >= Lm) { Lo -= Lm; Ml++; }
        while (Ml >= Lm) { Ml -= Lm; Mh++; }
        while (Mh >= Lm) { Mh -= Lm; Hi++; }
        while (Hi >= Lm) { Hi -= Lm; Tp++; }
        if (Tp > 0) return Tp.ToString() + Hi.ToString(Fm) + Mh.ToString(Fm) + Ml.ToString(Fm) + Lo.ToString(Fm);
        if (Hi > 0) return Hi.ToString() + Mh.ToString(Fm) + Ml.ToString(Fm) + Lo.ToString(Fm);
        if (Mh > 0) return Mh.ToString() + Ml.ToString(Fm) + Lo.ToString(Fm);
        if (Ml > 0) return Ml.ToString() + Lo.ToString(Fm);
        return Lo.ToString();
    }

    static void funF(int d) { // structure of UInt64 method, high performance
        LI[] m = Co[d];
        string s = new string(d.ToString()[0], d); Write("{0}: ", d);
        for (int i = d, c = 0; c < ls; i++) {
            if (scale((uint)d, ref m[0]).Contains(s))
                Write("{0} ", i, ++c);
            for (int j = d, k = d - 1; j > 0; j = k--)
                inc(ref m[k], m[j]);
        }
        fin();
    }

    static void init() { // initializes co and Co
        for (int v = 1; v < 10; v++) {
            BI[] res = new BI[v + 1];
            long[] f = new long[v + 1], l = new long[v + 1];
            for (int j = 0; j <= v; j++) {
                if (j == v) {
                    LI[] t = new LI[v + 1];
                    for (int y = 0; y <= v; y++) set(ref t[y], (UInt64)f[y]);
                    Co.Add(t);
                }
                res[j] = f[j];
                l[0] = f[0]; f[0] = ipow(j + 1, v);
                for (int a = 0, b = 1; b <= v; a = b++) {
                    l[b] = f[b]; f[b] = f[a] - l[a];
                }
            }
            for (int z = res.Length - 2; z > 0; z -= 2) res[z] *= -1;
            co.Add(res);
        }
    }

    static DateTime st;

    static void doOne(string title, int top, Action<int> func) {
        WriteLine('\n' + title); st = DateTime.Now;
        for (int i = 2; i <= top; i++) func(i);
    }

    static void Main(string[] args)
    {
        init(); const int top = 9;
        doOne("BigInteger mostly addition:", top, funS);
        doOne("BigInteger.Pow():", top, funM);
        doOne("UInt64 structure mostly addition:", top, funF);
    }
}


  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")


// 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")
}


#!/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}"


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <gmp.h>

int main() {
    for (unsigned int d = 2; d <= 9; ++d) {
        printf("First 10 super-%u numbers:\n", d);
        char digits[16] = { 0 };
        memset(digits, '0' + d, d);
        mpz_t bignum;
        mpz_init(bignum);
        for (unsigned int count = 0, n = 1; count < 10; ++n) {
            mpz_ui_pow_ui(bignum, n, d);
            mpz_mul_ui(bignum, bignum, d);
            char* str = mpz_get_str(NULL, 10, bignum);
            if (strstr(str, digits)) {
                printf("%u ", n);
                ++count;
            }
            free(str);
        }
        mpz_clear(bignum);
        printf("\n");
    }
    return 0;
}


#include <iostream>
#include <sstream>
#include <vector>

uint64_t ipow(uint64_t base, uint64_t exp) {
    uint64_t result = 1;
    while (exp) {
        if (exp & 1) {
            result *= base;
        }
        exp >>= 1;
        base *= base;
    }
    return result;
}

int main() {
    using namespace std;

    vector<string> rd{ "22", "333", "4444", "55555", "666666", "7777777", "88888888", "999999999" };

    for (uint64_t ii = 2; ii < 5; ii++) {
        cout << "First 10 super-" << ii << " numbers:\n";
        int count = 0;

        for (uint64_t j = 3; /* empty */; j++) {
            auto k = ii * ipow(j, ii);
            auto kstr = to_string(k);
            auto needle = rd[(size_t)(ii - 2)];
            auto res = kstr.find(needle);
            if (res != string::npos) {
                count++;
                cout << j << ' ';
                if (count == 10) {
                    cout << "\n\n";
                    break;
                }
            }
        }
    }

    return 0;
}


[
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 ) );

]


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]


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


(defn super [d]
  (let [run (apply str (repeat d (str d)))]
   (filter #(clojure.string/includes? (str (* d (Math/pow % d ))) run) (range))))

(doseq [d (range 2 9)]
    (println (str d ": ") (take 10 (super d))))


import std.bigint;
import std.conv;
import std.stdio;
import std.string;

void main() {
    auto rd = ["22", "333", "4444", "55555", "666666", "7777777", "88888888", "999999999"];
    BigInt one = 1;
    BigInt nine = 9;

    for (int ii = 2; ii <= 9; ii++) {
        writefln("First 10 super-%d numbers:", ii);
        auto count = 0;

        inner:
        for (BigInt j = 3; ; j++) {
            auto k = ii * j ^^ ii;
            auto ix = k.to!string.indexOf(rd[ii-2]);
            if (ix >= 0) {
                count++;
                write(j, ' ');
                if (count == 10) {
                    writeln();
                    writeln();
                    break inner;
                }
            }
        }
    }
}


A := {John, Bob, Mary, Serena};
B := {Jim, Mary, John, Bob};


// Generate Super-N numbers. Nigel Galloway: October 12th., 2019
let superD N=
  let      I=bigint(pown 10 N)
  let      G=bigint N
  let      E=G*(111111111I%I)
  let rec fL n=match (E-n%I).IsZero with true->true |_->if (E*10I)<n then false else fL (n/10I)
  seq{1I..999999999999999999I}|>Seq.choose(fun n->if fL (G*n**N) then Some n else None)


USING: arrays formatting io kernel lists lists.lazy math
math.functions math.ranges math.text.utils prettyprint sequences
;
IN: rosetta-code.super-d

: super-d? ( seq n d -- ? ) tuck ^ * 1 digit-groups subseq? ;

: super-d ( d -- list )
    [ dup <array> ] [ drop 1 lfrom ] [ ] tri [ super-d? ] curry
    with lfilter ;

: super-d-demo ( -- )
    10 2 6 [a,b] [
        dup "First 10 super-%d numbers:\n" printf
        super-d ltake list>array [ pprint bl ] each nl nl
    ] with each ;

MAIN: super-d-demo


package main

import (
    "fmt"
    "math/big"
    "strings"
    "time"
)

func main() {
    start := time.Now()
    rd := []string{"22", "333", "4444", "55555", "666666", "7777777", "88888888", "999999999"}
    one := big.NewInt(1)
    nine := big.NewInt(9)
    for i := big.NewInt(2); i.Cmp(nine) <= 0; i.Add(i, one) {
        fmt.Printf("First 10 super-%d numbers:\n", i)
        ii := i.Uint64()
        k := new(big.Int)
        count := 0
    inner:
        for j := big.NewInt(3); ; j.Add(j, one) {
            k.Exp(j, i, nil)
            k.Mul(i, k)
            ix := strings.Index(k.String(), rd[ii-2])
            if ix >= 0 {
                count++
                fmt.Printf("%d ", j)
                if count == 10 {
                    fmt.Printf("\nfound in %d ms\n\n", time.Since(start).Milliseconds())
                    break inner
                }
            }
        }
    }
}


/* builtin */
symmdifference({"John", "Bob", "Mary", "Serena"},
               {"Jim", "Mary", "John", "Bob"});
{"Jim", "Serena"}


:- 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).


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


import Data.List (isInfixOf)
import Data.Char (intToDigit)

isSuperd :: (Show a, Integral a) => a -> a -> Bool
isSuperd p n =
  (replicate <*> intToDigit) (fromIntegral p) `isInfixOf` show (p * n ^ p)

findSuperd :: (Show a, Integral a) => a -> [a]
findSuperd p = filter (isSuperd p) [1 ..]

main :: IO ()
main =
  mapM_
    (putStrLn .
     ("First 10 super-" ++) .
     ((++) . show <*> ((" : " ++) . show . take 10 . findSuperd)))
    [2 .. 6]


#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;
}


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)


import java.math.BigInteger;

public class SuperDNumbers {

    public static void main(String[] args) {
        for ( int i = 2 ; i <= 9 ; i++ ) {
            superD(i, 10);
        }
    }

    private static final void superD(int d, int max) {
        long start = System.currentTimeMillis();
        String test = "";
        for ( int i = 0 ; i < d ; i++ ) {
            test += (""+d);
        }

        int n = 0;
        int i = 0;
        System.out.printf("First %d super-%d numbers: %n", max, d);
        while ( n < max ) {
            i++;
            BigInteger val = BigInteger.valueOf(d).multiply(BigInteger.valueOf(i).pow(d));
            if ( val.toString().contains(test) ) {
                n++;
                System.out.printf("%d ", i);
            }
        }
        long end = System.currentTimeMillis();
        System.out.printf("%nRun time %d ms%n%n", end-start);

    }

}


# To take advantage of gojq's arbitrary-precision integer arithmetic:
def power($b): . as $in | reduce range(0;$b) as $i (1; . * $in);

# Input is $d, the number of consecutive digits, 2 <= $d <= 9
# $max is the number of superd numbers to be emitted.
def superd($number):
  . as $d
  | tostring as $s
  | ($s * $d) as $target
  | {count:0, j: 3 }
  |  while ( .count <= $number;
        .emit = null
        | if ((.j|power($d) * $d) | tostring) | index($target)
          then .count += 1
          | .emit = .j
	  else .
          end
        | .j += 1 )
   | select(.emit).emit ;

# super-d for 2 <=d < 8
range(2; 8)
| "First 10 super-\(.) numbers:",
   superd(10)


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


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]}}}


function superd(N)
    println("First 10 super-$N numbers:")
    count, j = 0, BigInt(3)
    target = Char('0' + N)^N
    while count < 10
        if occursin(target, string(j^N * N))
            count += 1
            print("$j ")
        end
        j += 1
    end
    println()
end

for n in 2:9
    @time superd(n)
end


import java.math.BigInteger

fun superD(d: Int, max: Int) {
    val start = System.currentTimeMillis()
    var test = ""
    for (i in 0 until d) {
        test += d
    }

    var n = 0
    var i = 0
    println("First $max super-$d numbers:")
    while (n < max) {
        i++
        val value: Any = BigInteger.valueOf(d.toLong()) * BigInteger.valueOf(i.toLong()).pow(d)
        if (value.toString().contains(test)) {
            n++
            print("$i ")
        }
    }
    val end = System.currentTimeMillis()
    println("\nRun time ${end - start} ms\n")
}

fun main() {
    for (i in 2..9) {
        superD(i, 10)
    }
}


for d = 2, 5 do
  local n, found = 0, {}
  local dds = string.rep(d, d)
  while #found < 10 do
    local dnd = string.format("%15.f", d * n ^ d)
    if string.find(dnd, dds) then found[#found+1] = n end
    n = n + 1
  end
  print("super-" .. d .. ":  " .. table.concat(found,", "))
end


ClearAll[SuperD]
SuperD[d_, m_] := Module[{n, res, num},
  res = {};
  n = 1;
  While[Length[res] < m,
   num = IntegerDigits[d n^d];
   If[MatchQ[num, {___, Repeated[d, {d}], ___}],
    AppendTo[res, n]
    ];
   n++;
   ];
  res
  ]
Scan[Print[SuperD[#, 10]] &, Range[2, 6]]


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"])


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.


import sequtils, strutils, times
import bignum

iterator superDNumbers(d, maxCount: Positive): Natural =
  var count = 0
  var n = 2
  let e = culong(d)   # Bignum ^ requires a culong as exponent.
  let pattern = repeat(chr(d + ord('0')), d)
  while count != maxCount:
    if pattern in $(d * n ^ e):
      yield n
      inc count
    inc n, 1

let t0 = getTime()
for d in 2..9:
  echo "First 10 super-$# numbers:".format(d)
  echo toSeq(superDNumbers(d, 10)).join(" ")
echo "Time: ", getTime() - t0


program Super_D;
uses
  sysutils,gmp;

var
  s :ansistring;
  s_comp : ansistring;
  test : mpz_t;
  i,j,dgt,cnt : NativeUint;
Begin
  mpz_init(test);

  for dgt := 2 to 9 do
  Begin
    //create '22' to '999999999'
    i := dgt;
    For j := 2 to dgt do
      i := i*10+dgt;
    s_comp := IntToStr(i);
    writeln('Finding ',s_comp,' in ',dgt,'*i**',dgt);

    i := dgt;
    cnt := 0;
    repeat
      mpz_ui_pow_ui(test,i,dgt);
      mpz_mul_ui(test,test,dgt);
      setlength(s,mpz_sizeinbase(test,10));
      mpz_get_str(pChar(s),10,test);
      IF Pos(s_comp,s) <> 0 then
      Begin
        write(i,' ');
        inc(cnt);
      end;
      inc(i);
    until cnt = 10;
    writeln;
  end;
  mpz_clear(test);
End.


use strict;
use warnings;
use bigint;
use feature 'say';

sub super {
    my $d = shift;
    my $run = $d x $d;
    my @super;
    my $i = 0;
    my $n = 0;
    while ( $i < 10 ) {
        if (index($n ** $d * $d, $run) > -1) {
            push @super, $n;
            ++$i;
        }
        ++$n;
    }
    @super;
}

say "\nFirst 10 super-$_ numbers:\n", join ' ', super($_) for 2..6;


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";


function Union(sequence a, sequence b)
    for i=1 to length(a) do
        if not find(a[i],b) then
            b = append(b,a[i])
        end if
    end for
    return b
end function

function Difference(sequence a, sequence b)
sequence res = {}
    for i=1 to length(a) do
        if not find(a[i],b)
        and not find(a[i],res) then
            res = append(res,a[i])
        end if
    end for
    return res
end function

function Symmetric_Difference(sequence a, sequence b)
    return Union(Difference(a, b), Difference(b, a))
end function

sequence a = {"John", "Serena", "Bob", "Mary", "Serena"},
         b = {"Jim", "Mary", "John", "Jim", "Bob"}
?Symmetric_Difference(a,a)
?Symmetric_Difference(a,b)
?Symmetric_Difference(b,a)
?Symmetric_Difference(b,b)


with javascript_semantics
include mpfr.e

procedure main()
    atom t0 = time()
    mpz k = mpz_init()
    for i=2 to iff(platform()=JS?7:9) do
        printf(1,"First 10 super-%d numbers:\n", i)
        integer count := 0, j = 3
        string tgt = repeat('0'+i,i)
        while count<10 do
            mpz_ui_pow_ui(k,j,i)
            mpz_mul_si(k,k,i)
            string s = mpz_get_str(k)
            integer ix = match(tgt,s)
            if ix then
                count += 1
                printf(1,"%d ", j)
            end if
            j += 1
        end while
        printf(1,"\nfound in %s\n\n", {elapsed(time()-t0)})
    end for
end procedure
main()


from itertools import islice, count

def superd(d):
    if d != int(d) or not 2 <= d <= 9:
        raise ValueError("argument must be integer from 2 to 9 inclusive")
    tofind = str(d) * d
    for n in count(2):
        if tofind in str(d * n ** d):
            yield n

if __name__ == '__main__':
    for d in range(2, 9):
        print(f"{d}:", ', '.join(str(n) for n in islice(superd(d), 10)))


library(Rmpfr)
options(scipen = 999)

find_super_d_number <- function(d, N = 10){

  super_number <- c(NA)
  n = 0
  n_found = 0

  while(length(super_number) < N){

    n = n + 1
    test = d * mpfr(n, precBits = 200) ** d   #Here I augment precision
    test_formatted = .mpfr2str(test)$str      #and I extract the string from S4 class object

    iterable = strsplit(test_formatted, "")[[1]]

    if (length(iterable) < d) next

    for(i in d:length(iterable)){
      if (iterable[i] != d) next
      equalities = 0

      for(j in 1:d) {
        if (i == j) break

        if(iterable[i] == iterable[i-j])
          equalities = equalities + 1
        else break
      }

      if (equalities >= (d-1)) {
        n_found = n_found + 1
        super_number[n_found] = n
        break
      }
    }
  }

  message(paste0("First ", N, " super-", d, " numbers:"))
  print((super_number))

  return(super_number)
}

for(d in 2:6){find_super_d_number(d, N = 10)}


<?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";
?>


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)).


sub super (\d) {
    my \run = d x d;
    ^∞ .hyper.grep: -> \n { (d * n ** d).Str.contains: run }
}

(2..9).race(:1batch).map: {
    my $now = now;
    put "\nFirst 10 super-$_ numbers:\n{.&super[^10]}\n{(now - $now).round(.1)} sec."
}


/*REXX program computes and displays the first  N  super─d  numbers for D from LO to HI.*/
numeric digits 100                               /*ensure enough decimal digs for calc. */
parse arg n LO HI .                              /*obtain optional arguments from the CL*/
if  n=='' |  n==","  then  n= 10                 /*the number of super─d numbers to calc*/
if LO=='' | LO==","  then LO=  2                 /*low  end of  D  for the super─d nums.*/
if HI=='' | HI==","  then HI=  9                 /*high  "   "  "   "   "     "      "  */
                                                 /* [↓]   process  D  from  LO ──►  HI. */
     do d=LO  to HI;     #= 0;     $=            /*count & list of super─d nums (so far)*/
     z= copies(d, d)                             /*the string that is being searched for*/
           do j=2  until #==n                    /*search for super─d numbers 'til found*/
           if pos(z, d * j**d)==0  then iterate  /*does product have the required reps? */
           #= # + 1;               $= $ j        /*bump counter;  add the number to list*/
           end   /*j*/
     say
     say center(' the first '     n     " super-"d 'numbers ',  digits(),  "═")
     say $
     end   /*d*/                                 /*stick a fork in it,  we're all done. */


(2..8).each do |d|
  rep = d.to_s * d
  print "#{d}: "
  puts (2..).lazy.select{|n| (d * n**d).to_s.include?(rep) }.first(10).join(", ")
end


// [dependencies]
// rug = "1.9"

fn print_super_d_numbers(d: u32, limit: u32) {
    use rug::Assign;
    use rug::Integer;

    println!("First {} super-{} numbers:", limit, d);
    let digits = d.to_string().repeat(d as usize);
    let mut count = 0;
    let mut n = 1;
    let mut s = Integer::new();
    while count < limit {
        s.assign(Integer::u_pow_u(n, d));
        s *= d;
        if s.to_string().contains(&digits) {
            print!("{} ", n);
            count += 1;
        }
        n += 1;
    }
    println!();
}

fn main() {
    for d in 2..=9 {
        print_super_d_numbers(d, 10);
    }
}


(de symdiff (A B)
   (uniq (conc (diff A B) (diff B A))) )


> 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" >)


func super_d(d) {
    var D = Str(d)*d
    1..Inf -> lazy.grep {|n| Str(d * n**d).contains(D) }
}

for d in (2..8) {
    say ("#{d}: ", super_d(d).first(10))
}


import BigInt
import Foundation

let rd = ["22", "333", "4444", "55555", "666666", "7777777", "88888888", "999999999"]

for d in 2...9 {
  print("First 10 super-\(d) numbers:")

  var count = 0
  var n = BigInt(3)
  var k = BigInt(0)

  while true {
    k = n.power(d)
    k *= BigInt(d)

    if let _ = String(k).range(of: rd[d - 2]) {
      count += 1

      print(n, terminator: " ")
      fflush(stdout)

      guard count < 10 else {
        break
      }
    }

    n += 1
  }

  print()
  print()
}


Imports System.Numerics

Module Module1

    Sub Main()
        Dim rd = {"22", "333", "4444", "55555", "666666", "7777777", "88888888", "999999999"}
        Dim one As BigInteger = 1
        Dim nine As BigInteger = 9

        For ii = 2 To 9
            Console.WriteLine("First 10 super-{0} numbers:", ii)
            Dim count = 0

            Dim j As BigInteger = 3
            While True
                Dim k = ii * BigInteger.Pow(j, ii)
                Dim ix = k.ToString.IndexOf(rd(ii - 2))
                If ix >= 0 Then
                    count += 1
                    Console.Write("{0} ", j)
                    If count = 10 Then
                        Console.WriteLine()
                        Console.WriteLine()
                        Exit While
                    End If
                End If

                j += 1
            End While
        Next
    End Sub

End Module


$A = @( "John"
        "Bob"
        "Mary"
        "Serena" )

$B = @( "Jim"
        "Mary"
        "John"
        "Bob" )

#  Full commandlet name and full parameter names
Compare-Object -ReferenceObject $A -DifferenceObject $B

#  Same commandlet using an alias and positional parameters
Compare $A $B

#  A - B
Compare $A $B | Where SideIndicator -eq "<=" | Select -ExpandProperty InputObject

#  B - A
Compare $A $B | Where SideIndicator -eq "=>" | Select -ExpandProperty InputObject


sym_diff :-
    A = ['John', 'Serena', 'Bob', 'Mary', 'Serena'],
    B = ['Jim', 'Mary', 'John', 'Jim', 'Bob'],
    format('A : ~w~n', [A]),
    format('B : ~w~n', [B]),
    list_to_set(A, SA),
    list_to_set(B, SB),
    format('set from A : ~w~n', [SA]),
    format('set from B : ~w~n', [SB]),
    subtract(SA, SB, DAB),
    format('difference A\\B : ~w~n', [DAB]),
    subtract(SB, SA, DBA),
    format('difference B\\A : ~w~n', [DBA]),
    union(DAB, DBA, Diff),
    format('symetric difference : ~w~n', [Diff]).


import "/big" for BigInt
import "/fmt" for Fmt

var start = System.clock
var rd = ["22", "333", "4444", "55555", "666666", "7777777", "88888888"]
for (i in 2..8) {
    Fmt.print("First 10 super-$d numbers:", i)
    var count = 0
    var j = BigInt.three
    while (true) {
        var k = j.pow(i) * i
        var ix = k.toString.indexOf(rd[i-2])
        if (ix >= 0) {
            count = count + 1
            Fmt.write("$i ", j)
            if (count == 10) {
                Fmt.print("\nfound in $f seconds\n", System.clock - start)
                break
            }
        }
        j = j.inc
    }
}


var [const] BI=Import("zklBigNum");  // libGMP

fcn superDW(d){
   digits:=d.toString()*d;
   [2..].tweak('wrap(n)
      { BI(n).pow(d).mul(d).toString().holds(digits) and n or Void.Skip });
}
foreach d in ([2..8]){ println(d," : ",superDW(d).walk(10).concat(" ")) }


Dim A.s(3)
Dim B.s(3)

A(0)="John": A(1)="Bob": A(2)="Mary": A(3)="Serena"
B(0)="Jim":  B(1)="Mary":B(2)="John": B(3)="Bob"

For a=0 To ArraySize(A())    ; A-B
  For b=0 To ArraySize(B())
    If A(a)=B(b)
      Break
    ElseIf b=ArraySize(B())
      Debug A(a)
    EndIf
  Next b
Next a

For b=0 To ArraySize(B())     ; B-A
  For a=0 To ArraySize(A())
    If A(a)=B(b)
      Break
    ElseIf a=ArraySize(A())
      Debug B(b)
    EndIf
  Next a
Next b


>>> setA = {"John", "Bob", "Mary", "Serena"}
>>> setB = {"Jim", "Mary", "John", "Bob"}
>>> setA ^ setB # symmetric difference of A and B
{'Jim', 'Serena'}
>>> setA - setB # elements in A that are not in B
{'Serena'}
>>> setB - setA # elements in B that are not in A
{'Jim'}
>>> setA | setB # elements in A or B (union)
{'John', 'Bob', 'Jim', 'Serena', 'Mary'}
>>> setA & setB # elements in both A and B (intersection)
{'Bob', 'John', 'Mary'}


  [ $ "rosetta/bitwisesets.qky" loadfile ] now!

( i.e. using the Quackery code for sets at
  http://rosettacode.org/wiki/Set#Indexed_Bitmaps )

  set{ John Bob Mary Serena }set is A ( --> { )

  set{ Jim Mary John Bob }set    is B ( --> { )

  say "A \ B is " A B difference echoset cr

  say "B \ A is " B A difference echoset cr

  say "(A \ B) U (B \ A) is "
  A B difference B A difference union echoset cr

  say "(A U B) \ (A n B) is "
  A B union A B intersection difference echoset cr

  say "Using built-in symmetric difference: "
  A B symmdiff echoset cr


a <- c( "John", "Bob", "Mary", "Serena" )
b <- c( "Jim", "Mary", "John", "Bob" )
c(setdiff(b, a), setdiff(a, b))

a <- c("John", "Serena", "Bob", "Mary", "Serena")
b <- c("Jim", "Mary", "John", "Jim", "Bob")
c(setdiff(b, a), setdiff(a, b))


#lang racket
(define A (set "John" "Bob" "Mary" "Serena"))
(define B (set "Jim" "Mary" "John" "Bob"))

(set-symmetric-difference A B)
(set-subtract A B)
(set-subtract B A)


my \A = set <John Serena Bob Mary Serena>;
my \B = set <Jim Mary John Jim Bob>;

say  A ∖ B; # Set subtraction
say  B ∖ A; # Set subtraction
say (A ∪ B) ∖ (A ∩ B);  # Symmetric difference, via basic set operations
say  A ⊖ B;             # Symmetric difference, via dedicated operator


a: [John Serena Bob Mary Serena]
b: [Jim Mary John Jim Bob]
difference a b


/*REXX program finds  symmetric difference  and  symmetric AND  (between two lists).    */
a= '["John", "Serena", "Bob", "Mary", "Serena"]' /*note the duplicate element:  Serena  */
b= '["Jim", "Mary", "John", "Jim", "Bob"]'       /*  "   "       "       "      Jim     */
a.=0;   SD.=0;   SA.=0;    SD=;     SA=          /*falsify booleans; zero & nullify vars*/
a.1=a;         say '──────────────list A ='  a   /*assign a list and display it to term.*/
a.2=b;         say '──────────────list B ='  b   /*   "   "   "   "     "     "  "   "  */
                                                 /* [↓]  parse the two lists.           */
    do k=1  for 2                                /*process both lists  (stemmed array). */
    a.k=strip( strip(a.k, , "["), ,']')          /*strip leading and trailing brackets. */
               do j=1  until a.k=''              /*parse names  [they may have blanks]. */
               a.k=strip(a.k, , ',')             /*strip all commas (if there are any). */
               parse var  a.k   '"'  _  '"'  a.k /*obtain the name of the list.         */
               a.k.j=_                           /*store the name of the list.          */
               a.k._=1                           /*make a boolean value.                */
               end   /*j*/
    a.k.0=j-1                                    /*the number of this list  (of names). */
    end              /*k*/
say                                              /* [↓]  find the symmetric difference. */
    do k=1  for 2;             ko=word(2 1, k)   /*process both lists;   KO=other list. */
      do j=1  for a.k.0;       _=a.k.j           /*process the list names.              */
      if \a.ko._ & \SD._  then do;   SD._=1      /*if not in both, then  ···            */
                               SD=SD  '"'_'",'   /*add to symmetric difference list.    */
                               end
      end   /*j*/
    end     /*k*/
                                                 /* [↓]  SD ≡  symmetric difference.    */
SD= "["strip( strip(SD), 'T', ",")']'            /*clean up and add brackets [ ]  to it.*/
say 'symmetric difference ='   SD                /*display the symmetric difference.    */
                                                 /* [↓]  locate the symmetric AND.      */
   do j=1  for a.1.0;     _=a.1.j                /*process the   A   list names.        */
   if a.1._ & a.2._ & \SA._  then do;   SA._=1   /*if it's common to both, then  ···    */
                                  SA=SA '"'_'",' /*add to symmetric AND  list.          */
                                  end
   end   /*j*/
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. */


alist = []
blist = []
alist = ["john", "bob", "mary", "serena"]
blist = ["jim", "mary", "john", "bob"]

alist2 = []
for i = 1 to len(alist)
    flag = 0
    for j = 1 to len(blist)
        if alist[i] = blist[j]  flag = 1 ok
    next
    if (flag = 0) add(alist2, alist[i]) ok
next

blist2 = []
for j = 1 to len(alist)
    flag = 0
    for i = 1 to len(blist)
        if alist[i] = blist[j]  flag = 1 ok
    next
    if (flag = 0) add(blist2, blist[j]) ok
next
see "a xor b :" see nl
see alist2
see blist2 see nl
see "a-b :" see nl
see alist2 see nl
see "b-a :" see nl
see blist2 see nl


a = ["John", "Serena", "Bob", "Mary", "Serena"]
b = ["Jim", "Mary", "John", "Jim", "Bob"]
# the union minus the intersection:
p sym_diff = (a | b)-(a & b)  # => ["Serena", "Jim"]


setA$ = "John,Bob,Mary,Serena"
setB$ = "Jim,Mary,John,Bob"

x$ = b$(setA$,setB$)
print word$(x$,1,",")
c$ = c$ + x$

x$ = b$(setB$,setA$)
print word$(x$,1,",")
print c$;x$
end
function b$(a$,b$)
 i = 1
 while word$(a$,i,",") <> ""
  a1$ = word$(a$,i,",")
  j   = instr(b$,a1$)
  if j <> 0 then b$ = left$(b$,j-1) + mid$(b$,j+len(a1$)+1)
  i   = i + 1
wend
end function


use std::collections::HashSet;

fn main() {
    let a: HashSet<_> = ["John", "Bob", "Mary", "Serena"]
        .iter()
        .collect();
    let b = ["Jim", "Mary", "John", "Bob"]
        .iter()
        .collect();

    let diff = a.symmetric_difference(&b);
    println!("{:?}", diff);
}


scala> val s1 = Set("John", "Serena", "Bob", "Mary", "Serena")
s1: scala.collection.immutable.Set[java.lang.String] = Set(John, Serena, Bob, Mary)

scala> val s2 = Set("Jim", "Mary", "John", "Jim", "Bob")
s2: scala.collection.immutable.Set[java.lang.String] = Set(Jim, Mary, John, Bob)

scala> (s1 diff s2) union (s2 diff s1)
res46: scala.collection.immutable.Set[java.lang.String] = Set(Serena, Jim)


with Ada.Calendar; use Ada.Calendar;
with Ada.Calendar.Formatting; use Ada.Calendar.Formatting;
with Ada.Calendar.Time_Zones; use Ada.Calendar.Time_Zones;
with Ada.Text_Io; use Ada.Text_Io;

procedure System_Time is
   Now : Time := Clock;
begin
   Put_line(Image(Date => Now, Time_Zone => -7*60));
end System_Time;


(import (scheme base)
        (scheme write))

;; -- given two sets represented as lists, return (A \ B)
(define (a-without-b a b)
  (cond ((null? a)
         '())
        ((member (car a) (cdr a)) ; drop head of a if it's a duplicate
         (a-without-b (cdr a) b))
        ((member (car a) b) ; head of a is in b so drop it
         (a-without-b (cdr a) b))
        (else ; head of a not in b, so keep it
          (cons (car a) (a-without-b (cdr a) b)))))

;; -- given two sets represented as lists, return symmetric difference
(define (symmetric-difference a b)
  (append (a-without-b a b)
          (a-without-b b a)))

;; -- test case
(define A '(John Bob Mary Serena))
(define B '(Jim Mary John Bob))

(display "A\\B: ") (display (a-without-b A B)) (newline)
(display "B\\A: ") (display (a-without-b B A)) (newline)
(display "Symmetric difference: ") (display (symmetric-difference A B)) (newline)
;; -- extra test as we are using lists
(display "Symmetric difference 2: ")
(display (symmetric-difference '(John Serena Bob Mary Serena)
                               '(Jim Mary John Jim Bob))) (newline)


$ include "seed7_05.s7i";

const type: striSet is set of string;

enable_output(striSet);

const proc: main is func
  local
    const striSet: setA is {"John", "Bob" , "Mary", "Serena"};
    const striSet: setB is {"Jim" , "Mary", "John", "Bob"   };
  begin
    writeln(setA >< setB);
  end func;


date d;

d_now(d);

o_form("~-/f2/-/f2/ /f2/:/f2/:/f2/\n", d_year(d), d_y_month(d), d_m_day(d),
       d_d_hour(d), d_h_minute(d), d_m_second(d));


FORMAT time repr = $"year="4d,", month="2d,", day="2d,", hours="2d,",  \
                   minutes="2d,", seconds="2d,", day of week="d,",  \
                   daylight-saving-time flag="dl$;
printf((time repr, local time));
printf((time repr, utc time))


var a = ["John", "Serena", "Bob", "Mary", "Serena"];
var b = ["Jim", "Mary", "John", "Jim", "Bob"];
a ^ b -> unique.dump.say;


|A B|
A := Set new.
B := Set new.
A addAll: #( 'John' 'Bob' 'Mary' 'Serena' ).
B addAll: #( 'Jim' 'Mary' 'John' 'Bob' ).

( (A - B) + (B - A) ) displayNl.


CREATE OR REPLACE FUNCTION arrxor(anyarray,anyarray) RETURNS anyarray AS $$
SELECT ARRAY(
        (
        SELECT r.elements
        FROM    (
                (SELECT 1,unnest($1))
                UNION ALL
                (SELECT 2,unnest($2))
                ) AS r (arr, elements)
        GROUP BY 1
        HAVING MIN(arr) = MAX(arr)
        )
)
$$ LANGUAGE SQL strict immutable;


/* ARM assembly Raspberry PI  */
/*  program sysTime.s   */

/* REMARK 1 : this program use routines in a include file
   see task Include a file language arm assembly
   for the routine affichageMess conversion10
   see at end of this program the instruction include */

/*******************************************/
/* Constantes                              */
/*******************************************/
.equ STDOUT, 1           @ Linux output console
.equ EXIT,   1           @ Linux syscall
.equ WRITE,  4           @ Linux syscall
.equ BRK,    0x2d        @ Linux syscall
.equ CHARPOS,     '@'

.equ GETTIME,   0x4e     @ call system linux gettimeofday

/*******************************************/
/* Structures                               */
/********************************************/
/* example structure  time  */
    .struct  0
timeval_sec:                     @
    .struct  timeval_sec + 4
timeval_usec:                     @
    .struct  timeval_usec + 4
timeval_end:
    .struct  0
timezone_min:                     @
    .struct  timezone_min + 4
timezone_dsttime:                 @
    .struct  timezone_dsttime + 4
timezone_end:

/*********************************/
/* Initialized data              */
/*********************************/
.data
szMessError:       .asciz "Error detected !!!!. \n"
szMessResult:      .asciz "GMT: @/@/@  @:@:@  @ms\n"  @ message result

szCarriageReturn:  .asciz "\n"
.align 4
tbDayMonthYear:    .int  0,  31,  60,  91, 121, 152, 182, 213, 244, 274, 305, 335
                   .int 366, 397, 425, 456, 486, 517, 547, 578, 609, 639, 670, 700
                   .int 731, 762, 790, 821, 851, 882, 912, 943, 974,1004,1035,1065
                   .int 1096,1127,1155,1186,1216,1247,1277,1308,1339,1369,1400,1430
/*********************************/
/* UnInitialized data            */
/*********************************/
.bss
.align 4
stTVal:                .skip timeval_end
stTZone:               .skip timezone_end
sZoneConv:             .skip 100
/*********************************/
/*  code section                 */
/*********************************/
.text
.global main
main:                              @ entry of program
    ldr r0,iAdrstTVal
    ldr r1,iAdrstTZone
    mov r7,#GETTIME
    svc 0
    cmp r0,#-1                     @ error ?
    beq 99f
    ldr r0,iAdrstTVal
    ldr r1,[r0,#timeval_sec]       @ timestemp in second
    //ldr r1,iTStest1
    //ldr r1,iTStest2
    //ldr r1,iTStest3
    ldr r2,iSecJan2020
    sub r0,r1,r2                   @ total secondes to 01/01/2020
    mov r1,#60
    bl division
    mov r0,r2
    mov r6,r3                      @ compute secondes
    mov r1,#60
    bl division
    mov r7,r3                      @ compute minutes
    mov r0,r2
    mov r1,#24
    bl division
    mov r8,r3                      @ compute hours
    mov r0,r2
    mov r11,r0
    mov r1,#(365 * 4 + 1)
    bl division
    lsl r9,r2,#2                   @ multiply by 4 = year1
    mov r1,#(365 * 4 + 1)
    mov r0,r11
    bl division
    mov r10,r3
    ldr r1,iAdrtbDayMonthYear
    mov r2,#3
    mov r3,#12
1:
    mul r11,r3,r2
    ldr r12,[r1,r11,lsl #2]         @ load days by year
    cmp r10,r12
    bge 2f
    sub r2,r2,#1
    cmp r2,#0
    bne 1b
2:                                 @ r2 = year2
    mov r5,#11
    mul r4,r3,r2
    lsl r4,#2
    add r4,r1
3:
    ldr r12,[r4,r5,lsl #2]         @ load days by month
    cmp r10,r12
    bge 4f
    subs r5,r5,#1
    bne 3b
4:                                 @ r5 = month - 1
    mul r11,r3,r2
    add r11,r5
    ldr r1,iAdrtbDayMonthYear
    ldr r3,[r1,r11,lsl #2]
    sub r0,r10,r3

    add r0,r0,#1                   @ final compute day
    ldr r1,iAdrsZoneConv
    bl conversion10                @ this function do not zero final
    mov r4,#0                      @ store zero final
    strb r4,[r1,r0]
    ldr r0,iAdrszMessResult
    ldr r1,iAdrsZoneConv
    bl strInsertAtCharInc          @ insert result at first @ character
    mov r3,r0
    add r0,r5,#1                   @ final compute month
    ldr r1,iAdrsZoneConv
    bl conversion10
    mov r4,#0                      @ store zero final
    strb r4,[r1,r0]
    mov r0,r3
    ldr r1,iAdrsZoneConv
    bl strInsertAtCharInc          @ insert result at next @ character
    mov r3,r0
    ldr r11,iYearStart
    add r0,r9,r11
    add r0,r0,r2                   @ final compute year = 2020 + year1 + year2
    ldr r1,iAdrsZoneConv
    bl conversion10
    mov r4,#0                      @ store zero final
    strb r4,[r1,r0]
    mov r0,r3
    ldr r1,iAdrsZoneConv
    bl strInsertAtCharInc          @ insert result at next @ character
    mov r3,r0
    mov r0,r8                      @ hours
    ldr r1,iAdrsZoneConv
    bl conversion10
    mov r4,#0                      @ store zero final
    strb r4,[r1,r0]
    mov r0,r3
    ldr r1,iAdrsZoneConv
    bl strInsertAtCharInc          @ insert result at next @ character
    mov r3,r0
    mov r0,r7                      @ minutes
    ldr r1,iAdrsZoneConv
    bl conversion10
    mov r4,#0                      @ store zero final
    strb r4,[r1,r0]
    mov r0,r3
    ldr r1,iAdrsZoneConv
    bl strInsertAtCharInc          @ insert result at next @ character
    mov r3,r0
    mov r0,r6                      @ secondes
    ldr r1,iAdrsZoneConv
    bl conversion10
    mov r4,#0                      @ store zero final
    strb r4,[r1,r0]
    mov r0,r3
    ldr r1,iAdrsZoneConv
    bl strInsertAtCharInc          @ insert result at next @ character
    mov r3,r0
    ldr r1,iAdrstTVal
    ldr r0,[r1,#timeval_usec]      @ millisecondes
    ldr r1,iAdrsZoneConv
    bl conversion10
    mov r4,#0                      @ store zero final
    strb r4,[r1,r0]
    mov r0,r3
    ldr r1,iAdrsZoneConv
    bl strInsertAtCharInc          @ insert result at next @ character
    bl affichageMess
    b 100f
99:
    ldr r0,iAdrszMessError
    bl affichageMess
100:                               @ standard end of the program
    mov r0,#0                      @ return code
    mov r7,#EXIT                   @ request to exit program
    svc 0                          @ perform the system call

iAdrszMessError:          .int szMessError
iAdrstTVal:               .int stTVal
iAdrstTZone:              .int stTZone
iAdrszMessResult:         .int szMessResult
iAdrszCarriageReturn:     .int szCarriageReturn
iAdrsZoneConv:            .int sZoneConv
iSecJan2020:              .int 1577836800
iAdrtbDayMonthYear:       .int tbDayMonthYear
iYearStart:               .int 2020
iTStest1:                 .int 1609508339    @ 01/01/2021
iTStest2:                 .int 1657805939    @ 14/07/2022
iTStest3:                 .int 1767221999    @ 31/12/2025
/***************************************************/
/*      ROUTINES INCLUDE                 */
/***************************************************/
.include "../affichage.inc"


let setA : Set<String> = ["John", "Bob", "Mary", "Serena"]
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


package require struct::set

set A {John Bob Mary Serena}
set B {Jim Mary John Bob}

set AnotB   [struct::set difference $A $B]
set BnotA   [struct::set difference $B $A]
set SymDiff [struct::set union $AnotB $BnotA]

puts "A\\B = $AnotB"
puts "B\\A = $BnotA"
puts "A\u2296B = $SymDiff"

# Of course, the library already has this operation directly...
puts "Direct Check: [struct::set symdiff $A $B]"


$$ MODE TUSCRIPT
a="John'Bob'Mary'Serena"
b="Jim'Mary'John'Bob"

DICT names CREATE

SUBMACRO checknames
!var,val
PRINT val,": ",var
 LOOP n=var
  DICT names APPEND/QUIET n,num,cnt,val;" "
 ENDLOOP
ENDSUBMACRO

CALL checknames (a,"a")
CALL checknames (b,"b")

DICT names UNLOAD names,num,cnt,val

LOOP n=names,v=val
PRINT n," in: ",v
ENDLOOP


time();
time("%a %b %d %H:%M:%S %Z %Y");
//are equivalent ways of returning the current time in the default format used by the UNIX date command.


a = <'John','Bob','Mary','Serena'>
b = <'Jim','Mary','John','Bob'>

#cast %sLm

main =

<
   'a': a,
   'b': b,
   'a not b': ~&j/a b,
   'b not a': ~&j/b a,
   'symmetric difference': ~&jrljTs/a b>


MsgBox(0,"Time", "Year: "&@YEAR&",Day: " &@MDAY& ",Hours: "& @HOUR & ", Minutes: "& @MIN &", Seconds: "& @SEC)


$ awk 'BEGIN{print systime(),strftime()}'


' BaCon time
n = NOW
PRINT n, " seconds since January 1st, 1970"
PRINT YEAR(n), MONTH(n), DAY(n) FORMAT "%04d/%02d/%02d "
PRINT HOUR(n), MINUTE(n), SECOND(n) FORMAT "%02d:%02d:%02d\n"


import "/set" for Set

var symmetricDifference = Fn.new { |a, b| a.except(b).union(b.except(a)) }

var a = Set.new(["John", "Bob", "Mary", "Serena"])
var b = Set.new(["Jim", "Mary", "John", "Bob"])
System.print("A     = %(a)")
System.print("B     = %(b)")
System.print("A - B = %(a.except(b))")
System.print("B - A = %(b.except(a))")
System.print("A △ B = %(symmetricDifference.call(a, b))")


def  John, Bob, Mary, Serena, Jim;   \enumerate set items (0..4)

proc SetOut(S);         \Output the elements in set
int  S;
int  Name, I;
[Name:= ["John", "Bob", "Mary", "Serena", "Jim"];
for I:= 0 to 31 do
    if S & 1<<I then
        [Text(0, Name(I));  ChOut(0, ^ )];
CrLf(0);
];

int A, B;
[A:= 1<<John ! 1<<Bob ! 1<<Mary ! 1<<Serena;
 B:= 1<<Jim ! 1<<Mary ! 1<<John ! 1<<Bob;
Text(0, "A xor B =   ");  SetOut(A | B);
Text(0, "A\B =       ");  SetOut(A & ~B);
Text(0, "B\A =       ");  SetOut(B & ~A);
Text(0, "A\B U B\A = ");  SetOut(A&~B ! B&~A);
]


lista1$ = "John Serena Bob Mary Serena"
lista2$ = "Jim Mary John Jim Bob"

lista1$ = quitadup$(lista1$)
lista2$ = quitadup$(lista2$)
res$ = quitacomun$(lista1$, lista2$)
res$ = res$ + quitacomun$(lista2$, lista1$)
print res$

sub quitadup$(l$)
	l$ = l$ + " "
	return quitarep$(l$)
end sub

sub quitacomun$(l1$, l2$)
	l1$ = l1$ + " "
	l2$ = l2$ + " "
	return quitarep$(l1$, l2$)
end sub

sub quitarep$(l1$, l2$)
	local pos, n, x, listar$, nombre$, largo

	largo = len(l1$)
	pos = 1
	while(true)
		n = instr(l1$, " ", pos)
		if n > 0 then
			nombre$ = mid$(l1$, pos, n-pos)
			if numparams = 1 then
				x = instr(listar$, nombre$)
			else
				x = instr(l2$, nombre$)
			end if
			if x = 0 listar$ = listar$ + nombre$ + " "
			pos = n + 1
		else
			return listar$
		end if
	wend
end sub


print month+1; "-"; day; "-"; year
# returns system date in format: mm-dd-yyyy

print hour; ":"; minute; ":"; second
# returns system time in format: hh:mm:ss


fcn setCommon(list1,list2){ list1.filter(list2.holds); }
fcn sdiff(list1,list2)
   { list1.extend(list2).copy().removeEach(setCommon(list1,list2)) }


#include<time.h>
#include<stdio.h>
#include<stdlib.h>
int main(){
  time_t my_time = time(NULL);
  printf("%s", ctime(&my_time));
  return 0;
}


#include <iostream>
#include <boost/date_time/posix_time/posix_time.hpp>

int main( ) {
   boost::posix_time::ptime t ( boost::posix_time::second_clock::local_time( ) ) ;
   std::cout << to_simple_string( t ) << std::endl ;
   return 0 ;
}


(import '[java.util Date])
; the current system date time string
(print (new Date))
; the system time as milliseconds since 1970
(print (. (new Date) getTime))
; or
(print (System/currentTimeMillis))


start_up = proc ()
    stream$putl(stream$primary_output(), date$unparse(now()))
end start_up


       WORKING-STORAGE SECTION.
       01  WS-CURRENT-DATE-FIELDS.
           05  WS-CURRENT-DATE.
               10  WS-CURRENT-YEAR    PIC  9(4).
               10  WS-CURRENT-MONTH   PIC  9(2).
               10  WS-CURRENT-DAY     PIC  9(2).
           05  WS-CURRENT-TIME.
               10  WS-CURRENT-HOUR    PIC  9(2).
               10  WS-CURRENT-MINUTE  PIC  9(2).
               10  WS-CURRENT-SECOND  PIC  9(2).
               10  WS-CURRENT-MS      PIC  9(2).
           05  WS-DIFF-FROM-GMT       PIC S9(4).

       PROCEDURE DIVISION.
           MOVE FUNCTION CURRENT-DATE TO WS-CURRENT-DATE-FIELDS.


<cfscript>
  // Date Time
  currentTime = Now();
  writeOutput( currentTime );

  // Epoch
  // Credit for Epoch time should go to Ben Nadel
  // bennadel.com is his blog
  utcDate = dateConvert( "local2utc", currentTime );
  writeOutput( utcDate.getTime() );
</cfscript>


(multiple-value-bind (second minute hour day month year) (get-decoded-time)
 	  (format t "~4,'0D-~2,'0D-~2,'0D ~2,'0D:~2,'0D:~2,'0D" year month day hour minute second))


# current time in system's time zone:
Time.local

# current time in UTC
Time.utc

# monotonic time (useful for measuring elapsed time)
Time.monotonic


$ start_time = f$time()
$ wait 0::10
$ end_time = f$time()
$ write sys$output "start time was ", start_time
$ write sys$output "end time was   ", end_time
$ write sys$output "delta time is         ", f$delta_time( start_time, end_time )


lblDateTime.Caption := FormatDateTime('dd mmmm yyyy hh:mm:ss', Now);


PrintLn(FormatDateTime('dd mmmm yyyy hh:mm:ss', Now));


import extensions;
import system'calendar;

public program()
{
    console.printLine(Date.Now);
}


:os.timestamp                   # => {MegaSecs, Secs, MicroSecs}
:erlang.time                    # => {Hour, Minute, Second}
:erlang.date                    # => {Year, Month, Day}
:erlang.localtime               # => {{Year, Month, Day}, {Hour, Minute, Second}}
:erlang.universaltime           # => {{Year, Month, Day}, {Hour, Minute, Second}}

:calendar.local_time            # => {{Year, Month, Day}, {Hour, Minute, Second}}
:calendar.universal_time        # => {{Year, Month, Day}, {Hour, Minute, Second}}


(message "%s" (current-time-string))
;; => "Wed Oct 14 22:21:05 1987"


/* Added by Aykayayciti Earl Lamont Montgomery
April 10th, 2018 */

> CurrentTime().toString()


fansh> DateTime.nowTicks
351823905158000000
fansh> DateTime.now
2011-02-24T00:51:47.066Z London
fansh> DateTime.now.toJava
1298508885979


[UNDEFINED] [email protected] [IF]                                   \ Win32Forth (rolls over daily)
 [DEFINED] ?MS [IF] ( -- ms )
   : [email protected] ?MS ;                                         \ iForth
 [ELSE] [DEFINED] cputime [IF] ( -- Dusec )
   : [email protected] cputime d+ 1000 um/mod nip ;                  \ gforth: Anton Ertl
 [ELSE] [DEFINED] [email protected] [IF] ( -- Dusec )
   : [email protected] [email protected] >us 1000 um/mod nip ;                  \ bigForth
 [ELSE] [DEFINED] gettimeofday [IF] ( -- usec sec )
   : [email protected] gettimeofday 1000 MOD 1000 * SWAP 1000 / + ;  \ PFE
 [ELSE] [DEFINED] counter [IF]
   : [email protected] counter ;                                     \ SwiftForth
 [ELSE] [DEFINED] GetTickCount [IF]
   : [email protected] GetTickCount ;                                \ VFX Forth
 [ELSE] [DEFINED] MICROSECS [IF]
   : [email protected]  microsecs 1000 UM/MOD nip ;                  \  MacForth
[THEN] [THEN] [THEN] [THEN] [THEN] [THEN] [THEN]

[email protected] .   \ print millisecond counter


integer :: start, stop, rate
real :: result

! optional 1st integer argument (COUNT) is current raw system clock counter value (not UNIX epoch millis!!)
! optional 2nd integer argument (COUNT_RATE) is clock cycles per second
! optional 3rd integer argument (COUNT_MAX) is maximum clock counter value
call system_clock( start, rate )

result = do_timed_work()

call system_clock( stop )

print *, "elapsed time: ", real(stop - start) / real(rate)


' FB 1.05.0 Win64

Print Date + " " + Time  '' returns system date/time in format : mm-dd-yyyy hh:mm:ss
Sleep


window 1
print time
print time(@"hh:mm:ss"  )
print time(@"h:mm a"    )
print time(@"h:mm a zzz")
HandleEvents


Public Sub Main()

Print Format(Now, "dddd dd mmmm yyyy hh:nn:ss")

End


[indent=4]

init
    var now = new DateTime.now_local()
    print now.to_string()


package main

import "time"
import "fmt"

func main() {
    t := time.Now()
    fmt.Println(t)                                    // default format
    fmt.Println(t.Format("Mon Jan  2 15:04:05 2006")) // some custom format
}


def nowMillis = new Date().time
println 'Milliseconds since the start of the UNIX Epoch (Jan 1, 1970) == ' + nowMillis


import System.Time
       (getClockTime, toCalendarTime, formatCalendarTime)

import System.Locale (defaultTimeLocale)

main :: IO ()
main = do
  ct <- getClockTime
  print ct -- print default format, or
  cal <- toCalendarTime ct
  putStrLn $ formatCalendarTime defaultTimeLocale "%a %b %e %H:%M:%S %Y" cal


seconds_since_midnight = TIME() ! msec as fraction

seconds_since_midnight = TIME(Year=yr, Day=day, WeekDay=wday, Gregorian=gday)
                             ! other options e.g. Excel, YYYYMMDD (num or text)


CDateStruct ds;
Date2Struct(&ds, Now + local_time_offset);

Print("%04d-%02d-%02d %02d:%02d:%02d\n", ds.year, ds.mon, ds.day_of_mon, ds.hour, ds.min, ds.sec);


procedure main()

    write("&time - milliseconds of CPU time = ",&time)
    write("&clock - Time of day as hh:mm:ss (24-hour format) = ",&clock)
    write("&date - current date in yyyy/mm/dd format = ",&date)
    write("&dateline - timestamp with day of the week, date, and current time to the minute = ",&dateline)

    if find("Unicon",&version) then
       write("&now - time in seconds since the epoch = ", &now)  # Unicon only

end


public class SystemTime{
    public static void main(String[] args){
        System.out.format("%tc%n", System.currentTimeMillis());
    }
}


console.log(new Date()) // => Sat, 28 May 2011 08:22:53 GMT
console.log(Date.now()) // => 1306571005417 // Unix epoch


ts = time()

println("The system time is (in ISO 8601 format):")
println(strftime("    %F %T %Z", ts))


// version 1.0.6

fun main(args: Array<String>) {
    println("%tc".format(System.currentTimeMillis()))
}


print time$()               'time now as string "16:21:44"
print time$("seconds")      'seconds since midnight as number 32314
print time$("milliseconds") 'milliseconds since midnight as number 33221342
print time$("ms")           'milliseconds since midnight as number 33221342


print [system date]; print [system date +%s.%N]


put time()
-- "03:45"

put date()
-- "01.10.2016"

put the systemdate
-- date( 2016, 10, 1 )

put the systemdate.seconds
-- 13950

-- milliseconds since last boot, due to higher resolution better suited for random number seeding
put _system.milliseconds
-- 41746442


print time
print time/300;"s since last reboot"


to time
  output first first shell [date +%s]
end

make "start time
wait 300              ; 60ths of a second
print time - :start   ; 5


/* Time and date in a formatted string */
timedate();
"2012-08-27 20:26:23+10:00"

/* Time in seconds elapsed since 1900/1/1 0:0:0 */
absolute_real_time();

/* Time in seconds since Maxima was started */
elapsed_real_time();
elapsed_run_time();


MODULE Mytime;

FROM SysClock IMPORT
  GetClock, DateTime;
FROM STextIO IMPORT
  WriteString, WriteLn;
FROM FormatDT IMPORT
  DateTimeToString;

VAR
  CurrentTime: DateTime;
  DateStr, TimeStr: ARRAY [0 .. 20] OF CHAR;
BEGIN
  GetClock(CurrentTime);
  DateTimeToString(CurrentTime, DateStr, TimeStr);
  WriteString("Current time: ");
  WriteString(DateStr);
  WriteString(" ");
  WriteString(TimeStr);
  WriteLn;
END Mytime.


MODULE MyTime EXPORTS Main;

IMPORT IO, FmtTime, Time;

BEGIN
  IO.Put("Current time: " & FmtTime.Long(Time.Now()) & "\n");
END MyTime.


SYSTIME
 NEW PH
 SET PH=$PIECE($HOROLOG,",",2)
 WRITE "The system time is ",PH\3600,":",PH\60#60,":",PH#60
 KILL PH
 QUIT


import Nanoquery.Util
println new(Date).getTime()


/**
 <doc>

System time

Neko uses Int32 to store system date/time values.
 And lib C strftime style formatting for converting to string form

 </doc>
*/

var date_now = $loader.loadprim("[email protected]_now", 0)
var date_format = $loader.loadprim("[email protected]_format", 2)

var now = date_now()
$print(now, " ", date_format(now, "%T"), "\n")


import java.text.SimpleDateFormat
say SimpleDateFormat("yyyy-MM-dd-HH.mm.ss.SSS").format(Date())


import times

echo getDateStr()
echo getClockStr()
echo getTime()
echo now()  # shorthand for "getTime().local"


function : Time() ~ Nil {
  t := Time->New();
  IO.Console->GetInstance()->Print(t->GetHours())->Print(":")->Print(t->GetMinutes())->Print(":")->PrintLine(t->GetSeconds());
}


#load "unix.cma";;
open Unix;;
let {tm_sec = sec;
     tm_min = min;
     tm_hour = hour;
     tm_mday = mday;
     tm_mon = mon;
     tm_year = year;
     tm_wday = wday;
     tm_yday = yday;
     tm_isdst = isdst} = localtime (time ());;
Printf.printf "%04d-%02d-%02d %02d:%02d:%02d\n" (year + 1900) (mon + 1) mday hour min sec;


System.tick println
#[ #sqrt 1000000 seq map sum println ] bench


{Show {OS.time}}      %% posix time (seconds since 1970-01-01)
{Show {OS.gmTime}}    %% current UTC as a record
{Show {OS.localTime}} %% current local time as record

%% Also interesting: undocumented module OsTime
%% When did posix time reach 1 billion?
{Show {OsTime.gmtime 1000000000}}
{Show {OsTime.localtime 1000000000}}


type
	timeStamp = packed record
			dateValid: Boolean;
			year: integer;
			month: 1..12;
			day: 1..31;
			timeValid: Boolean;
			hour: 0..23;
			minute: 0..59;
			second: 0..59;
		end;


include timedate.e
?format_timedate(date(),"Dddd, Mmmm dth, YYYY, h:mm:ss pm")

atom t0 = time()
sleep(0.9)
?time()-t0


def printList len for get print endfor enddef

time

"Actual time is " swap 1 get " hour, " rot 2 get " minutes, " rot 3 get nip " seconds, "
"and elapsed " msec " seconds of running time." 10 tolist printList


put (datetime()); /* writes out the date and time */
                  /* The time is given to thousandths of a second, */
                  /* in the format hhmiss999 */
put (time());     /* gives the time in the format hhmiss999. */


time=Date()  ; Unix timestamp
time$=FormatDate("%mm.%dd.%yyyy %hh:%ii:%ss",time)

; following value is only reasonable accurate, on Windows it can differ by +/- 20 ms
ms_counter=ElapsedMilliseconds()
; could use API like QueryPerformanceCounter_() on Windows for more accurate values


time 1000000 / echo say " seconds since the Unix epoch."


#lang racket
(require racket/date)
(date->string (current-date))


say DateTime.now;
dd DateTime.now.Instant;


time dup print "\n" print int '%a %b %e %H:%M:%S %Y' date


now
print rejoin [now/year "-" now/month "-" now/day " " now/time]


/*REXX program shows various ways to display the system time, including other options.  */

say '════════════ Normal format of time'
say 'hh:mm:ss        ◄─────────────── hh= is  00 ──► 23'
say 'hh:mm:ss        ◄─────────────── hh= hour   mm= minute   ss= second'
say time()
say time('n')                                    /*    (same as the previous example.)  */
say time('N')                                    /*       "   "  "      "       "       */
say time('Normal')                               /*       "   "  "      "       "       */
say time('nitPick')                              /*       "   "  "      "       "       */

say
say '════════════ Civil format of time'
say 'hh:mmcc         ◄─────────────── hh= is   1 ──► 12'
say 'hh:mmam         ◄─────────────── hh= hour   mm= minute   am= ante meridiem'
say 'hh:mmpm         ◄───────────────                         pm= post meridiem'
say time('C')
say time('civil')                                /*    (same as the previous example.)  */
                                                 /*ante meridiem≡Latin for before midday*/
                                                 /*post    "       "    "   after   "   */
say
say '════════════ long format of time'
say 'hh:mm:ss        ◄─────────────── hh= is   0 ──► 23'
say 'hh:mm:ss.ffffff ◄─────────────── hh= hour   mm= minute   fffff= fractional seconds'
say time('L')
say time('long')                                 /*    (same as the previous example.)  */
say time('long time no see')                     /*       "   "  "      "       "       */

say
say '════════════ complete hours since midnight'
say 'hh              ◄─────────────── hh =  0 ───► 23'
say time('H')
say time('hours')                                /*    (same as the previous example.)  */

say
say '════════════ complete minutes since midnight'
say 'mmmm            ◄─────────────── mmmm =  0 ───► 1439'
say time('M')
say time('minutes')                              /*    (same as the previous example.)  */

say
say '════════════  complete seconds since midnight'
say 'sssss           ◄─────────────── sssss =  0 ───► 86399'
say time('S')
say time('seconds')                              /*    (same as the previous example.)  */
                                                 /*stick a fork in it,  we're all done. */


/* Output:
** Sun                  abbreviated weekday name
** Sunday               full weekday name
** May                  abbreviated month name
** May                  full month name
** 05/24/15 09:58:38    Date & Time
** 24                   Day of the month
** 09                   Hour (24)
** 09                   Hour (12)
** 144                  Day of the year
** 05                   Month of the year
** 58                   Minutes after hour
** AM                   AM or PM
** 38                   Seconds after the hour
** 21                   Week of the year (sun-sat)
** 0                    day of the week
** 05/24/15             date
** 09:58:38             time
** 15                   year of the century
** 2015                 year
** Arab Standard Time   time zone
** %                    percent sign
*/

See TimeList()


t = Time.now

# textual
puts t        # => 2013-12-27 18:00:23 +0900

# epoch time
puts t.to_i   # => 1388134823

# epoch time with fractional seconds
puts t.to_f   # => 1388134823.9801579

# epoch time as a rational (more precision):
puts Time.now.to_r  # 1424900671883862959/1000000000


// 20210210 Rust programming solution

extern crate chrono;
use chrono::prelude::*;

fn main() {
   let utc: DateTime<Utc> = Utc::now();
   println!("{}", utc.format("%d/%m/%Y %T"));
}