package require math::linearalgebra

proc build.matrix {xvec degree} {
    set sums [llength $xvec]
    for {set i 1} {$i <= 2*$degree} {incr i} {
        set sum 0
        foreach x $xvec {
            set sum [expr {$sum + pow($x,$i)}]
        }
        lappend sums $sum
    }

    set order [expr {$degree + 1}]
    set A [math::linearalgebra::mkMatrix $order $order 0]
    for {set i 0} {$i <= $degree} {incr i} {
        set A [math::linearalgebra::setrow A $i [lrange $sums $i $i+$degree]]
    }
    return $A
}

proc build.vector {xvec yvec degree} {
    set sums [list]
    for {set i 0} {$i <= $degree} {incr i} {
        set sum 0
        foreach x $xvec y $yvec {
            set sum [expr {$sum + $y * pow($x,$i)}]
        }
        lappend sums $sum
    }

    set x [math::linearalgebra::mkVector [expr {$degree + 1}] 0]
    for {set i 0} {$i <= $degree} {incr i} {
        set x [math::linearalgebra::setelem x $i [lindex $sums $i]]
    }
    return $x
}

# Now, to solve the example from the top of this page
set x {0   1   2   3   4   5   6   7   8   9  10}
set y {1   6  17  34  57  86 121 162 209 262 321}

# build the system A.x=b
set degree 2
set A [build.matrix $x $degree]
set b [build.vector $x $y $degree]
# solve it
set coeffs [math::linearalgebra::solveGauss $A $b]
# show results
puts $coeffs


popCount: function [num][
    size select split to :string as.binary num 'x -> x="1"
]

print "population count for the first thirty powers of 3:"
print map 0..29 => [popCount 3^&]

print "first thirty evil numbers"
print take select 0..100 => [even? popCount &] 30

print "first thirty odious numbers"
print take select 0..100 => [odd? popCount &] 30


#import std
#import nat
#import flo

(fit "n") ("x","y") = ..dgelsd\"y" (gang \/*pow float*x iota successor "n")* "x"


Option Base 1
Private Function polynomial_regression(y As Variant, x As Variant, degree As Integer) As Variant
    Dim a() As Double
    ReDim a(UBound(x), 2)
    For i = 1 To UBound(x)
        For j = 1 To degree
            a(i, j) = x(i) ^ j
        Next j
    Next i
    polynomial_regression = WorksheetFunction.LinEst(WorksheetFunction.Transpose(y), a, True, True)
End Function
Public Sub main()
    x = [{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}]
    y = [{1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321}]
    result = polynomial_regression(y, x, 2)
    Debug.Print "coefficients   : ";
    For i = UBound(result, 2) To 1 Step -1
        Debug.Print Format(result(1, i), "0.#####"),
    Next i
    Debug.Print
    Debug.Print "standard errors: ";
    For i = UBound(result, 2) To 1 Step -1
        Debug.Print Format(result(2, i), "0.#####"),
    Next i
    Debug.Print vbCrLf
    Debug.Print "R^2 ="; result(3, 1)
    Debug.Print "F   ="; result(4, 1)
    Debug.Print "Degrees of freedom:"; result(4, 2)
    Debug.Print "Standard error of y estimate:"; result(3, 2)
End Sub


# syntax: GAWK -f POPULATION_COUNT.AWK
# converted from VBSCRIPT
BEGIN {
    nmax = 30
    b = 3
    n = 0
    bb = 1
    for (i=1; i<=nmax; i++) {
      list = list pop_count(bb) " "
      bb *= b
    }
    printf("%s^n: %s\n",b,list)
    for (j=0; j<=1; j++) {
      c = (j == 0) ? "evil" : "odious"
      i = n = 0
      list = ""
      while (n < nmax) {
        if (pop_count(i) % 2 == j) {
          n++
          list = list i " "
        }
        i++
      }
      printf("%s: %s\n",c,list)
    }
    exit(0)
}
function pop_count(xx,  xq,xr,y) {
    while (xx > 0) {
      xq = int(xx / 2)
      xr = xx - xq * 2
      if (xr == 1) { y++ }
      xx = xq
    }
    return(y)
}


print "Pop cont (3^x): ";
for i = 0 to 29
    print population(3^i); " "; #los últimos números no los muestra correctamente
next i

print : print
print "Evil numbers:   ";
call EvilOdious(30, 0)

print : print
print "Odious numbers: ";
call EvilOdious(30, 1)
end

subroutine EvilOdious(limit, type)
    i = 0 : cont = 0

    do
        eo = (population(i) mod 2)
        if (type and eo) or (not type and not eo) then
            cont += 1 : print i; " ";
        end if
        i += 1
    until (cont = limit)
end subroutine

function population(number)
    popul = 0

    binary$ = tobinary(number)
    for i = 1 to length(binary$)
        popul += int(mid(binary$, i, 1))
    next i
    return popul
end function


import "/math" for Nums
import "/seq" for Lst
import "/fmt" for Fmt

var polynomialRegression = Fn.new { |x, y|
    var xm   = Nums.mean(x)
    var ym   = Nums.mean(y)
    var x2m  = Nums.mean(x.map { |e| e * e })
    var x3m  = Nums.mean(x.map { |e| e * e * e })
    var x4m  = Nums.mean(x.map { |e| e * e * e * e })
    var z    = Lst.zip(x, y)
    var xym  = Nums.mean(z.map { |p| p[0] * p[1] })
    var x2ym = Nums.mean(z.map { |p| p[0] * p[0] * p[1] })

    var sxx   = x2m - xm * xm
    var sxy   = xym - xm * ym
    var sxx2  = x3m - xm * x2m
    var sx2x2 = x4m - x2m * x2m
    var sx2y  = x2ym - x2m * ym

    var b = (sxy * sx2x2 - sx2y * sxx2) / (sxx * sx2x2 - sxx2 * sxx2)
    var c = (sx2y * sxx - sxy * sxx2) / (sxx * sx2x2 - sxx2 * sxx2)
    var a = ym - b * xm - c * x2m

    var abc = Fn.new { |xx| a + b * xx + c * xx * xx }

    System.print("y = %(a) + %(b)x + %(c)x^2\n")
    System.print(" Input  Approximation")
    System.print(" x   y     y1")
    for (p in z) Fmt.print("$2d $3d  $5.1f", p[0], p[1], abc.call(p[0]))
}

var x = List.filled(11, 0)
for (i in 1..10) x[i] = i
var y = [1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321]
polynomialRegression.call(x, y)


get "libhdr"

// Definitions
let popcount(n) = n=0 -> 0, (n&1) + popcount(n >> 1)
let evil(n)     = (popcount(n) & 1) = 0
let odious(n)   = (popcount(n) & 1) = 1

// The BCPL word size is implementation-dependent,
// but very unlikely to be big enough to store 3^29.
// This implements a 48-bit integer using byte strings.
let move48(dest, src) be
    for i=0 to 5 do dest%i := src%i

let set48(dest, n) be
    for i=5 to 0 by -1
    $(  dest%i := n & #XFF
        n := n >> 8
    $)

let add48(dest, src) be
$(  let temp = ? and carry = 0
    for i=5 to 0 by -1
    $(  temp := dest%i + src%i + carry
        carry := temp > #XFF -> 1, 0
        dest%i := temp & #XFF
    $)
$)

let mul3(n) be
$(  let temp = vec 2  // big enough even on a 16-bit machine
    move48(temp, n)
    add48(n, n)
    add48(n, temp)
$)

let popcount48(n) = valof
$(  let total = 0
    for i=0 to 5 do
        total := total + popcount(n%i)
    resultis total
$)

// print the first N numbers
let printFirst(amt, prec) be
$(  let seen = 0 and n = 0
    until seen >= amt
    $(  if prec(n)
        $(  writed(n, 3)
            seen := seen + 1
        $)
        n := n + 1
    $)
    wrch('*N')
$)

let start() be
$(  let pow3 = vec 2

    // print 3^0 to 3^29
    set48(pow3, 1)
    for i = 0 to 29
    $(  writed(popcount48(pow3), 3)
        mul3(pow3)
    $)
    wrch('*N')

    // print the first 30 evil and odious numbers
    printFirst(30, evil)
    printFirst(30, odious)
$)


PopCount ← {(2|𝕩)+𝕊⍟×⌊𝕩÷2}
Odious ← 2|PopCount
Evil ← ¬Odious

_List ← {𝕩↑𝔽¨⊸/↕2×𝕩}
>⟨PopCount¨ 3⋆↕30,
  Evil _List 30,
  Odious _List 30⟩


#include <stdio.h>

int main() {
  {
    unsigned long long n = 1;
    for (int i = 0; i < 30; i++) {
      // __builtin_popcount() for unsigned int
      // __builtin_popcountl() for unsigned long
      // __builtin_popcountll() for unsigned long long
      printf("%d ", __builtin_popcountll(n));
      n *= 3;
    }
    printf("\n");
  }

  int od[30];
  int ne = 0, no = 0;
  printf("evil  : ");
  for (int n = 0; ne+no < 60; n++) {
    if ((__builtin_popcount(n) & 1) == 0) {
      if (ne < 30) {
	printf("%d ", n);
	ne++;
      }
    } else {
      if (no < 30) {
	od[no++] = n;
      }
    }
  }
  printf("\n");
  printf("odious: ");
  for (int i = 0; i < 30; i++) {
    printf("%d ", od[i]);
  }
  printf("\n");

  return 0;
}


var [const] GSL=Import("zklGSL");	// libGSL (GNU Scientific Library)
xs:=GSL.VectorFromData(0,  1,  2,  3,  4,  5,   6,   7,   8,   9,  10);
ys:=GSL.VectorFromData(1,  6, 17, 34, 57, 86, 121, 162, 209, 262, 321);
v :=GSL.polyFit(xs,ys,2);
v.format().println();
GSL.Helpers.polyString(v).println();
GSL.Helpers.polyEval(v,xs).format().println();


using System;
using System.Linq;

namespace PopulationCount
{
    class Program
    {
        private static int PopulationCount(long n)
        {
            string binaryn = Convert.ToString(n, 2);
            return binaryn.ToCharArray().Where(t => t == '1').Count();
        }

        static void Main(string[] args)
        {
            Console.WriteLine("Population Counts:");
            Console.Write("3^n :   ");

            int count = 0;

            while (count < 30)
            {
                double n = Math.Pow(3f, (double)count);
                int popCount = PopulationCount((long)n);
                Console.Write(string.Format("{0} ", popCount));
                count++;
            }

            Console.WriteLine();
            Console.Write("Evil:   ");

            count = 0;
            int i = 0;

            while (count < 30)
            {
                int popCount = PopulationCount(i);

                if (popCount % 2 == 0)
                {
                    count++;
                    Console.Write(string.Format("{0} ", i));
                }

                i++;
            }

            Console.WriteLine();
            Console.Write("Odious: ");

            count = 0;
            i = 0;

            while (count < 30)
            {
                int popCount = PopulationCount(i);

                if (popCount % 2 != 0)
                {
                    count++;
                    Console.Write(string.Format("{0} ", i));
                }

                i++;
            }

            Console.ReadKey();
        }
    }
}


#include <iostream>
#include <bitset>
#include <climits>

size_t popcount(unsigned long long n) {
  return std::bitset<CHAR_BIT * sizeof n>(n).count();
}

int main() {
  {
    unsigned long long n = 1;
    for (int i = 0; i < 30; i++) {
      std::cout << popcount(n) << " ";
      n *= 3;
    }
    std::cout << std::endl;
  }

  int od[30];
  int ne = 0, no = 0;
  std::cout << "evil  : ";
  for (int n = 0; ne+no < 60; n++) {
    if ((popcount(n) & 1) == 0) {
      if (ne < 30) {
	std::cout << n << " ";
	ne++;
      }
    } else {
      if (no < 30) {
	od[no++] = n;
      }
    }
  }
  std::cout << std::endl;
  std::cout << "odious: ";
  for (int i = 0; i < 30; i++) {
    std::cout << od[i] << " ";
  }
  std::cout << std::endl;

  return 0;
}


(defn population-count [n]
  (Long/bitCount n))         ; use Java inter-op

(defn exp [n pow]
  (reduce * (repeat pow n)))

(defn evil? [n]
  (even? (population-count n)))

(defn odious? [n]
  (odd? (population-count n)))

;;
;; Clojure's support for generating "lazily-evaluated" infinite sequences can
;; be used to generate the requested output sets.  We'll create some infinite
;; sequences, and only as many items will be computed as are "pulled" by 'take'.
;;
(defn integers []
  (iterate inc 0))

(defn powers-of-n [n]
  (map #(exp n %) (integers)))

(defn evil-numbers []
  (filter evil? (integers)))

(defn odious-numbers []
  (filter odious? (integers)))


pop_count = proc (n: int) returns (int)
    p: int := 0
    while n>0 do
        p := p + n//2
        n := n/2
    end
    return(p)
end pop_count

evil = proc (n: int) returns (bool)
    return(pop_count(n)//2 = 0)
end evil

odious = proc (n: int) returns (bool)
    return(~evil(n))
end odious

first = iter (n: int, p: proctype (int) returns (bool)) yields (int)
    i: int := 0
    while n>0 do
        if p(i) then
            yield(i)
            n := n-1
        end
        i := i+1
    end
end first

start_up = proc ()
    po: stream := stream$primary_output()

    for i: int in int$from_to(0,29) do
        stream$putright(po, int$unparse(pop_count(3**i)), 3)
    end
    stream$putl(po, "")

    for i: int in first(30, evil) do
        stream$putright(po, int$unparse(i), 3)
    end
    stream$putl(po, "")

    for i: int in first(30, odious) do
        stream$putright(po, int$unparse(i), 3)
    end
    stream$putl(po, "")
end start_up


       IDENTIFICATION DIVISION.
       PROGRAM-ID.  HAMMING.

       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01 POPCOUNT-VARIABLES.
          03 POPCOUNT-IN       PIC 9(15)V9.
          03 FILLER            REDEFINES POPCOUNT-IN.
             05 POPCOUNT-REST  PIC 9(15).
             05 FILLER         PIC 9.
                88 BIT-IS-SET  VALUE 5.
          03 POPCOUNT-OUT      PIC 99.
          03 FILLER            REDEFINES POPCOUNT-OUT.
             05 FILLER         PIC 9.
             05 FILLER         PIC 9.
                88 EVIL        VALUES 0, 2, 4, 6, 8.
                88 ODIOUS      VALUES 1, 3, 5, 7, 9.

       01 STATE-VARIABLES.
          03 CUR-POWER-3       PIC 9(15) VALUE 1.
          03 CUR-EVIL-NUM      PIC 99 VALUE 0.
          03 CUR-ODIOUS-NUM    PIC 99 VALUE 0.
          03 LINE-INDEX        PIC 99 VALUE 1.

       01 OUTPUT-FORMAT.
          03 LINENO            PIC Z9.
          03 FILLER            PIC X VALUE '.'.
          03 FILLER            PIC XX VALUE SPACES.
          03 OUT-POW3          PIC Z9.
          03 FILLER            PIC X(4) VALUE SPACES.
          03 OUT-EVIL          PIC Z9.
          03 FILLER            PIC X(4) VALUE SPACES.
          03 OUT-ODIOUS        PIC Z9.

       PROCEDURE DIVISION.
       BEGIN.
           DISPLAY "     3^   EVIL   ODD"
           PERFORM MAKE-LINE 30 TIMES.
           STOP RUN.

       MAKE-LINE.
           MOVE LINE-INDEX TO LINENO.
           MOVE CUR-POWER-3 TO POPCOUNT-IN.
           PERFORM FIND-POPCOUNT.
           MOVE POPCOUNT-OUT TO OUT-POW3.
           PERFORM FIND-EVIL.
           MOVE CUR-EVIL-NUM TO OUT-EVIL.
           PERFORM FIND-ODIOUS.
           MOVE CUR-ODIOUS-NUM TO OUT-ODIOUS.
           DISPLAY OUTPUT-FORMAT.
           MULTIPLY 3 BY CUR-POWER-3.
           ADD 1 TO CUR-EVIL-NUM.
           ADD 1 TO CUR-ODIOUS-NUM.
           ADD 1 TO LINE-INDEX.

       FIND-EVIL.
           MOVE CUR-EVIL-NUM TO POPCOUNT-IN.
           PERFORM FIND-POPCOUNT.
           IF NOT EVIL, ADD 1 TO CUR-EVIL-NUM, GO TO FIND-EVIL.

       FIND-ODIOUS.
           MOVE CUR-ODIOUS-NUM TO POPCOUNT-IN.
           PERFORM FIND-POPCOUNT.
           IF NOT ODIOUS, ADD 1 TO CUR-ODIOUS-NUM, GO TO FIND-ODIOUS.

       FIND-POPCOUNT.
           MOVE 0 TO POPCOUNT-OUT.
           PERFORM PROCESS-BIT UNTIL POPCOUNT-IN IS EQUAL TO ZERO.

       PROCESS-BIT.
           DIVIDE 2 INTO POPCOUNT-IN.
           IF BIT-IS-SET, ADD 1 TO POPCOUNT-OUT.
           MOVE POPCOUNT-REST TO POPCOUNT-IN.


(format T "3^x: ~{~a ~}~%"
        (loop for i below 30
              collect (logcount (expt 3 i))))

(multiple-value-bind
  (evil odious)
  (loop for i below 60
        if (evenp (logcount i)) collect i into evil
        else collect i into odious
        finally (return (values evil odious)))
  (format T "evil: ~{~a ~}~%" evil)
  (format T "odious: ~{~a ~}~%" odious))


struct Int
  def evil?
    self >= 0 && popcount.even?
  end
end

puts "Powers of 3:", (0...30).map{|n| (3u64 ** n).popcount}.join(' ') # can also use &** (to prevent arithmetic overflow)
puts "Evil:"  , 0.step.select(&.evil?).first(30).join(' ')
puts "Odious:", 0.step.reject(&.evil?).first(30).join(' ')


void main() {
    import std.stdio, std.algorithm, std.range, core.bitop;

    enum pCount = (ulong n) => popcnt(n & uint.max) + popcnt(n >> 32);
    writefln("%s\nEvil: %s\nOdious: %s",
             uint.max.iota.map!(i => pCount(3L ^^ i)).take(30),
             uint.max.iota.filter!(i => pCount(i) % 2 == 0).take(30),
             uint.max.iota.filter!(i => pCount(i) % 2).take(30));
}


program Population_count;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.SysUtils,
  Math;

function PopulationCount(AInt: UInt64): Integer;
begin
  Result := 0;
  repeat
    inc(Result, (AInt and 1));
    AInt := AInt div 2;
  until (AInt = 0);
end;

var
  i, count: Integer;
  n: Double;
  popCount: Integer;

begin
  Writeln('Population Counts:'#10);
  Write('3^n :   ');
  for i := 0 to 30 do
  begin
    n := Math.Power(3, i);
    popCount := PopulationCount(round(n));
    Write(Format('%d ', [popCount]));
  end;
  Writeln(#10#10'Evil:   ');

  count := 0;
  i := 0;
  while (count < 30) do
  begin
    popCount := PopulationCount(i);
    if not Odd(popCount) then
    begin
      inc(count);
      Write(Format('%d ', [i]));
    end;
    inc(i);
  end;
  Writeln(#10#10'Odious: ');

  count := 0;
  i := 0;
  while (count < 30) do
  begin
    popCount := PopulationCount(i);
    if Odd(popCount) then
    begin
      inc(count);
      Write(Format('%d ', [i]));
    end;
    inc(i);
  end;

  readln;
end.


defmodule Population do

  def count(n), do: count(<<n :: integer>>, 0)

  defp count(<<>>, acc), do: acc

  defp count(<<bit :: integer-1, rest :: bitstring>>, sum), do: count(rest, sum + bit)

  def evil?(n), do: n >= 0 and rem(count(n),2) == 0

  def odious?(n), do: n >= 0 and rem(count(n),2) == 1

end

IO.puts "Population count of the first thirty powers of 3:"
IO.inspect Stream.iterate(1, &(&1*3)) |> Enum.take(30) |> Enum.map(&Population.count(&1))
IO.puts "first thirty evil numbers:"
IO.inspect Stream.iterate(0, &(&1+1)) |> Stream.filter(&Population.evil?(&1)) |> Enum.take(30)
IO.puts "first thirty odious numbers:"
IO.inspect Stream.iterate(0, &(&1+1)) |> Stream.filter(&Population.odious?(&1)) |> Enum.take(30)


-module(population_count).
-export([popcount/1]).

-export([task/0]).

popcount(N) ->
    popcount(N,0).

popcount(0,Acc) ->
    Acc;
popcount(N,Acc) ->
    popcount(N div 2, Acc + N rem 2).

threes(_,0,Acc) ->
    lists:reverse(Acc);
threes(Threes,N,Acc) ->
    threes(Threes * 3, N-1, [popcount(Threes)|Acc]).

threes(N) ->
    threes(1,N,[]).

evil(_,0,Acc) ->
    lists:reverse(Acc);
evil(N,Count,Acc) ->
    case popcount(N) rem 2 of
        0 ->
            evil(N+1,Count-1,[N|Acc]);
        1 ->
            evil(N+1,Count,Acc)
    end.
evil(Count) ->
    evil(0,Count,[]).

odious(_,0,Acc) ->
    lists:reverse(Acc);
odious(N,Count,Acc) ->
    case popcount(N) rem 2 of
        1 ->
            odious(N+1,Count-1,[N|Acc]);
        0 ->
            odious(N+1,Count,Acc)
    end.
odious(Count) ->
    odious(1,Count,[]).

task() ->
    io:format("Powers of 3: ~p~n",[threes(30)]),
    io:format("Evil:~p~n",[evil(30)]),
    io:format("Odious:~p~n",[odious(30)]).


// Population count. Nigel Galloway: February 18th., 2021
let pC n=Seq.unfold(fun n->match n/2L,n%2L with (0L,0L)->None |(n,g)->Some(g,n))n|>Seq.sum
printf "pow3  :"; [0..29]|>List.iter((pown 3L)>>pC>>(printf "%3d")); printfn ""
printf "evil  :"; Seq.initInfinite(int64)|>Seq.filter(fun n->(pC n) &&& 1L=0L)|>Seq.take 30|>Seq.iter(printf "%3d"); printfn ""
printf "odious:"; Seq.initInfinite(int64)|>Seq.filter(fun n->(pC n) &&& 1L=1L)|>Seq.take 30|>Seq.iter(printf "%3d"); printfn ""


USING: formatting kernel lists lists.lazy math math.bitwise
math.functions namespaces prettyprint.config sequences ;

: 3^n ( obj -- obj' ) [ 3 swap ^ bit-count ] lmap-lazy ;
: evil ( obj -- obj' ) [ bit-count even? ] lfilter ;
: odious ( obj -- obj' ) [ bit-count odd? ] lfilter ;

100 margin set 0 lfrom [ 3^n ] [ evil ] [ odious ] tri
[ 30 swap ltake list>array ] [email protected]
"3^n:    %u\nEvil:   %u\nOdious: %u\n" printf


Func Popcount(n) = if n = 0 then 0 else if 2*(n\2)=n then Popcount(n\2) else Popcount((n-1)\2)+1 fi fi.
Func Odiousness(n) = p:=Popcount(n);if 2*(p\2) = p then 0 else 1 fi.

for n=0 to 29 do !Popcount(3^n);!' ' od
e:=0
n:=0
while e<30 do if Odiousness(n)=0 then !n;!' ';e:=e+1 fi; n:=n+1 od
e:=0
n:=0
while e<30 do if Odiousness(n)=1 then !n;!' ';e:=e+1 fi; n:=n+1 od


: popcnt ( n -- u)  0 swap
   BEGIN dup WHILE tuck 1 AND +  swap 1 rshift REPEAT
   DROP ;
: odious? ( n -- t|f)  popcnt 1 AND ;
: evil? ( n -- t|f)  odious? 0= ;

CREATE A 30 ,
: task1   1 0  ." 3**i popcnt: "
   BEGIN dup A @ < WHILE
     over popcnt .  1+ swap 3 * swap
   REPEAT  DROP DROP CR ;
: task2   0 0  ." evil       : "
   BEGIN dup A @ < WHILE
     over evil? IF over . 1+ THEN swap 1+ swap
   REPEAT  DROP DROP CR ;
: task3   0 0  ." odious     : "
   BEGIN dup A @ < WHILE
     over odious? IF over . 1+ THEN swap 1+ swap
   REPEAT  DROP DROP CR ;
task1 task2 task3 BYE


program population_count
  implicit none

  integer, parameter :: i64 = selected_int_kind(18)
  integer(i64) :: x
  integer :: i, n

  x = 1
  write(*, "(a8)", advance = "no") "3**i :"
  do i = 1, 30
    write(*, "(i3)", advance = "no") popcnt(x)
    x = x * 3
  end do

  write(*,*)
  write(*, "(a8)", advance = "no") "Evil :"
  n = 0
  x = 0
  do while(n < 30)
    if(mod(popcnt(x), 2) == 0) then
      n = n + 1
      write(*, "(i3)", advance = "no") x
    end if
    x = x + 1
  end do

  write(*,*)
  write(*, "(a8)", advance = "no") "Odious :"
  n = 0
  x = 0
  do while(n < 30)
    if(mod(popcnt(x), 2) /= 0) then
      n = n + 1
      write(*, "(i3)", advance = "no") x
    end if
    x = x + 1
  end do

contains

integer function popcnt(x)
  integer(i64), intent(in) :: x
  integer :: i

  popcnt = 0
  do i = 0, 63
    if(btest(x, i)) popcnt = popcnt + 1
  end do

end function
end program


program populationCount(input, output, stdErr);
var
	// general advice: iterator variables are _signed_
	iterator: int64;
	// the variable we’d like to count the set bits in
	number: qWord;
	// how many evil numbers we’ve already found
	evilCount: int64;
	// odious numbers
	odiousNumber: array[1..30] of qWord;
	odiousIterator: int64;
begin
	// population count for powers of three
	for iterator := 0 to 29 do
	begin
		number := round(exp(ln(3) * iterator));
		write(popCnt(number):3);
	end;
	writeLn();

	// evil numbers
	// (while preserving calculated odious numbers for next sub-task)
	evilCount := 0;
	odiousIterator := low(odiousNumber);

	// for-loop: because we (pretend to) don’t know,
	// when and where we’ve found the first 30 numbers of each
	for iterator := 0 to high(iterator) do
	begin
		// implicit typecast: popCnt only accepts _un_-signed integers
		number := iterator;
		if odd(popCnt(number)) then
		begin
			if odiousIterator <= high(odiousNumber) then
			begin
				odiousNumber[odiousIterator] := number;
				inc(odiousIterator);
			end;
		end
		else
		begin
			if evilCount < 30 then
			begin
				write(number:20);
				inc(evilCount);
			end;
		end;

		if evilCount + odiousIterator > 60 then
		begin
			break;
		end;
	end;
	writeLn();

	// odious numbers
	for number in odiousNumber do
	begin
		write(number:20);
	end;
	writeLn();
end.


#define NTERMS 30

function popcount( n as ulongint ) as uinteger
    if n = 0 then return 0
    if n = 1 then return 1
    if n mod 2 = 0 then return popcount(n/2)
    return 1 + popcount( (n - 1)/2 )
end function

dim as ulongint i=0, tp(0 to NTERMS-1), evil(0 to NTERMS-1),_
                     odious(0 to NTERMS-1), k, ne=0, no=0

while ne < NTERMS or no < NTERMS
    if i<NTERMS then tp(i) = popcount(3^i)
    k = popcount(i)
    if k mod 2 = 0 and ne < NTERMS then
        evil(ne) = i
        ne += 1
    endif
    if k mod 2 = 1 and no < NTERMS then
        odious(no) = i
        no += 1
    end if
    i += 1
wend

dim as string s_tp = "", s_evil = "", s_odious = ""

for i = 0 to NTERMS-1
    s_tp += str(tp(i))+" "
    s_evil += str(evil(i))+" "
    s_odious += str(odious(i))+" "
next i

print s_tp
print s_evil
print s_odious


Public Sub Main()
Dim sEvil, sOdious As String                         'To store the output for printing Evil and Odious
Dim iCount, iEvil, iOdious As Integer                'Counters

Print "First 30 numbers ^3\t";                       'Print title

For iCount = 0 To 29                                 'Count 30 times
  Print Len(Replace(Bin(3 ^ iCount), "0", ""));;     'Get the Bin of the number, take out the '0's and the remaining
Next                                                 'length is the Population count e.g. 3^2=9, Bin=1001, remove '0's='11', length=2

iCount = 0                                           'Reset iCount

Repeat                                               'Repeat/Until loop
  If Even(Len(Replace(Bin(iCount), "0", ""))) Then   'If (as above) the result is Even then
    sEvil &= Str(icount) & " "                       'Add it to sEvil
    Inc iEvil                                        'Increase iEvil
  End If
  If Odd(Len(Replace(Bin(iCount), "0", ""))) Then    'If (as above) the result is Odd then
    sOdious &= Str(icount) & " "                     'Add it to sOdious
    Inc iOdious                                      'Increase iOdious
  End If
  Inc iCount                                         'Increase iCount
Until iEvil = 30 And iOdious = 30                    'Until both iEvil and iOdious = 30 then exit the loop

Print "\n1st 30 Evil numbers =\t" & sEvil            'Print Evil
Print "1st 30 Odious numbers =\t" & sOdious          'Print Odious

End


package main

import (
    "fmt"
    "math/bits"
)

func main() {
    fmt.Println("Pop counts, powers of 3:")
    n := uint64(1) // 3^0
    for i := 0; i < 30; i++ {
        fmt.Printf("%d ", bits.OnesCount64(n))
        n *= 3
    }
    fmt.Println()
    fmt.Println("Evil numbers:")
    var od [30]uint64
    var ne, no int
    for n = 0; ne+no < 60; n++ {
        if bits.OnesCount64(n)&1 == 0 {
            if ne < 30 {
                fmt.Printf("%d ", n)
                ne++
            }
        } else {
            if no < 30 {
                od[no] = n
                no++
            }
        }
    }
    fmt.Println()
    fmt.Println("Odious numbers:")
    for _, n := range od {
        fmt.Printf("%d ", n)
    }
    fmt.Println()
}


import Data.Bits (popCount)

printPops :: (Show a, Integral a) => String -> [a] -> IO ()
printPops title counts = putStrLn $ title ++ show (take 30 counts)

main :: IO ()
main = do
  printPops "popcount " $ map popCount $ iterate (*3) (1 :: Integer)
  printPops "evil     " $ filter (even . popCount) ([0..] :: [Integer])
  printPops "odious   " $ filter ( odd . popCount) ([0..] :: [Integer])


module Main
import Data.Vect

isOdd : (x : Int) -> Bool
isOdd x = case mod x 2 of
            0 => False
            1 => True

popcnt : Int -> Int
popcnt 0 = 0
popcnt x = case isOdd x of
  False => popcnt (shiftR x 1)
  True => 1 + popcnt (shiftR x 1)

isOdious : Int -> Bool
isOdious k = isOdd (popcnt k)

isEvil : Int -> Bool
isEvil k = not (isOdious k)

filterUnfoldN : (n : Nat) ->
                (pred : Int -> Bool) -> (f : Int -> a) ->
                (next : Int -> Int) -> (seed : Int) ->
                Vect n a
filterUnfoldN Z pred f next seed = []
filterUnfoldN (S k) pred f next seed =
  if pred seed
  then (f seed) :: filterUnfoldN k pred f next (next seed)
  else filterUnfoldN (S k) pred f next (next seed)

printCompact : (Show a) => Vect n a -> IO ()
printCompact v = putStrLn (unwords (map show (toList v)))

main : IO ()
main = do putStr "popcnt(3**i): "
          printCompact (filterUnfoldN 30 (\_ => True) popcnt (3 *) 1)
          putStr "Evil:         "
          printCompact (filterUnfoldN 30 isEvil id (1 +) 0)
          putStr "Odious:       "
          printCompact (filterUnfoldN 30 isOdious id (1 +) 0)


import java.math.BigInteger;

public class PopCount {
    public static void main(String[] args) {
	{ // with int
	    System.out.print("32-bit integer: ");
	    int n = 1;
	    for (int i = 0; i < 20; i++) {
		System.out.printf("%d ", Integer.bitCount(n));
		n *= 3;
	    }
	    System.out.println();
	}
	{ // with long
	    System.out.print("64-bit integer: ");
	    long n = 1;
	    for (int i = 0; i < 30; i++) {
		System.out.printf("%d ", Long.bitCount(n));
		n *= 3;
	    }
	    System.out.println();
	}
	{ // with BigInteger
	    System.out.print("big integer   : ");
	    BigInteger n = BigInteger.ONE;
	    BigInteger three = BigInteger.valueOf(3);
	    for (int i = 0; i < 30; i++) {
		System.out.printf("%d ", n.bitCount());
		n = n.multiply(three);
	    }
	    System.out.println();
	}

	int[] od = new int[30];
	int ne = 0, no = 0;
	System.out.print("evil   : ");
	for (int n = 0; ne+no < 60; n++) {
	    if ((Integer.bitCount(n) & 1) == 0) {
		if (ne < 30) {
		    System.out.printf("%d ", n);
		    ne++;
		}
	    } else {
		if (no < 30) {
		    od[no++] = n;
		}
	    }
	}
	System.out.println();
	System.out.print("odious : ");
	for (int n : od) {
	    System.out.printf("%d ", n);
	}
	System.out.println();
    }
}


(() => {
    'use strict';

    // populationCount :: Int -> Int
    const populationCount = n =>
        // The number of non-zero bits in the binary
        // representation of the integer n.
        sum(unfoldr(
            x => 0 < x ? (
                Just(Tuple(x % 2)(Math.floor(x / 2)))
            ) : Nothing()
        )(n));

    // ----------------------- TEST ------------------------
    // main :: IO ()
    const main = () => {
        const [evens, odds] = Array.from(
            partition(compose(even, populationCount))(
                enumFromTo(0)(59)
            )
        );
        return [
            'Population counts of the first 30 powers of three:',
            `    [${enumFromTo(0)(29).map(
                    compose(populationCount, raise(3))
                 ).join(',')}]`,
            "\nFirst thirty 'evil' numbers:",
            `    [${[evens.join(',')]}]`,
            "\nFirst thirty 'odious' numbers:",
            `    [${odds.join(',')}]`
        ].join('\n');
    };

    // ----------------- GENERIC FUNCTIONS -----------------

    // Just :: a -> Maybe a
    const Just = x => ({
        type: 'Maybe',
        Nothing: false,
        Just: x
    });

    // Nothing :: Maybe a
    const Nothing = () => ({
        type: 'Maybe',
        Nothing: true,
    });

    // Tuple (,) :: a -> b -> (a, b)
    const Tuple = a =>
        b => ({
            type: 'Tuple',
            '0': a,
            '1': b,
            length: 2
        });

    // compose (<<<) :: (b -> c) -> (a -> b) -> a -> c
    const compose = (...fs) =>
        // A function defined by the right-to-left
        // composition of all the functions in fs.
        fs.reduce(
            (f, g) => x => f(g(x)),
            x => x
        );

    // enumFromTo :: Int -> Int -> [Int]
    const enumFromTo = m =>
        n => !isNaN(m) ? (
            Array.from({
                length: 1 + n - m
            }, (_, i) => m + i)
        ) : enumFromTo_(m)(n);

    // even :: Int -> Bool
    const even = n =>
        // True if n is an even number.
        0 === n % 2;

    // partition :: (a -> Bool) -> [a] -> ([a], [a])
    const partition = p =>
        // A tuple of two lists - those elements in
        // xs which match p, and those which don't.
        xs => ([...xs]).reduce(
            (a, x) =>
            p(x) ? (
                Tuple(a[0].concat(x))(a[1])
            ) : Tuple(a[0])(a[1].concat(x)),
            Tuple([])([])
        );

    // raise :: Num -> Int -> Num
    const raise = x =>
        // X to the power of n.
        n => Math.pow(x, n);

    // sum :: [Num] -> Num
    const sum = xs =>
        // The numeric sum of all values in xs.
        xs.reduce((a, x) => a + x, 0);

    // unfoldr :: (b -> Maybe (a, b)) -> b -> [a]
    const unfoldr = f =>
        v => {
            const xs = [];
            let xr = [v, v];
            while (true) {
                const mb = f(xr[1]);
                if (mb.Nothing) {
                    return xs
                } else {
                    xr = mb.Just;
                    xs.push(xr[0])
                }
            }
        };

    // ---
    return main();
})();


def popcount:
  def bin: recurse( if . == 0 then empty else ./2 | floor end ) % 2;
  [bin] | add;

def firstN(count; condition):
  if count > 0 then
    if condition then ., (1+.| firstN(count-1; condition))
    else (1+.) | firstN(count; condition)
    end
  else empty
  end;

def task:
  def pow(n): . as $m | reduce range(0;n) as $i (1; . * $m);

  "The pop count of the first thirty powers of 3:",
   [range(0;30) as $n | 3 | pow($n) | popcount],

  "The first thirty evil numbers:",
   [0 | firstN(30; (popcount % 2) == 0)],

  "The first thirty odious numbers:",
   [0 | firstN(30; (popcount % 2) == 1)]
;

task


println("First 3 ^ i, up to 29 pop. counts: ", join((count_ones(3 ^ n) for n in 0:29), ", "))
println("Evil numbers: ", join(filter(x -> iseven(count_ones(x)), 0:59), ", "))
println("Odious numbers: ", join(filter(x -> isodd(count_ones(x)), 0:59), ", "))


// version 1.0.6

fun popCount(n: Long) = when {
    n < 0L -> throw IllegalArgumentException("n must be non-negative")
    else   -> java.lang.Long.bitCount(n)
}

fun main(args: Array<String>) {
    println("The population count of the first 30 powers of 3 are:")
    var pow3 = 1L
    for (i in 1..30) {
        print("${popCount(pow3)} ")
        pow3 *= 3L
    }
    println("\n")
    println("The first thirty evil numbers are:")
    var count = 0
    var i = 0
    while (true) {
        val pc = popCount(i.toLong())
        if (pc % 2 == 0) {
           print("$i ")
           if (++count == 30) break
        }
        i++
    }
    println("\n")
    println("The first thirty odious numbers are:")
    count = 0
    i = 1
    while (true) {
        val pc = popCount(i.toLong())
        if (pc % 2 == 1) {
            print("$i ")
            if (++count == 30) break
        }
        i++
    }
    println()
}


-- Take decimal number, return binary string
function dec2bin (n)
    local bin, bit = ""
    while n > 0 do
        bit = n % 2
        n = math.floor(n / 2)
        bin = bit .. bin
    end
    return bin
end

-- Take decimal number, return population count as number
function popCount (n)
    local bin, count = dec2bin(n), 0
    for pos = 1, bin:len() do
        if bin:sub(pos, pos) == "1" then count = count + 1 end
    end
    return count
end

-- Implement task requirements
function firstThirty (mode)
    local numStr, count, n, remainder = "", 0, 0
    if mode == "Evil" then remainder = 0 else remainder = 1 end
    while count < 30 do
        if mode == "3^x" then
            numStr = numStr .. popCount(3 ^ count) .. " "
            count = count + 1
        else
            if popCount(n) % 2 == remainder then
                numStr = numStr .. n .. " "
                count = count + 1
            end
            n = n + 1
        end
    end
    print(mode .. ":" , numStr)
end

-- Main procedure
firstThirty("3^x")
firstThirty("Evil")
firstThirty("Odious")


            NORMAL MODE IS INTEGER

            INTERNAL FUNCTION LOWBIT.(K) = K-K/2*2

          R FUNCTION TO CALC POP COUNT
            INTERNAL FUNCTION(N)
            ENTRY TO POPCNT.
            RSLT = 0
            PCTNUM = N
LOOP        PCTNXT = PCTNUM/2
            RSLT = RSLT + PCTNUM-PCTNXT*2
            PCTNUM = PCTNXT
            WHENEVER PCTNUM.NE.0, TRANSFER TO LOOP
            FUNCTION RETURN RSLT
            END OF FUNCTION

          R POP COUNT OF 3^0 TO 3^29
            POW3 = 1
            THROUGH P3CNT, FOR I=0, 1, I.GE.30
            PRINT FORMAT P3FMT, I, POPCNT.(POW3)
P3CNT       POW3 = POW3 * 3
            VECTOR VALUES P3FMT = $15HPOP COUNT OF 3^,I2,2H: ,I3*$

          R EVIL AND ODIOUS NUMBERS
            PRINT COMMENT$ $
            PRINT COMMENT$ FIRST 30 EVIL NUMBERS ARE$
            SEEN = 1
            THROUGH EVIL, FOR I=0, 1, SEEN.GE.30
            WHENEVER LOWBIT.(POPCNT.(I)).E.0
                PRINT FORMAT NUMFMT,I
                SEEN = SEEN + 1
EVIL        END OF CONDITIONAL

            PRINT COMMENT$ $
            PRINT COMMENT$ FIRST 30 ODIOUS NUMBERS ARE$
            SEEN = 1
            THROUGH ODIOUS, FOR I=0, 1, SEEN.GE.30
            WHENEVER LOWBIT.(POPCNT.(I)).E.1
                PRINT FORMAT NUMFMT,I
                SEEN = SEEN + 1
ODIOUS      END OF CONDITIONAL

            VECTOR VALUES NUMFMT = $I2*$
            END OF PROGRAM


popcount[n_Integer] := IntegerDigits[n, 2] // Total
Print["population count of powers of 3"]
popcount[#] & /@ (3^Range[0, 30])
(*******)
evilQ[n_Integer] := popcount[n] // EvenQ
evilcount = 0;
evillist = {};
i = 0;
While[evilcount < 30,
 If[evilQ[i], AppendTo[evillist, i]; evilcount++];
 i++
 ]
Print["first thirty evil numbers"]
evillist
(*******)
odiousQ[n_Integer] := popcount[n] // OddQ
odiouscount = 0;
odiouslist = {};
i = 0;
While[odiouscount < 30,
 If[odiousQ[i], AppendTo[odiouslist, i]; odiouscount++];
 i++
 ]
Print["first thirty odious numbers"]
odiouslist


(2 over over mod 'div dip) :divmod2

(
  :n () =list
  (n 0 >) (n divmod2 list append #list @n) while
  list (1 ==) filter size
) :pop-count

(:n 0 () (over swap append 'succ dip) n times) :iota

"3^n:    " print! 30 iota (3 swap pow int pop-count) map puts!
60 iota (pop-count odd?) partition
"Evil:   " print! puts! "Odious: " print! puts!


import bitops
import strformat

var n = 1
write(stdout, "3^x   :")
for i in 0..<30:
  write(stdout, fmt"{popcount(n):2} ")
  n *= 3

var od: array[30, int]
var ne, no = 0
n = 0
write(stdout, "\nevil  :")
while ne + no < 60:
  if (popcount(n) and 1) == 0:
    if ne < 30:
      write(stdout, fmt"{n:2} ")
      inc ne
  else:
    if no < 30:
      od[no] = n
      inc no
  inc n

write(stdout, "\nodious:")
for i in 0..<30:
  write(stdout, fmt"{od[i]:2} ")
write(stdout, '\n')


: popcount(n)
   0 while ( n ) [ n isOdd + n bitRight(1) ->n ] ;

: test
| i count |
   30 seq map(#[ 3 swap 1- pow ]) map(#popcount) println

   0 ->count
   0 while( count 30 <> ) [ dup popcount isEven ifTrue: [ dup . count 1+ ->count ] 1+ ] drop printcr

   0 ->count
   0 while( count 30 <> ) [ dup popcount isOdd ifTrue: [ dup . count 1+ ->count ] 1+ ] drop ;


vector(30,n,hammingweight(3^(n-1)))
od=select(n->hammingweight(n)%2,[0..100]); ev=setminus([0..100],od);
ev[1..30]
od[1..30]


unit popcount;
{$IFDEF FPC}
   {$MODE DELPHI}
   {$OPTIMIZATION ON,ASMCSE,CSE,PEEPHOLE}
   {$Smartlink OFF}
{$ENDIF}

interface
  function popcnt(n:Uint64):integer;overload;
  function popcnt(n:Uint32):integer;overload;
  function popcnt(n:Uint16):integer;overload;
  function popcnt(n:Uint8):integer;overload;

implementation
const
//K1  = $0101010101010101;
  K33  = $3333333333333333;
  K55  = $5555555555555555;
  KF1 = $0F0F0F0F0F0F0F0F;
  KF2 = $00FF00FF00FF00FF;
  KF4 = $0000FFFF0000FFFF;
  KF8 = $00000000FFFFFFFF;
{
function popcnt64(n:Uint64):integer;
begin
  n := n- (n shr 1) AND K55;
  n := (n AND K33)+ ((n shr 2) AND K33);
  n := (n + (n shr 4)) AND KF1;
  n := (n*k1) SHR 56;
  result := n;
end;
}
function popcnt(n:Uint64):integer;overload;
// on Intel Haswell 2x faster for fpc 32-Bit
begin
  n := (n AND K55)+((n shr  1)  AND K55);
  n := (n AND K33)+((n shr  2)  AND K33);
  n := (n AND KF1)+((n shr  4)  AND KF1);
  n := (n AND KF2)+((n shr  8)  AND KF2);
  n := (n AND KF4)+((n shr 16)  AND KF4);
  n := (n AND KF8)+ (n shr 32);
  result := n;
end;

function popcnt(n:Uint32):integer;overload;
var
  c,b : NativeUint;
begin
  b := n;
  c := (b shr 1) AND NativeUint(K55);   b := (b AND NativeUint(K55))+C;
  c := ((b shr 2)  AND NativeUint(K33));b := (b AND NativeUint(K33))+C;
  c:= ((b shr 4)  AND NativeUint(KF1)); b := (b AND NativeUint(KF1))+c;
  c := ((b shr 8)  AND NativeUint(KF2));b := (b AND NativeUint(KF2))+c;
  c := b shr 16; b := (b AND NativeUint(KF4))+ C;
  result := b;
end;

function popcnt(n:Uint16):integer;overload;
var
  c,b : NativeUint;
begin
  b := n;
  c := (b shr 1) AND NativeUint(K55);  b := (b AND NativeUint(K55))+C;
  c :=((b shr 2)  AND NativeUint(K33)); b := (b AND NativeUint(K33))+C;
  c:= ((b shr 4)  AND NativeUint(KF1)); b := (b AND NativeUint(KF1))+c;
  c :=  b shr 8; b := (b AND NativeUint(KF2))+c;
  result := b;
end;

function popcnt(n:Uint8):integer;overload;
var
  c,b : NativeUint;
begin
  b := n;
  c := (b shr 1) AND NativeUint(K55);  b := (b AND NativeUint(K55))+C;
  c :=((b shr 2)  AND NativeUint(K33));b := (b AND NativeUint(K33))+C;
  c:=   b shr 4;
  result := (b AND NativeUint(KF1))+c;
end;

Begin
End.


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

sub evil {
    my $i = 0;
    sub { $i++ while population_count($i) % 2; $i++ }
}

sub odious {
    my $i = 0;
    sub { $i++ until population_count($i) % 2; $i++ }
}

sub population_count {
    my $n = shift;
    my $c;
    for ($c = 0; $n; $n >>= 1) { $c += $n & 1 }
    $c
}

say join ' ', map { population_count 3**$_ } 0 .. 30 - 1;

my (@evil, @odious);
my ($evil, $odious) = (evil, odious);
push( @evil, $evil->() ), push @odious, $odious->() for 1 .. 30;

say "Evil   @evil";
say "Odious @odious";


with javascript_semantics
function pop_count(atom n)
    if n<0 then ?9/0 end if
    integer res = 0
    while n!=0 do
        res += and_bits(n,1)
        n = floor(n/2)
    end while
    return res
end function

printf(1,"3^x pop_counts:%v\n",{apply(apply(true,power,{3,tagset(29,0)}),pop_count)})

procedure eo(integer b0, string name)
    sequence s = repeat(0,30)
    integer k=0, l=1
    while l<=30 do
        if and_bits(pop_count(k),1)=b0 then
            s[l] = k
            l += 1
        end if
        k += 1
    end while
    printf(1,"%s numbers:%v\n",{name,s})
end procedure
eo(0,"  evil")
eo(1,"odious")


function convertToBinary($integer) {
    $binary = "";

    do {
        $quotient = (int) ($integer / 2);
        $binary .= $integer % 2;
        $integer = $quotient;
    } while ($quotient > 0);

    return $binary;
}

function getPopCount($integer) {
    $binary = convertToBinary($integer);
    $offset = 0;
    $popCount = 0;

    do {
        $pos = strpos($binary, "1", $offset);
        if($pos !== FALSE) $popCount++;
        $offset = $pos + 1;
    } while ($pos !== FALSE);

    return $popCount;
}

function print3PowPopCounts() {
    for ($p = 0; $p < 30; $p++) {
        echo " " . getPopCount(3 ** $p);
    }
}

function printFirst30Evil() {
    $counter = 0;
    $pops = 0;

    while ($pops < 30) {
        $popCount = getPopCount($counter);
        if ($popCount % 2 == 0)  {
            echo " " . $counter;
            $pops++;
        }
        $counter++;
    }
}

function printFirst30Odious() {
    $counter = 1;
    $pops = 0;

    while ($pops < 30) {
        $popCount = getPopCount($counter);
        if ($popCount % 2 != 0)  {
            echo " " . $counter;
            $pops++;
        }
        $counter++;
    }
}

echo "3 ^ x pop counts:";
print3PowPopCounts();

echo "\nfirst 30 evil numbers:";
printFirst30Evil();

echo "\nfirst 30 odious numbers:";
printFirst30Odious();


go =>
  println(powers_of_three=[pop_count(3**I) : I in 0..29]),
  println('evil_numbers   '=take_n($evil_number, 30,0)),
  println('odious_numbers '=take_n($odious_number, 30,0)),
  nl.

% Get the first N numbers that satisfies function F, starting with S
take_n(F,N,S) = L =>
  I = S,
  C = 0,
  L = [],
  while(C < N)
    if call(F,I) then
       L := L ++ [I],
       C := C + 1
    end,
    I := I + 1
  end.

evil_number(N) => pop_count(N) mod 2 == 0.
odious_number(N) => pop_count(N) mod 2 == 1.

pop_count(N) = sum([1: I in N.to_binary_string(), I = '1']).


(de popz (N)
   (cnt
      '((N) (= "1" N))
      (chop (bin N)) ) )

(println
   'pops:
   (mapcar
      '((N) (popz (** 3 N)))
      (range 0 29) ) )
(setq N -1)
(println
   'evil:
   (make
      (for (C 0 (> 30 C))
         (unless (bit? 1 (popz (inc 'N)))
            (link N)
            (inc 'C) ) ) ) )
(setq N -1)
(println
   'odio:
   (make
      (for (C 0 (> 30 C))
         (when (bit? 1 (popz (inc 'N)))
            (link N)
            (inc 'C) ) ) ) )


function pop-count($n) {
    (([Convert]::ToString($n, 2)).toCharArray() | where {$_ -eq '1'}).count
}
"pop_count 3^n: $(1..29 | foreach -Begin {$n = 1; (pop-count $n)} -Process {$n = 3*$n; (pop-count $n)} )"
"even pop_count: $($m = $n = 0; while($m -lt 30) {if(0 -eq ((pop-count $n)%2)) {$m += 1; $n}; $n += 1} )"
"odd pop_count: $($m = $n = 0; while($m -lt 30) {if(1 -eq ((pop-count $n)%2)) {$m += 1; $n}; $n += 1} )"


Procedure.i PopCount(n.i) : ProcedureReturn CountString(Bin(Pow(3,n)),"1") : EndProcedure
Procedure   PutR(v.i)     : Print(RSet(Str(v),3))                          : EndProcedure

If OpenConsole()
  NewList ne() : NewList no()
  i=0
  While ListSize(ne())+ListSize(no())<60
    If CountString(Bin(i),"1")%2=0 : AddElement(ne()) : ne()=i
    Else                           : AddElement(no()) : no()=i : EndIf
    i+1
  Wend
  Print("3^i [i=0..29]") : For i=0 To 29 : PutR(PopCount(i)) : Next : PrintN("")
  Print("Evil numbers ") : ForEach ne()  : PutR(ne())        : Next : PrintN("")
  Print("Odious numb..") : ForEach no()  : PutR(no())        : Next : Input()
EndIf


  [ 0 swap
    [ dup while
      dup 1 &
      rot + swap
      1 >>
      again ]
    drop ]                    is popcount       ( n --> n )

  [ 1 & ]                     is odd            ( n --> b )

  [ odd not ]                 is even           ( n --> b )

  [ ]'[ temp put 0
    [ over while
        [ dup popcount
          temp share do
          if [ dup echo sp
               dip [ 1 - ] ]
           1+ ]
        again ]
    2drop temp release ]      is echopopwith    ( n -->   )

  say "Population counts of the first thirty powers of 3." cr
  30 times
    [ 3 i^ ** popcount echo sp ] cr
  cr
  say "The first thirty evil numbers." cr
  30 echopopwith even cr
  cr
  say "The first thirty odious numbers." cr
  30 echopopwith odd cr


library(bit64)
popCount <- function(x) sum(as.numeric(strsplit(as.bitstring(as.integer64(x)), "")[[1]]))
finder <- function()
{
  odious <- evil <- integer(0)
  x <- odiousLength <- evilLength <- 0
  while(evilLength + odiousLength != 60)#We could be smarter, but this condition suffices.
  {
    if(popCount(x) %% 2 == 0) evil[evilLength + 1] <- x else odious[odiousLength + 1] <- x
    x <- x + 1
    evilLength <- length(evil)
    odiousLength <- length(odious)
  }
  cat("The pop count of the 1st 30 powers of 3 are:", sapply(3^(0:29), popCount), "\n")
  cat("The first 30 evil numbers are:", evil, "\n")
  cat("The first 30 odious numbers are:", odious)
}
finder()


#lang racket
;; Positive version from "popcount_4" in:
;;   https://en.wikipedia.org/wiki/Hamming_weight#Efficient_implementation
;; negative version follows R6RS definition documented in:
;;   http://docs.racket-lang.org/r6rs/r6rs-lib-std/r6rs-lib-Z-H-12.html?q=bitwise-bit#node_idx_1074
(define (population-count n)
  (if (negative? n)
      (bitwise-not (population-count (bitwise-not n)))
      (let inr ((x n) (rv 0))
        (if (= x 0) rv (inr (bitwise-and x (sub1 x)) (add1 rv))))))

(define (evil? x)
  (and (not (negative? x))
       (even? (population-count x))))

(define (odious? x)
  (and (positive? x)
       (odd? (population-count x))))

(define tasks
  (list
   "display the pop count of the 1st thirty powers of 3 (3^0, 3^1, 3^2, 3^3, 3^4, ...)."
   (for/list ((i (in-range 30))) (population-count (expt 3 i)))
   "display the 1st thirty evil numbers."
   (for/list ((_ (in-range 30)) (e (sequence-filter evil? (in-naturals)))) e)
   "display the 1st thirty odious numbers."
   (for/list ((_ (in-range 30)) (o (sequence-filter odious? (in-naturals)))) o)))

(for-each displayln tasks)

(module+ test
  (require rackunit)
  (check-equal?
   (for/list ((p (sequence-map population-count (in-range 16)))) p)
   '(0 1 1 2 1 2 2 3 1 2 2 3 2 3 3 4))
  (check-true (evil? 0) "0 has just *got* to be evil")
  (check-true (evil? #b011011011) "six bits... truly evil")
  (check-false (evil? #b1011011011) "seven bits, that's odd!")
  (check-true (odious? 1) "the least odious number")
  (check-true (odious? #b1011011011) "seven (which is odd) bits")
  (check-false (odious? #b011011011) "six bits... is evil"))


sub population-count(Int $n where * >= 0) { [+] $n.base(2).comb }

say map &population-count, 3 «**« ^30;
say "Evil: ", (grep { population-count($_) %% 2 }, 0 .. *)[^30];
say "Odious: ", (grep { population-count($_)  % 2 }, 0 .. *)[^30];


/*REXX program counts the number of "one" bits in the binary version of a decimal number*/
/*─────────────────── and also generates a specific number of  EVIL and ODIOUS  numbers.*/
parse arg N B .                                  /*get optional arguments from the C.L. */
if N==''  |  N==","   then N= 30                 /*N not specified?   Then use default. */
if B==''  |  B==","   then B=  3                 /*B  "      "          "   "      "    */
numeric digits 2000                              /*be able to handle  gihugeic  numbers.*/
numeric digits max(20, length(B**N) )            /*whittle the  precision  down to size.*/
$=                                               /* [↑]  a little calculation for sizing*/
     do j=0  for  N;   $= $ popCount(B**j)       /*generate N popCounts for some powers.*/
     end   /*j*/                                 /* [↑]  append popCount to the $ list. */
                                                 /* [↓]  display popCounts of "3" powers*/
call showList  'popCounts of the powers of'  B   /*display the list with a header/title.*/

     do j=0  until  #>=N                         /*generate   N   evil  numbers.        */
     if popCount(j) // 2  then iterate           /*if  odd population count, skip it.   */
     #= # + 1;      $= $ j                       /*bump evil # count;  add it to $ list.*/
     end   /*j*/                                 /* [↑]  build a list of evil numbers.  */
                                                 /* [↓]  display the evil number list.  */
call showList  'evil numbers'                    /*display the  $  list with a header.  */

     do j=0  until  #>=N                         /*generate   N   odious  numbers.      */
     if popCount(j) // 2 ==0  then iterate       /*if even population count, then skip. */
     #= # + 1;      $=$ j                        /*bump odious # count;  add to $ list. */
     end   /*j*/                                 /* [↑]  build a list of odious numbers.*/
                                                 /* [↓]  display the odious number list.*/
call showList  'odious numbers'                  /*display the   $  list with a header. */
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
d2b:      return word( strip( x2b( d2x( arg(1) ) ), 'L', 0)  0, 1)        /*dec ──► bin.*/
popCount: return length( space( translate( d2b(arg(1) ), , 0), 0) )       /*count ones. */
showList: say;   say 'The 1st'   N   arg(1)":";   say strip($);     #= 0;     $=;   return


# Project : Population count

odds = []
evens = []
pows = []

for n = 0 to 59
      if n < 30 add(pows, onesCount(pow(3, n))) ok
      num = onesCount(n)
      if num & 1 = 0 add(evens, n) else add(odds, n) ok
next

showOne("3^x:", pows)
showOne("Evil numbers:", evens)
showOne("Odious numbers:", odds)

func onesCount(b)
      c = 0 m = 50
      while b > 0
            p = pow(2, m)
            if b >= p b -= p c++ ok
            m--
      end return c

func arrayToStr(ary)
      res = "[" s = ", "
      for n = 1 to len(ary)
            if ary[n] < 10 res += " " ok
            if n = len(ary) s = "]" ok
            res += "" + ary[n] + s
      next return res

func showOne(title, ary)
      ? title
      ? arrayToStr(ary) + nl


class Integer

  def popcount
    digits(2).count(1)     #pre Ruby 2.4: self.to_s(2).count("1")
  end

  def evil?
    self >= 0 && popcount.even?
  end

end

puts "Powers of 3:",  (0...30).map{|n| (3**n).popcount}.join(' ')
puts "Evil:"  , 0.step.lazy.select(&:evil?).first(30).join(' ')
puts "Odious:", 0.step.lazy.reject(&:evil?).first(30).join(' ')


fn main() {
    let mut num = 1u64;
    let mut vec = Vec::new();
    for _ in 0..30 {
        vec.push(num.count_ones());
        num *= 3;
    }
    println!("pop count of 3^0, 3^1 ... 3^29:\n{:?}",vec);
    let mut even = Vec::new();
    let mut odd  = Vec::new();
    num = 1;
    while even.len() < 30 || odd.len() < 30 {
        match 0 == num.count_ones()%2 {
            true if even.len() < 30 => even.push(num),
            false if odd.len() < 30 => odd.push(num),
            _                       => {}
        }
        num += 1;
    }
    println!("\nFirst 30 even pop count:\n{:?}",even);
    println!("\nFirst 30 odd pop count:\n{:?}",odd);
}


import java.lang.Long.bitCount

object PopCount extends App {
  val nNumber = 30

  def powersThree(start: Long): LazyList[Long] = start #:: powersThree(start * 3L)

  println("Population count of 3ⁿ :")
  println(powersThree(1L).map(bitCount).take(nNumber).mkString(", "))

  def series(start: Long): LazyList[Long] = start #:: series(start + 1L)

  println("Evil numbers:")
  println(series(0L).filter(bitCount(_) % 2 == 0).take(nNumber).mkString(", "))

  println("Odious numbers:")
  println(series(0L).filter(bitCount(_) % 2 != 0).take(nNumber).mkString(", "))

}


$ include "seed7_05.s7i";

const func integer: popcount (in integer: n) is
    return card(bitset(n));

const proc: main is func
  local
    var integer: count is 0;
    var integer: num is 0;
  begin
    for num range 0 to 29 do
      write(popcount(3 ** num) <& " ");
    end for;
    writeln;
    write("evil:   ");
    for num range 0 to integer.last until count >= 30 do
      if not odd(popcount(num)) then
        write(num <& " ");
	incr(count);
      end if;
    end for;
    writeln;
    write("odious: ");
    count := 0;
    for num range 0 to integer.last until count >= 30 do
      if odd(popcount(num)) then
        write(num <& " ");
        incr(count);
      end if;
    end for;
    writeln;
  end func;


func population_count(n) { n.as_bin.count('1') }
say "#{0..29 «**« 3 «call« population_count -> join(' ')}"

var numbers = 60.of { |i|
    [i, population_count(i)]
}

say "Evil:   #{numbers.grep{_[1] %% 2}.map{.first}.join(' ')}"
say "Odious: #{numbers.grep{_[1] &  1}.map{.first}.join(' ')}"


func populationCount(n: Int) -> Int {
  guard n >= 0 else { fatalError() }

  return String(n, radix: 2).filter({ $0 == "1" }).count
}

let pows = (0...)
    .lazy
    .map({ Int(pow(3, Double($0))) })
    .map(populationCount)
    .prefix(30)

let evils = (0...)
    .lazy
    .filter({ populationCount(n: $0) & 1 == 0 })
    .prefix(30)

let odious = (0...)
    .lazy
    .filter({ populationCount(n: $0) & 1 == 1 })
    .prefix(30)

print("Powers:", Array(pows))
print("Evils:", Array(evils))
print("Odious:", Array(odious))


| Pop Count 3^i

 i
 if i < 30
    (3^i) x
    popcount x 63 x
    ~ x $r
    + $r $s
    + ' ' $s
    + i
    goif
 endif
 "' Pop Count 3^i : ' $s " []

| Evil Numbers

 i
 cnt
 if cnt < 30
    popcount i 7 x
    x:0:1 y
    if y <> 1
       + cnt
       ~ i $r
       + $r $e
       + ' ' $e
    endif
    + i
    goif
 endif
 "' Evil Numbers  : ' $e " []

| Odious Numbers

 i
 cnt
 if cnt < 30
    popcount i 7 x
    x:0:1 y
    if y = 1
       + cnt
       ~ i $r
       + $r $o
       + ' ' $o
    endif
    + i
    goif
 endif
 "' Odious Numbers : ' $o " []


package require Tcl 8.6

proc hammingWeight {n} {
    tcl::mathop::+ {*}[split [format %llb $n] ""]
}
for {set n 0;set l {}} {$n<30} {incr n} {
    lappend l [hammingWeight [expr {3**$n}]]
}
puts "p3: $l"
for {set n 0;set e [set o {}]} {[llength $e]<30||[llength $o]<30} {incr n} {
    lappend [expr {[hammingWeight $n]&1 ? "o" : "e"}] $n
}
puts "evil: [lrange $e 0 29]"
puts "odious: [lrange $o 0 29]"


popcount() {
    local -i n=$1
    (( n < 0 )) && return 1
    local ones=0
    while (( n > 0 )); do
        (( ones += n%2 ))
        (( n /= 2 ))
    done
    echo $ones
}

popcount_3s=()
n=1
for (( i=0; i<30; i++ )); do
    popcount_3s+=( $(popcount $n) )
    (( n *= 3 ))
done
echo "powers of 3 popcounts: ${popcount_3s[*]}"

evil=()
odious=()
n=0
while (( ${#evil[@]} < 30 || ${#odious[@]} < 30 )); do
    p=$( popcount $n )
    if (( $p%2 == 0 )); then
        evil+=( $n )
    else
        odious+=( $n )
    fi
    (( n++ ))
done
echo "evil nums:   ${evil[*]:0:30}"
echo "odious nums: ${odious[*]:0:30}"


Sub Population_count()
    nmax = 30
    b = 3
    n = 0: List = "": bb = 1
    For i = 0 To nmax - 1
        List = List & " " & popcount(bb)
        bb = bb * b
    Next 'i
    Debug.Print "popcounts of the powers of " & b
    Debug.Print List
    For j = 0 To 1
        If j = 0 Then c = "evil numbers" Else c = "odious numbers"
        n = 0: List = "": i = 0
        While n < nmax
            If (popcount(i) Mod 2) = j Then
                n = n + 1
                List = List & " " & i
            End If
            i = i + 1
        Wend
        Debug.Print c
        Debug.Print List
    Next 'j
End Sub 'Population_count

Private Function popcount(x)
    Dim y, xx, xq, xr
    xx = x
    While xx > 0
        xq = Int(xx / 2)
        xr = xx - xq * 2
        If xr = 1 Then y = y + 1
        xx = xq
    Wend
    popcount = y
End Function 'popcount


' Population count - VBScript - 10/05/2019
	nmax=30
	b=3
	n=0: list="": bb=1
	For i=0 To nmax-1
		list=list & " " & popcount(bb)
		bb=bb*b
	Next 'i
	Msgbox list,,"popcounts of the powers of " & b
	For j=0 to 1
		If j=0 Then c="evil numbers": Else c="odious numbers"
		n=0: list="": i=0
		While n<nmax
			If (popcount(i) Mod 2)=j Then
				n=n+1
				list=list & " " & i
			End If
			i=i+1
		Wend
		Msgbox list,,c
	Next 'j

Function popcount(x)
	Dim y,xx,xq,xr
	xx=x
	While xx>0
		xq=Int(xx/2)
		xr=xx-xq*2
		If xr=1 Then y=y+1
		xx=xq
	Wend
	popcount=y
End Function 'popcount


Imports System.Console, System.Diagnostics

Module Module1

  Dim i As Integer, eo As Boolean

  Function PopCnt(n As Long) As Integer
    Return Convert.ToString(n, 2).ToCharArray().Where(Function(x) x = "1").Count()
  End Function

  Sub Aline(a As List(Of Integer), title As String)
    WriteLine("{0,-8}{1}", title, String.Join(" ", a.Take(30)))
  End Sub

  Sub Main(ByVal args As String())
    WriteLine("Population Counts:") : Dim t, e, o As New List(Of Integer)
    For c As Integer = 0 To 99
      If (PopCnt(c) And 1) = 0 Then e.Add(c) Else o.Add(c)
      If c < 30 Then t.Add(PopCnt(CLng(Math.Pow(3, c))))
    Next
    Aline(t, "3^n :") : Aline(e, "Evil:") : Aline(o, "Odious:")
    ' Extra:
    WriteLine(vbLf & "Pattern:{0}", Pattern(e, o))
    If Debugger.IsAttached Then ReadKey()
  End Sub

  ' support routines for pattern output
  Function Same(a As List(Of Integer)) As Boolean
    Return a(i) + 1 = a(i + 1)
  End Function

  Function Odd(a As List (Of Integer), b As List (Of Integer)) As Boolean
    eo = Not eo : If a(i) = b(i) + 1 Then i -= 1 : Return True
    Return False
  End Function

  Function SoO(a As List (Of Integer), b As List (Of Integer), c As String) As String
    Return If(Same(a), c(0), If(Odd(b, a), c(1), c(2)))
  End Function

  Function Either(a As List(Of Integer), b As List(Of Integer)) As String
    Return If(eo, SoO(a, b, "⌢↓↘"), SoO(b, a, "⌣↑↗"))
  End Function

  Function Pattern(a As List(Of Integer), b As List(Of Integer)) As String
    eo = a.Contains(0) : Dim res As New Text.StringBuilder
    For i = 0 To a.Count - 2 : res.Append(Either(a, b)) : Next
    Return res.ToString()
  End Function

End Module


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

var popCount = Fn.new { |n|
    var count = 0
    while (n != 0) {
        n = n & (n - 1)
        count = count + 1
    }
    return count
}

System.print("The population count of the first 30 powers of 3 is:")
var p3 = 1
for (i in 0..29) {
    System.write("%(popCount.call(p3)) ")
    p3 = p3 * 3
    if (i == 20) p3 = BigInt.new(p3)
}
var odious = []
System.print("\n\nThe first 30 evil numbers are:")
var count = 0
var n = 0
while (count < 30) {
    var pc = popCount.call(n)
    if (pc%2 == 0) {
        System.write("%(n) ")
        count = count + 1
    } else {
        odious.add(n)
    }
    n = n + 1
}
odious.add(n)
System.print("\n\nThe first 30 odious numbers are:")
Fmt.print("$d", odious)


print "Pop count (3^x): "

for i = 0 to 29
    print population(3^i);
next
print "\n"

print "Evil: "
EvilOdious(30)
print "\n"

print "Odious: "
EvilOdious(30, 1)
print "\n"

sub EvilOdious(limit, type)
    local i, count, eo

    repeat
        eo = mod(population(i), 2)
        if (type and eo) or (not type and not eo) count = count + 1 : print i;
        i = i + 1
    until(count = limit)
end sub

sub population(number)
    local i, binary$, popul

    binary$ = bin$(number)
    for i = 1 to len(binary$)
        popul = popul + val(mid$(binary$, i, 1))
    next
    return popul
end sub


n:=1; do(30){ print(n.num1s,","); n*=3 } println();

println("evil: ",[0..].filter(30,fcn(n){ n.num1s.isEven }).concat(","));

// now, as an iterator aka lazy:
println("odious: ",(0).walker(*).tweak(   // 0,1,2,3,4... iterator
   fcn(n){ if(n.num1s.isEven) Void.Skip else n }).walk(30).concat(","));


with Ada.Text_IO;  use Ada.Text_IO;

procedure Test_Polymorphic_Copy is
   package Base is
      type T is tagged null record;
      type T_ptr is access all T'Class;
      function Name (X : T) return String;
   end Base;
   use Base;

   package body Base is
      function Name (X : T) return String is
      begin
         return "T";
      end Name;
   end Base;

      -- The procedure knows nothing about S
   procedure Copier (X : T'Class) is
      Duplicate : T'Class := X;  -- A copy of X
   begin
      Put_Line ("Copied " & Duplicate.Name); -- Check the copy
   end Copier;

      -- The function knows nothing about S and creates a copy on the heap
   function Clone (X : T'Class) return T_ptr is
   begin
      return new T'Class(X);
   end Copier;

   package Derived is
      type S is new T with null record;
      overriding function Name (X : S) return String;
   end Derived;
   use Derived;

   package body Derived is
      function Name (X : S) return String is
      begin
         return "S";
      end Name;
   end Derived;

   Object_1 : T;
   Object_2 : S;
   Object_3 : T_ptr := Clone(T);
   Object_4 : T_ptr := Clone(S);
begin
   Copier (Object_1);
   Copier (Object_2);
   Put_Line ("Cloned " & Object_3.all.Name);
   Put_Line ("Cloned " & Object_4.all.Name);
end Test_Polymorphic_Copy;


class T {
    public function print {
        println ("class T")
    }
}

class S extends T {
    public function print {
        println ("class S")
    }
}

var t = new T()
var s = new S()
println ("before copy")
t.print()
s.print()

var tcopy = clone (t, false)
var scopy = clone (s, false)
println ("after copy")
tcopy.print()
scopy.print()


BEGIN
    # Algol 68 doesn't have classes and inheritence as such, however structures #
    # can contain procedures and different instances of a structure can have    #
    # different versons of the procedure                                        #
    # this allows us to simulate inheritence by creating structure instances    #
    # with different procedures                                                 #

    # the following declares a type (MODE) HORSE with two constructors, one for #
    # a standard horse and one for a zebra (the "derived class").               #
    # The standard horse has its print procedure set to thw print horse         #
    # procedure (the "base class" method). zebras get the print zebra procedure #
    # (the "derived class" method). A convenience operator (PRINT) is defined   #
    # to simplify calling the horse/zebra print method of its horse parameter   #
    # = this PRINT operator is independent of which actual print method the     #
    # horse has - it just saved typeing "( print OF h )( h )" everywhere we     #
    # need to call the print method (euivalent to h.print(h) in e.g. C, Java,   #
    # etc.)                                                                     #

    # "class" #
    MODE HORSE = STRUCT( STRING name, PROC(HORSE)VOID print );
    # constructors #
    PROC new horse   = ( STRING name )HORSE: ( name, print horse );
    PROC new zebra   = ( STRING name )HORSE: ( name, print zebra );
    # print methods: one for a standard horse and one for a zebra #
    PROC print horse = ( HORSE  h    )VOID: print( ( "horse: ", name OF h ) );
    PROC print zebra = ( HORSE  h    )VOID: print( ( "zebra: ", name OF h ) );
    # print operator #
    OP   PRINT       = ( HORSE  h    )VOID: ( print OF h )( h );

    # declare and construct some horses and zebras #
    HORSE h1 := new horse( "silver blaze" );
    HORSE z1 := new zebra( "stripy" );
    HORSE z2 := new zebra( "second zebra" );

    # show their values #
    PRINT h1; print( ( newline ) );
    PRINT z1; print( ( newline ) );
    PRINT z2; print( ( newline ) );
    print( ( "----", newline ) );

    # change the second zebra to be a copy of the first zebra #
    z2 := z1;
    PRINT z1; print( ( newline ) );
    PRINT z2; print( ( newline ) );
    print( ( "----", newline ) );

    # change the name of the first zebra leaving z2 unchanged #
    name OF z1 := "ed";
    PRINT z1; print( ( newline ) );
    PRINT z2; print( ( newline ) )
END


      INSTALL @lib$ + "CLASSLIB"

      REM Create parent class T:
      DIM classT{array#(0), setval, retval}
      DEF classT.setval (n%,v) classT.array#(n%) = v : ENDPROC
      DEF classT.retval (n%) = classT.array#(n%)
      PROC_class(classT{})

      REM Create class S derived from T, known only at run-time:
      RunTimeSize% = RND(100)
      DIM classS{array#(RunTimeSize%)}
      PROC_inherit(classS{}, classT{})
      DEF classS.retval (n%) = classS.array#(n%) ^ 2 : REM Overridden method
      PROC_class(classS{})

      REM Create an instance of class S:
      PROC_new(myobject{}, classS{})

      REM Now make a copy of the instance:
      DIM mycopy{} = myobject{}
      mycopy{} = myobject{}
      PROC_discard(myobject{})

      REM Test the copy (should print 123^2):
      PROC(mycopy.setval)(RunTimeSize%, 123)
      result% = FN(mycopy.retval)(RunTimeSize%)
      PRINT result%
      END


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

typedef struct object *BaseObj;
typedef struct sclass *Class;
typedef void (*CloneFctn)(BaseObj s, BaseObj clo);
typedef const char * (*SpeakFctn)(BaseObj s);
typedef void (*DestroyFctn)(BaseObj s);

typedef struct sclass {
    size_t csize;		/* size of the class instance */
    const char  *cname;		/* name of the class */
    Class  parent;		/* parent class */

    CloneFctn clone;		/* clone function */
    SpeakFctn speak;		/* speak function */
    DestroyFctn del;		/* delete the object */
} sClass;

typedef struct object {
    Class class;
} SObject;

static
BaseObj obj_copy( BaseObj s, Class c )
{
    BaseObj clo;
    if (c->parent)
        clo = obj_copy( s, c->parent);
    else
        clo = malloc( s->class->csize );

    if (clo)
        c->clone( s, clo );
    return clo;
}

static
void obj_del( BaseObj s, Class c )
{
    if (c->del)
        c->del(s);
    if (c->parent)
        obj_del( s, c->parent);
    else
        free(s);
}

BaseObj ObjClone( BaseObj s )
{ return obj_copy( s, s->class ); }

const char * ObjSpeak( BaseObj s )
{
    return s->class->speak(s);
}

void ObjDestroy( BaseObj s )
{ if (s) obj_del( s, s->class ); }

/* * * * * * */
static
void baseClone( BaseObj s, BaseObj clone)
{
    clone->class = s->class;
}

static
const char *baseSpeak(BaseObj s)
{
    return "Hello, I'm base object";
}

sClass boc = { sizeof(SObject), "BaseObj", NULL,
    &baseClone, &baseSpeak, NULL };
Class BaseObjClass = &boc;

/* * * * * * */
/* Dog - a derived class */

typedef struct sDogPart {
    double weight;
    char color[32];
    char name[24];
} DogPart;

typedef struct sDog *Dog;

struct sDog {
    Class   class;		// parent structure
    DogPart dog;
};

static
void dogClone( BaseObj s, BaseObj c)
{
    Dog src = (Dog)s;
    Dog clone = (Dog)c;
    clone->dog = src->dog;	/* no pointers so strncpys not needed */
}

static
const char *dogSpeak( BaseObj s)
{
    Dog d = (Dog)s;
    static char  response[90];
    sprintf(response, "woof! woof! My name is %s. I'm a %s %s",
            d->dog.name, d->dog.color, d->class->cname);
    return response;
}

sClass dogc = { sizeof(struct sDog), "Dog", &boc,
    &dogClone, &dogSpeak, NULL };
Class DogClass = &dogc;

BaseObj NewDog( const char *name, const char *color, double weight )
{
    Dog dog = malloc(DogClass->csize);
    if (dog) {
        DogPart *dogp = &dog->dog;
        dog->class = DogClass;
        dogp->weight = weight;
        strncpy(dogp->name, name, 23);
        strncpy(dogp->color, color, 31);
    }
    return (BaseObj)dog;
}

/* * * * * * * * * */
/* Ferret - a derived class */

typedef struct sFerretPart {
    char color[32];
    char name[24];
    int  age;
} FerretPart;

typedef struct sFerret *Ferret;

struct sFerret {
    Class   class;		// parent structure
    FerretPart ferret;
};

static
void ferretClone( BaseObj s, BaseObj c)
{
    Ferret src = (Ferret)s;
    Ferret clone = (Ferret)c;
    clone->ferret = src->ferret;  /* no pointers so strncpys not needed */
}

static
const char *ferretSpeak(BaseObj s)
{
    Ferret f = (Ferret)s;
    static char  response[90];
    sprintf(response, "My name is %s. I'm a %d mo. old %s wiley %s",
            f->ferret.name, f->ferret.age, f->ferret.color,
            f->class->cname);
    return response;
}

sClass ferretc = { sizeof(struct sFerret), "Ferret", &boc,
    &ferretClone, &ferretSpeak, NULL };
Class FerretClass = &ferretc;

BaseObj NewFerret( const char *name, const char *color, int age )
{
    Ferret ferret = malloc(FerretClass->csize);
    if (ferret) {
        FerretPart *ferretp = &(ferret->ferret);
        ferret->class = FerretClass;
        strncpy(ferretp->name, name, 23);
        strncpy(ferretp->color, color, 31);
        ferretp->age = age;
    }
    return (BaseObj)ferret;
}

/* * Now you really understand why Bjarne created C++ * */

int main()
{
    BaseObj  o1;
    BaseObj  kara = NewFerret( "Kara", "grey", 15 );
    BaseObj  bruce = NewDog("Bruce", "yellow", 85.0 );
    printf("Ok created things\n");

    o1 = ObjClone(kara );
    printf("Karol says %s\n", ObjSpeak(o1));
    printf("Kara says %s\n", ObjSpeak(kara));
    ObjDestroy(o1);

    o1 = ObjClone(bruce );
    strncpy(((Dog)o1)->dog.name, "Donald", 23);
    printf("Don says %s\n", ObjSpeak(o1));
    printf("Bruce says %s\n", ObjSpeak(bruce));
    ObjDestroy(o1);
    return 0;
}


using System;

class T
{
    public virtual string Name()
    {
        return "T";
    }

    public virtual T Clone()
    {
        return new T();
    }
}

class S : T
{
    public override string Name()
    {
        return "S";
    }

    public override T Clone()
    {
        return new S();
    }
}

class Program
{
    static void Main()
    {
        T original = new S();
        T clone = original.Clone();

        Console.WriteLine(original.Name());
        Console.WriteLine(clone.Name());
    }
}


#include <iostream>

class T
{
public:
  virtual void identify() { std::cout << "I am a genuine T" << std::endl; }
  virtual T* clone() { return new T(*this); }
  virtual ~T() {}
};

class S: public T
{
public:
  virtual void identify() { std::cout << "I am an S" << std::endl; }
  virtual S* clone() { return new S(*this); }
};

class X // the class of the object which contains a T or S
{
public:
  // by getting the object through a pointer to T, X cannot know if it's an S or a T
  X(T* t): member(t) {}

  // copy constructor
  X(X const& other): member(other.member->clone()) {}

  // copy assignment operator
  X& operator=(X const& other)
  {
    T* new_member = other.member->clone();
    delete member;
    member = new_member;
  }

  // destructor
  ~X() { delete member; }

  // check what sort of object it contains
  void identify_member() { member->identify(); }

private:
  T* member;
};

int main()
{
  X original(new S);      // construct an X and give it an S,
  X copy = original;      // copy it,
  copy.identify_member(); // and check what type of member it contains
}


(defstruct super foo)

(defstruct (sub (:include super)) bar)

(defgeneric frob (thing))

(defmethod frob ((super super))
  (format t "~&Super has foo = ~w." (super-foo super)))

(defmethod frob ((sub sub))
  (format t "~&Sub has foo = ~w, bar = ~w."
          (sub-foo sub) (sub-bar sub)))


class T {
    override string toString() { return "I'm the instance of T"; }
    T duplicate() { return new T; }
}

class S : T {
    override string toString() { return "I'm the instance of S"; }

    override T duplicate() { return new S; }
}

void main () {
    import std.stdio;
    T orig = new S;
    T copy = orig.duplicate();

    writeln(orig);
    writeln(copy);
}


program PolymorphicCopy;

type
  T = class
    function Name:String; virtual;
    function Clone:T; virtual;
  end;

  S = class(T)
    function Name:String; override;
    function Clone:T; override;
  end;

function T.Name :String; begin Exit('T')     end;
function T.Clone:T;      begin Exit(T.Create)end;

function S.Name :String; begin Exit('S')     end;
function S.Clone:T;      begin Exit(S.Create)end;

procedure Main;
var
  Original, Clone :T;
begin
  Original := S.Create;
  Clone    := Original.Clone;

  WriteLn(Original.Name);
  WriteLn(Clone.Name);
end;

begin
  Main;
end.


INCLUDE "H6:REALMATH.ACT"

INT ARRAY SinTab=[
  0 4 9 13 18 22 27 31 36 40 44 49 53 58 62 66 71 75 79 83
  88 92 96 100 104 108 112 116 120 124 128 132 136 139 143
  147 150 154 158 161 165 168 171 175 178 181 184 187 190
  193 196 199 202 204 207 210 212 215 217 219 222 224 226
  228 230 232 234 236 237 239 241 242 243 245 246 247 248
  249 250 251 252 253 254 254 255 255 255 256 256 256 256]

INT FUNC Sin(INT a)
  WHILE a<0 DO a==+360 OD
  WHILE a>360 DO a==-360 OD
  IF a<=90 THEN
    RETURN (SinTab(a))
  ELSEIF a<=180 THEN
    RETURN (SinTab(180-a))
  ELSEIF a<=270 THEN
    RETURN (-SinTab(a-180))
  ELSE
    RETURN (-SinTab(360-a))
  FI
RETURN (0)

INT FUNC Cos(INT a)
RETURN (Sin(a-90))

PROC DrawSpiral(INT x0,y0)
  INT i,angle,x,y,tmp
  REAL rx,ry,len,dlen,r1,r2,r3,r256

  IntToReal(x0,rx)
  IntToReal(y0,ry)
  ValR("1.9",len)
  ValR("1.14",dlen)
  IntToReal(256,r256)
  angle=0
  Plot(x0,y0)
  FOR i=1 TO 150
  DO
    tmp=Cos(angle)
    IntToRealForNeg(tmp,r1)
    RealDiv(r1,r256,r2)
    RealMult(r2,len,r1)
    RealAdd(rx,r1,r2)
    RealAssign(r2,rx)

    tmp=Sin(angle)
    IntToRealForNeg(tmp,r1)
    RealDiv(r1,r256,r2)
    RealMult(r2,len,r1)
    RealAdd(ry,r1,r2)
    RealAssign(r2,ry)

    x=RealToInt(rx)
    y=RealToInt(ry)
    DrawTo(x,y)

    RealAdd(len,dlen,r1)
    RealAssign(r1,len)
    angle==+123
    IF angle>360 THEN
      angle==-360
    FI
  OD
RETURN

PROC Main()
  BYTE CH=$02FC,COLOR1=$02C5,COLOR2=$02C6

  Graphics(8+16)
  Color=1
  COLOR1=$0C
  COLOR2=$02

  DrawSpiral(160,96)

  DO UNTIL CH#$FF OD
  CH=$FF
RETURN


def deSubgraphKit := <elib:serial.deSubgraphKit>

def copy(object) {
    return deSubgraphKit.recognize(object, deSubgraphKit.makeBuilder())
}


(lib 'types)
(lib 'struct)

(struct T (integer:x)) ;; super class
(struct S T (integer:y)) ;; sub class
(struct K (T:box)) ;; container class, box must be of type T, or derived

(define k-source (K (S 33 42)))
(define k-copy (copy k-source))

k-source
    → #<K> (#<S> (33 42)) ;; new container, with a S in box
k-copy
    → #<K> (#<S> (33 42)) ;; copied S type

(set-S-y! (K-box k-source) 666) ;; modify k-source.box.y

k-source
    → #<K> (#<S> (33 666)) ;; modified
k-copy
    → #<K> (#<S> (33 42))  ;; unmodified

(K "string-inside") ;; trying to put a string in the container box
😡 error: T : type-check failure : string-inside → 'K:box'


import extensions;

class T
{
    Name = "T";

    T clone() = new T();
}

class S : T
{
    Name = "S";

    T clone() = new S();
}

public program()
{
    T original := new S();
    T clone := original.clone();

    console.printLine(original.Name);
    console.printLine(clone.Name)
}


If !pToken := Gdip_Startup()
{
    MsgBox, 48, gdiplus error!, Gdiplus failed to start. Please ensure you have gdiplus on your system
    ExitApp
}

OnExit, Exit
gdip1()

incr := 0
π := 3.141592653589793
loop
{
    incr := Mod(incr + 0.05, 360)
    x1 := Width/2
    y1 := Height/2
    length := 5
    angle := incr
    Gdip_FillRoundedRectangle(G, pBrush, 0, 0, Width, Height, 0)
    loop 150
    {
        x2 := x1 + length * Cos(angle * π/180)
        y2 := y1 + length * Sin(angle * π/180)
        Gdip_DrawLine(G, pPen, x1, y1, x2, y2)
        x1 := x2
        y1 := y2
        length := length + 3
        angle := Mod(angle + incr, 360)
    }
    UpdateLayeredWindow(hwnd1, hdc, -1, -1, Width, Height)
    Sleep 25
}
return
;----------------------------------------------------------------
Esc:: Pause, toggle
^Esc::ExitApp
;----------------------------------------------------------------
gdip1(){
    global
    Width := A_ScreenWidth+1, Height := A_ScreenHeight+1
    Gui, 1: -Caption +E0x80000 +LastFound +OwnDialogs +Owner +AlwaysOnTop
    Gui, 1: Show, NA
    hwnd1 := WinExist()
    hbm := CreateDIBSection(Width, Height)
    hdc := CreateCompatibleDC()
    obm := SelectObject(hdc, hbm)
    G := Gdip_GraphicsFromHDC(hdc)
    Gdip_SetSmoothingMode(G, 4)
    pBrush := Gdip_BrushCreateSolid("0xFF000000")
    pPen := Gdip_CreatePen("0xFF00FF00", 1)
}
;----------------------------------------------------------------
gdip2(){
    global
    Gdip_DeletePen(pPen)
    Gdip_DeleteBrush(pBrush)
    SelectObject(hdc, obm)
    DeleteObject(hbm)
    DeleteDC(hdc)
    Gdip_DeleteGraphics(G)
}
;----------------------------------------------------------------
Exit:
gdip2()
Gdip_Shutdown(pToken)
ExitApp
Return
;----------------------------------------------------------------


#include<graphics.h>
#include<math.h>

#define factor M_PI/180
#define LAG 1000

void polySpiral(int windowWidth,int	windowHeight){
	int incr = 0, angle, i, length;
	double x,y,x1,y1;

	while(1){
		incr = (incr + 5)%360;

		x = windowWidth/2;
		y = windowHeight/2;

		length = 5;
		angle = incr;

		for(i=1;i<=150;i++){
			x1 = x + length*cos(factor*angle);
			y1 = y + length*sin(factor*angle);
			line(x,y,x1,y1);

			length += 3;

			angle = (angle + incr)%360;

			x = x1;
			y = y1;
		}
		delay(LAG);
		cleardevice();
	}
}

int main()
{
	initwindow(500,500,"Polyspiral");

	polySpiral(500,500);

	closegraph();

	return 0;
}


type T() =
  // expose protected MemberwiseClone method (and downcast the result)
  member x.Clone() = x.MemberwiseClone() :?> T
  // virtual method Print with default implementation
  abstract Print : unit -> unit
  default x.Print() = printfn "I'm a T!"

type S() =
  inherit T()
  override x.Print() = printfn "I'm an S!"

let s = new S()
let s2 = s.Clone()  // the static type of s2 is T, but it "points" to an S
s2.Print() // prints "I'm an S!"


USING: classes kernel prettyprint serialize ;
TUPLE: A ;
TUPLE: C < A ;
: serial-clone ( obj -- obj' ) object>bytes bytes>object ;

C new
[ clone ]
[ serial-clone ] bi [ class . ] [email protected]


include lib/memcell.4th
include 4pp/lib/foos.4pp
                                       ( a1 -- a2)
:token fork dup allocated dup (~~alloc) swap >r swap over r> smove ;
                                       \ allocate an empty object
:: T()                                 \ super class T
   class
     method: print                     \ print message
     method: clone                     \ clone yourself
   end-class {
                                       \ implementing methods
     :method { ." class T" cr } ; defines print
     fork defines clone                ( -- addr)
   }
;

:: S()                                 \ class S
   extends T()                         \ derived from T
   end-extends {                       \ print message
     :method { ." class S" cr } ; defines print
   }                                   \ clone yourself
;

new T() t                              \ create a new object t
new S() s                              \ create a new object s

." before copy" cr
t => print                             \ use "print" methods
s => print

t => clone to tcopy                    \ cloning t, spawning tcopy
s => clone to scopy                    \ cloning s, spawning scopy

." after copy" cr
tcopy => print                         \ use "print" methods
scopy => print


!-----------------------------------------------------------------------
!Module polymorphic_copy_example_module
!-----------------------------------------------------------------------
module polymorphic_copy_example_module
   implicit none
   private ! all by default
   public :: T,S

   type, abstract :: T
   contains
      procedure (T_procedure1), deferred, pass :: identify
      procedure (T_procedure2), deferred, pass :: duplicate
   end type T

   abstract interface
      subroutine T_procedure1(this)
         import  :: T
         class(T), intent(inout) :: this
      end subroutine T_procedure1
      function T_procedure2(this) result(Tobj)
         import  :: T
         class(T), intent(inout) :: this
         class(T), allocatable :: Tobj
      end function T_procedure2
   end interface

   type, extends(T) :: S
   contains
      procedure, pass :: identify
      procedure, pass :: duplicate
   end type S

 contains

   subroutine  identify(this)
      implicit none
      class(S), intent(inout) :: this
      write(*,*) "S"
   end subroutine identify

   function duplicate(this) result(obj)
      class(S), intent(inout) :: this
      class(T), allocatable :: obj
      allocate(obj, source = S())
   end function duplicate

end module polymorphic_copy_example_module

!-----------------------------------------------------------------------
!Main program test
!-----------------------------------------------------------------------
program    test
   use polymorphic_copy_example_module
   implicit none

   class(T), allocatable :: Sobj
   class(T), allocatable :: Sclone

   allocate(Sobj, source = S())
   allocate(Sclone, source = Sobj % duplicate())

   call Sobj % identify()
   call Sclone % identify()

end program test


using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
using System.Windows.Threading;

namespace Polyspiral
{
    public partial class Form1 : Form
    {
        private double inc;

        public Form1()
        {
            Width = Height = 640;
            StartPosition = FormStartPosition.CenterScreen;
            SetStyle(
                ControlStyles.AllPaintingInWmPaint |
                ControlStyles.UserPaint |
                ControlStyles.DoubleBuffer,
                true);

            var timer = new DispatcherTimer();
            timer.Tick += (s, e) => { inc = (inc + 0.05) % 360; Refresh(); };
            timer.Interval = new TimeSpan(0, 0, 0, 0, 40);
            timer.Start();
        }

        private void DrawSpiral(Graphics g, int len, double angleIncrement)
        {
            double x1 = Width / 2;
            double y1 = Height / 2;
            double angle = angleIncrement;

            for (int i = 0; i < 150; i++)
            {
                double x2 = x1 + Math.Cos(angle) * len;
                double y2 = y1 - Math.Sin(angle) * len;
                g.DrawLine(Pens.Blue, (int)x1, (int)y1, (int)x2, (int)y2);
                x1 = x2;
                y1 = y2;

                len += 3;

                angle = (angle + angleIncrement) % (Math.PI * 2);
            }
        }

        protected override void OnPaint(PaintEventArgs args)
        {
            var g = args.Graphics;
            g.SmoothingMode = SmoothingMode.AntiAlias;
            g.Clear(Color.White);

            DrawSpiral(g, 5, ToRadians(inc));
        }

        private double ToRadians(double angle)
        {
            return Math.PI * angle / 180.0;
        }
    }
}


#include <windows.h>
#include <sstream>
#include <ctime>

const float PI = 3.1415926536f, TWO_PI = 2.f * PI;
class vector2
{
public:
    vector2( float a = 0, float b = 0 ) { set( a, b ); }
    void set( float a, float b ) { x = a; y = b; }
    void rotate( float r ) {
        float _x = x, _y = y,
               s = sinf( r ), c = cosf( r ),
               a = _x * c - _y * s, b = _x * s + _y * c;
        x = a; y = b;
    }
    vector2 add( const vector2& v ) {
        x += v.x; y += v.y;
        return *this;
    }
    float x, y;
};
class myBitmap
{
public:
    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}
    ~myBitmap(){
        DeleteObject( pen );
        DeleteObject( brush );
        DeleteDC( hdc );
        DeleteObject( bmp );
    }
    bool create( int w, int h ){
        BITMAPINFO    bi;
        ZeroMemory( &bi, sizeof( bi ) );
        bi.bmiHeader.biSize        = sizeof( bi.bmiHeader );
        bi.bmiHeader.biBitCount    = sizeof( DWORD ) * 8;
        bi.bmiHeader.biCompression = BI_RGB;
        bi.bmiHeader.biPlanes      = 1;
        bi.bmiHeader.biWidth       =  w;
        bi.bmiHeader.biHeight      = -h;

        HDC dc = GetDC( GetConsoleWindow() );
        bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );
        if( !bmp ) return false;

        hdc = CreateCompatibleDC( dc );
        SelectObject( hdc, bmp );
        ReleaseDC( GetConsoleWindow(), dc );

        width = w; height = h;
        return true;
    }
    void clear( BYTE clr = 0 ){
        memset( pBits, clr, width * height * sizeof( DWORD ) );
    }
    void setBrushColor( DWORD bClr ){
        if( brush ) DeleteObject( brush );
        brush = CreateSolidBrush( bClr );
        SelectObject( hdc, brush );
    }
    void setPenColor( DWORD c ){
        clr = c; createPen();
    }
    void setPenWidth( int w ){
        wid = w; createPen();
    }
    void saveBitmap( std::string path ){
        BITMAPFILEHEADER fileheader;
        BITMAPINFO       infoheader;
        BITMAP           bitmap;
        DWORD            wb;

        GetObject( bmp, sizeof( bitmap ), &bitmap );
        DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];
        ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );
        ZeroMemory( &infoheader, sizeof( BITMAPINFO ) );
        ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );

        infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;
        infoheader.bmiHeader.biCompression = BI_RGB;
        infoheader.bmiHeader.biPlanes = 1;
        infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );
        infoheader.bmiHeader.biHeight = bitmap.bmHeight;
        infoheader.bmiHeader.biWidth = bitmap.bmWidth;
        infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );

        fileheader.bfType    = 0x4D42;
        fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );
        fileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;

        GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );

        HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );
        WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );
        WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );
        WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );
        CloseHandle( file );

        delete [] dwpBits;
    }
    HDC getDC() const     { return hdc; }
    int getWidth() const  { return width; }
    int getHeight() const { return height; }
private:
    void createPen(){
        if( pen ) DeleteObject( pen );
        pen = CreatePen( PS_SOLID, wid, clr );
        SelectObject( hdc, pen );
    }
    HBITMAP bmp; HDC hdc;
    HPEN pen; HBRUSH brush;
    void *pBits; int width, height, wid;
    DWORD clr;
};
int main( int argc, char* argv[] ) {
    srand( unsigned( time( 0 ) ) );
    myBitmap bmp;
    bmp.create( 600, 600 ); bmp.clear();
    HDC dc = bmp.getDC();
    float fs = ( TWO_PI ) / 100.f;
    int index = 0;
    std::string a = "f://users//images//test", b;
    float ang, len;
    vector2 p1, p2;

    for( float step = 0.1f; step < 5.1f; step += .05f ) {
        ang = 0; len = 2;
        p1.set( 300, 300 );
        bmp.setPenColor( RGB( rand() % 50 + 200, rand() % 300 + 220, rand() % 50 + 200 ) );
        for( float xx = 0; xx < TWO_PI; xx += fs ) {
            MoveToEx( dc, (int)p1.x, (int)p1.y, NULL );
            p2.set( 0, len ); p2.rotate( ang ); p2.add( p1 );
            LineTo( dc, (int)p2.x, (int)p2.y );
            p1 = p2; ang += step; len += step;
        }
        std::ostringstream ss; ss << index++;
        b = a + ss.str() + ".bmp";
        bmp.saveBitmap( b );
        bmp.clear();
    }
    return 0;
}


package main

import (
    "fmt"
    "reflect"
)

// interface types provide polymorphism, but not inheritance.
type i interface {
    identify() string
}

// "base" type
type t float64

// "derived" type.  in Go terminology, it is simply a struct with an
// anonymous field.  fields and methods of anonymous fields however,
// can be accessed without additional qualification and so are
// "inherited" in a sense.
type s struct {
    t
    kōan string
}

// another type with an "embedded" t field.  (t is the *type*, this field
// has no *name*.)
type r struct {
    t
    ch chan int
}

// a method on t.  this method makes t satisfy interface i.
// since a t is embedded in types s and r, they automatically "inherit"
// the method.
func (x t) identify() string {
    return "I'm a t!"
}

// the same method on s.  although s already satisfied i, calls to identify
// will now find this method rather than the one defined on t.
// in a sense it "overrides" the method of the "base class."
func (x s) identify() string {
    return "I'm an s!"
}

func main() {
    // three variables with different types, initialized from literals.
    var t1 t = 5
    var s1 s = s{6, "one"}
    var r1 r = r{t: 7}

    // variables declared with the same type.  initial value is nil.
    var i1, i2, i3 i
    fmt.Println("Initial (zero) values of interface variables:")
    fmt.Println("i1:", i1)
    fmt.Println("i2:", i2)
    fmt.Println("i3:", i3)

    // in the terminology of the Go language reference, i1, i2, and i3
    // still have static type i, but now have different dynamic types.
    i1, i2, i3 = t1, s1, r1
    fmt.Println("\nPolymorphic:")
    fmt.Println("i1:", i1, "/", i1.identify(), "/", reflect.TypeOf(i1))
    fmt.Println("i2:", i2, "/", i2.identify(), "/", reflect.TypeOf(i2))
    fmt.Println("i3:", i3, "/", i3.identify(), "/", reflect.TypeOf(i3))

    // copy: declare and assign in one step using "short declaration."
    i1c, i2c, i3c := i1, i2, i3

    // modify first set of polymorphic variables.
    i1, i2, i3 = s{3, "dog"}, r{t: 1}, t(2)

    // demonstrate that copies are distinct from first set
    // and that types are preserved.
    fmt.Println("\nFirst set now modified:")
    fmt.Println("i1:", i1, "/", i1.identify(), "/", reflect.TypeOf(i1))
    fmt.Println("i2:", i2, "/", i2.identify(), "/", reflect.TypeOf(i2))
    fmt.Println("i3:", i3, "/", i3.identify(), "/", reflect.TypeOf(i3))

    fmt.Println("\nCopies made before modifications:")
    fmt.Println("i1c:", i1c, "/", i1c.identify(), "/", reflect.TypeOf(i1c))
    fmt.Println("i2c:", i2c, "/", i2c.identify(), "/", reflect.TypeOf(i2c))
    fmt.Println("i3c:", i3c, "/", i3c.identify(), "/", reflect.TypeOf(i3c))
}


import javafx.application {
    Application
}
import javafx.stage {
    Stage
}
import javafx.animation {
    AnimationTimer
}
import ceylon.numeric.float {
    remainder,
    cos,
    sin,
    toRadians
}
import javafx.scene.layout {
    BorderPane
}
import javafx.scene.canvas {
    Canvas
}
import javafx.scene {
    Scene
}
import javafx.scene.paint {
    Color
}

shared void run() {
    Application.launch(`PolySpiralApp`);
}

shared class PolySpiralApp() extends Application() {

    value width = 600.0;
    value height = 600.0;

    variable value incr = 0.0;

    shared actual void start(Stage primaryStage) {

        value canvas = Canvas(width, height);
        value graphics = canvas.graphicsContext2D;

        object extends AnimationTimer() {

            shared actual void handle(Integer now) {

                incr = remainder(incr + 0.05, 360.0);

                variable value x = width / 2.0;
                variable value y = width / 2.0;
                variable value length = 5.0;
                variable value angle = incr;

                graphics.fillRect(0.0, 0.0, width, height);
                graphics.beginPath();
                graphics.moveTo(x, y);

                for (i in 1..150) {
                    value radians = toRadians(angle);
                    x = x + cos(radians) * length;
                    y = y + sin(radians)  * length;
                    graphics.stroke = Color.hsb(angle, 1.0, 1.0);
                    graphics.lineTo(x, y);
                    length += 3;
                    angle = remainder(angle + incr, 360.0);
                }

                graphics.stroke();
            }
        }.start();

        value root = BorderPane();
        root.center = canvas;
        value scene = Scene(root);
        primaryStage.title = "poly-spiral";
        primaryStage.setScene(scene);
        primaryStage.show();
    }
}


#include "fbgfx.bi"
#if __FB_LANG__ = "fb"
    Using FB '' Scan code constants are stored in the FB namespace in lang FB
#endif
#define pi  4 * Atn(1)
#define Deg2Rad  pi/180

Dim As Integer w = 900, h = w
Screenres w, h, 8
Windowtitle "Polyspiral"

Dim As Integer incr = 0, angulo, longitud, x1, y1, x2, y2, N
Do
    incr += 1
    x1 = w / 2
    y1 = h / 2
    Pset (Fix(x1), Fix(y1))
    longitud = 5
    angulo = incr
    For N = 1 To 150
        x2 = x1 + longitud * Cos(angulo * Deg2Rad)
        y2 = y1 + longitud * Sin(angulo * Deg2Rad)
        Line - (Fix(x2), Fix(y2)), N+16
        x1 = x2
        y1 = y2
        longitud += 3
        angulo += incr
    Next N
    Sleep 500
    Cls
Loop Until Multikey(SC_ESCAPE)


## plotpoly.gp 1/10/17 aev
## Plotting a polyspiral and writing to the png-file.
## Note: assign variables: rng, d, clr, filename and ttl (before using load command).
## Direction d (-1 clockwise / 1 counter-clockwise)
reset
set terminal png font arial 12 size 640,640
ofn=filename.".png"
set output ofn
unset border; unset xtics; unset ytics; unset key;
set title ttl font "Arial:Bold,12"
set parametric
c=rng*pi; set xrange[-c:c]; set yrange[-c:c];
set dummy t
plot [0:c] t*cos(d*t), t*sin(d*t) lt rgb @clr
set output


class T implements Cloneable {
    String property
    String name() { 'T' }
    T copy() {
        try { super.clone() }
        catch(CloneNotSupportedException e) { null }
    }
    @Override
    boolean equals(that) { this.name() == that?.name() && this.property == that?.property }
}

class S extends T {
    @Override String name() { 'S' }
}


class T()
    method a(); write("This is T's a"); end
end

class S: T()
    method a(); write("This is S's a"); end
end

procedure main()
    write("S:",deepcopy(S()).a())
end

procedure deepcopy(A, cache)  #: return a deepcopy of A
    local k

    /cache := table()        # used to handle multireferenced objects
    if \cache[A] then return cache[A]

    case type(A) of {
        "table"|"list": {
            cache[A] := copy(A)
            every cache[A][k := key(A)] := deepcopy(A[k], cache)
            }
        "set": {
            cache[A] := set()
            every insert(cache[A], deepcopy(!A, cache))
            }
        default: {           # records and objects (encoded as records)
            cache[A] := copy(A)
            if match("record ",image(A)) then {
                every cache[A][k := key(A)] := deepcopy(A[k], cache)
                }
            }
        }
    return .cache[A]
end


  $ convert polyspiral.gif -coalesce polyspiral2.gif
  $ eog polyspiral2.gif


{-# LANGUAGE OverloadedStrings #-}
import Reflex
import Reflex.Dom
import Reflex.Dom.Time
import Data.Text (Text, pack)
import Data.Map (Map, fromList)
import Data.Time.Clock (getCurrentTime)
import Control.Monad.Trans (liftIO)

type Point = (Float,Float)
type Segment = (Point,Point)

main = mainWidget $ do

  -- An event that fires every 0.05 seconds.
  dTick <- tickLossy 0.05 =<< liftIO getCurrentTime

  -- A dynamically updating counter.
  dCounter <- foldDyn (\_ c -> c+1) (0::Int) dTick

  let
      -- A dynamically updating angle.
      dAngle = fmap (\c -> fromIntegral c / 800.0) dCounter

      -- A dynamically updating spiral
      dSpiralMap = fmap toSpiralMap dAngle

      -- svg parameters
      width = 600
      height = 600

      boardAttrs =
         fromList [ ("width" , pack $ show width)
                  , ("height", pack $ show height)
                  , ("viewBox", pack $ show (-width/2) ++ " " ++ show (-height/2) ++ " " ++ show width ++ " " ++ show height)
                  ]

  elAttr "h1" ("style" =: "color:black") $ text "Polyspiral"
  elAttr "a" ("href" =: "http://rosettacode.org/wiki/Polyspiral#Haskell") $ text "Rosetta Code / Polyspiral / Haskell"

  el "br" $ return ()
  elSvgns "svg" (constDyn boardAttrs) (listWithKey dSpiralMap showLine)

  return ()

-- The svg attributes needed to display a line segment.
lineAttrs :: Segment -> Map Text Text
lineAttrs ((x1,y1), (x2,y2)) =
  fromList [ ( "x1",    pack $ show x1)
           , ( "y1",    pack $ show y1)
           , ( "x2",    pack $ show x2)
           , ( "y2",    pack $ show y2)
           , ( "style", "stroke:blue")
           ]

-- Use svg to display a line segment.
showLine :: MonadWidget t m => Int -> Dynamic t Segment -> m ()
showLine _ dSegment = elSvgns "line" (lineAttrs <$> dSegment) $ return ()

-- Given a point and distance/bearing , get the next point
advance :: Float -> (Point, Float, Float) -> (Point, Float, Float)
advance angle ((x,y), len, rot) =
  let new_x = x + len * cos rot
      new_y = y + len * sin rot
      new_len = len + 3.0
      new_rot = rot + angle
  in ((new_x, new_y), new_len, new_rot)

-- Given an angle, generate a map of segments that form a spiral.
toSpiralMap :: Float -> Map Int ((Float,Float),(Float,Float))
toSpiralMap angle =
      fromList                       -- changes list to map (for listWithKey)
  $   zip [0..]                      -- annotates segments with index
  $   (\pts -> zip pts $ tail pts)   -- from points to line segments
  $   take 80                        -- limit the number of points
  $   (\(pt,_,_) -> pt)              -- cull out the (x,y) values
  <$> iterate (advance angle) ((0, 0), 0, 0)  -- compute the spiral

-- Display an element in svg namespace
elSvgns :: MonadWidget t m => Text -> Dynamic t (Map Text Text) -> m a -> m a
elSvgns t m ma = do
    (el, val) <- elDynAttrNS' (Just "http://www.w3.org/2000/svg") t m ma
    return val


class T implements Cloneable {
    public String name() { return "T"; }
    public T copy() {
        try {
            return (T)super.clone();
        } catch (CloneNotSupportedException e) {
            return null;
        }
    }
}

class S extends T {
    public String name() { return "S"; }
}

public class PolymorphicCopy {
    public static T copier(T x) { return x.copy(); }
    public static void main(String[] args) {
        T obj1 = new T();
        S obj2 = new S();
        System.out.println(copier(obj1).name()); // prints "T"
        System.out.println(copier(obj2).name()); // prints "S"
    }
}


function clone(obj){
    if (obj == null || typeof(obj) != 'object')
        return obj;

    var temp = {};
    for (var key in obj)
        temp[key] = clone(obj[key]);
    return temp;
}