with Ada.Text_IO;  use Ada.Text_IO;

procedure Jensen_Device is
   function Sum
            (  I : not null access Float;
               Lo, Hi : Float;
               F : access function return Float
            )  return Float is
      Temp : Float := 0.0;
   begin
      I.all := Lo;
      while I.all <= Hi loop
         Temp := Temp + F.all;
         I.all := I.all + 1.0;
      end loop;
      return Temp;
   end Sum;

   I : aliased Float;
   function Inv_I return Float is
   begin
      return 1.0 / I;
   end Inv_I;
begin
   Put_Line (Float'Image (Sum (I'Access, 1.0, 100.0, Inv_I'Access)));
end Jensen_Device;


begin
   integer i;
   real procedure sum (i, lo, hi, term);
      value lo, hi;
      integer i, lo, hi;
      real term;
      comment term is passed by-name, and so is i;
   begin
      real temp;
      temp := 0;
      for i := lo step 1 until hi do
         temp := temp + term;
      sum := temp
   end;
   comment note the correspondence between the mathematical notation and the call to sum;
   print (sum (i, 1, 100, 1/i))
end


BEGIN
   INT i;
   PROC sum  = (REF INT i, INT lo, hi, PROC REAL term)REAL:
      COMMENT term is passed by-name, and so is i COMMENT
   BEGIN
      REAL temp := 0;
      i := lo;
      WHILE i <= hi DO           # ALGOL 68 has a "for" loop but it creates a distinct #
         temp +:= term;          # variable which would not be shared with the passed "i" #
         i +:= 1                 # Here the actual passed "i" is incremented. #
      OD;
      temp
   END;
   COMMENT note the correspondence between the mathematical notation and the call to sum COMMENT
   print (sum (i, 1, 100, REAL: 1/i))
END


begin
   integer i;
   real procedure sum  ( integer %name% i; integer value lo, hi; real procedure term );
      % i is passed by-name, term is passed as a procedure which makes it effectively passed by-name %
   begin
       real temp;
       temp := 0;
       i := lo;
       while i <= hi do begin      % The Algol W "for" loop (as in Algol 68) creates a distinct %
           temp := temp + term;    % variable which would not be shared with the passed "i" %
           i := i + 1              % Here the actual passed "i" is incremented. %
       end while_i_le_temp;
       temp
   end;
   % note the correspondence between the mathematical notation and the call to sum %
   write( sum( i, 1, 100, 1/i ) )
end.


class TestClass{
    String foo {get;set;}
    Integer bar {get;set;}
}

TestClass testObj = new TestClass();
testObj.foo = 'ABC';
testObj.bar = 123;

String serializedString = JSON.serialize(testObj);
TestClass deserializedObject = (TestClass)JSON.deserialize(serializedString, TestClass.class);

//"testObj.foo == deserializedObject.foo" is true
//"testObj.bar == deserializedObject.bar" is true


print read.json {{ "foo": 1, "bar": [10, "apples"] }}

object: #[
	name: "john"
	surname: "doe"
	address: #[
		number: 10
		street: "unknown"
		country: "Spain"
    ]
	married: false
]

print write.json ø object


USING: kernel prettyprint sequences ;

: count-jewels ( stones jewels -- n ) [ member? ] curry count ;

"aAAbbbb" "aA"
"ZZ" "z" [ count-jewels . ] [email protected]


function number_of(object jewels, object stones) -- why limit ourselves to strings?
integer ct = 0
    for i = 1 to length(stones) do
        ct += find(stones[i],jewels) != 0
    end for
    return ct
end function

? number_of("aA","aAAbbbb")
? number_of("z","ZZ")
? number_of({1,"Boo",3},{1,2,3,'A',"Boo",3}) -- might as well send a list of things to find, not just one!


function contar_joyas(piedras as string, joyas as string) as integer
    dim as integer bc, cont: cont = 0
    for i as integer = 1 to len(piedras)
        bc = instr(1, joyas, mid(piedras, i, 1))
        if bc <> 0 then cont += 1
    next i
    contar_joyas = cont
end function

print contar_joyas("aAAbbbb", "aA")
print contar_joyas("ZZ", "z")
print contar_joyas("[email protected]", _
                   "[email protected]")
print contar_joyas("AB", "")


*      Knapsack problem/0-1      16/02/2017
KNAPSA01 CSECT
       USING  KNAPSA01,R13
       B      72(R15)
       DC     17F'0'
       STM    R14,R12,12(R13)
       ST     R13,4(R15)
       ST     R15,8(R13)
       LR     R13,R15            end of prolog
       L      R0,N               n
       LA     R1,1
POWER  MH     R1,=H'2'           *2
       BCT    R0,POWER
       BCTR   R1,0               -1
       ST     R1,IMAX            imax=2**n-1
       SR     R6,R6              i=0
       DO WHILE=(C,R6,LE,IMAX)   do i=0 to imax
         SR     R10,R10            im=0
         SR     R8,R8              iw=0
         SR     R9,R9              iv=0
         LA     R7,1               j=1
         DO WHILE=(C,R7,LE,N)      do j=1 to n
           LR     R1,R6              i
           LR     R2,R7              j
           BAL    R14,TSTBIT         call tstbit(i,j)
           IF C,R0,EQ,=F'1' THEN     if tstbit(i,j)=1 then
             LA     R10,1(R10)         im=im+1
             LR     R3,R7              j
             BCTR   R3,0
             SLA    R3,5
             LA     R1,24(R3)
             A      R8,DATA(R1)        iw=iw+data(j).w
             LA     R1,28(R3)
             A      R9,DATA(R1)        iv=iv+data(j).v
           ENDIF  ,                  endif
           LA     R7,1(R7)           j=j+1
         ENDDO  ,                  enddo j
         IF C,R8,LE,MAXW,AND,C,R9,GT,XV THEN  if w<=maxw and iv>xv then
           ST     R6,XB              xb=i
           ST     R10,XM             xm=im
           ST     R8,XW              xw=iw
           ST     R9,XV              xv=iv
         ENDIF  ,                  endif
         LA     R6,1(R6)           i=i+1
       ENDDO  ,                  enddo i
       MVC    PG(2),=C'n='
       L      R1,N               n
       XDECO  R1,XDEC            edit n
       MVC    PG+2(2),XDEC+10
       XPRNT  PG,L'PG            print buffer
       LA     R6,1
       DO WHILE=(C,R6,LE,N)      do i=1 to n
         L      R1,XB              xb
         LR     R2,R6              i
         BAL    R14,TSTBIT         call tstbit(xb,i)
         IF C,R0,EQ,=F'1' THEN     if tstbit(xb,i)=1 then
           LR     R1,R6              i
           BCTR   R1,0
           SLA    R1,5
           LA     R2,DATA(R1)        @data(i).n
           MVC    PG(24),0(R2)
           XPRNT  PG,24              print item
         ENDIF  ,                  endif
         LA     R6,1(R6)           i=i+1
       ENDDO  ,                  enddo i
       L      R1,XM              xm
       XDECO  R1,XDEC            edit xm
       MVC    PGT+6(2),XDEC+10
       L      R1,XW              xw
       XDECO  R1,XDEC            edit xw
       MVC    PGT+16(3),XDEC+9
       L      R1,XV              xv
       XDECO  R1,XDEC            edit xv
       MVC    PGT+26(4),XDEC+8
       XPRNT  PGT,L'PGT          print buffer
       L      R13,4(0,R13)       epilog
       LM     R14,R12,12(R13)
       XR     R15,R15
       BR     R14                exit
TSTBIT EQU    *                  R1 value to test the R2 bit
       LA     R3,32              32
       SR     R3,R2              (32-i)
       STC    R3,XSLL+3
       LR     R0,R1              n
       EX     0,XSLL             SLL R0,(32-i)
       SRL    R0,31
       BR     R14                return R0
XSLL   SLL    R0,0               shift left logical
*
MAXW   DC     F'400'             maximum weight
N      DC     A((DATAE-DATA)/32)
IMAX   DS     F                  number of combinations
XB     DS     F                  max vector
XM     DS     F                  max items
XW     DS     F                  max weight
XV     DS     F                  max value
PG     DC     CL80' '
PGT    DC     CL32'items=.. weight=... value=....'
XDEC   DS     CL12
DATA   DC     CL24'map',F'9',F'150'
       DC     CL24'compass',F'13',F'35'
       DC     CL24'water',F'153',F'200'
       DC     CL24'sandwich',F'50',F'160'
       DC     CL24'glucose',F'15',F'60'
       DC     CL24'tin',F'68',F'45'
       DC     CL24'banana',F'27',F'60'
       DC     CL24'apple',F'39',F'40'
       DC     CL24'cheese',F'23',F'30'
       DC     CL24'beer',F'52',F'10'
       DC     CL24'suntan cream',F'11',F'70'
       DC     CL24'camera',F'32',F'30'
       DC     CL24'T-shirt',F'24',F'15'
       DC     CL24'trousers',F'48',F'10'
       DC     CL24'umbrella',F'73',F'40'
       DC     CL24'book',F'30',F'10'
       DC     CL24'waterproof trousers',F'42',F'70'
       DC     CL24'waterproof overclothes',F'43',F'75'
       DC     CL24'note-case',F'22',F'80'
       DC     CL24'sunglasses',F'7',F'20'
       DC     CL24'towel',F'18',F'12'
       DC     CL24'socks',F'4',F'50'
DATAE  DC     0C
       YREGS
       END    KNAPSA01


with Ada.Text_IO;
with Ada.Strings.Unbounded;

procedure Knapsack_01 is
   package US renames Ada.Strings.Unbounded;

   type Item is record
      Name   : US.Unbounded_String;
      Weight : Positive;
      Value  : Positive;
      Taken  : Boolean;
   end record;

   type Item_Array is array (Positive range <>) of Item;

   function Total_Weight (Items : Item_Array; Untaken : Boolean := False) return Natural is
      Sum : Natural := 0;
   begin
      for I in Items'Range loop
         if Untaken or else Items (I).Taken then
            Sum := Sum + Items (I).Weight;
         end if;
      end loop;
      return Sum;
   end Total_Weight;

   function Total_Value (Items : Item_Array; Untaken : Boolean := False) return Natural is
      Sum : Natural := 0;
   begin
      for I in Items'Range loop
         if Untaken or else Items (I).Taken then
            Sum := Sum + Items (I).Value;
         end if;
      end loop;
      return Sum;
   end Total_Value;

   function Max (Left, Right : Natural) return Natural is
   begin
      if Right > Left then
         return Right;
      else
         return Left;
      end if;
   end Max;

   procedure Solve_Knapsack_01 (Items : in out Item_Array;
                                Weight_Limit : Positive := 400) is
      type W_Array is array (0..Items'Length, 0..Weight_Limit) of Natural;
      W : W_Array := (others => (others => 0));
   begin
      -- fill W
      for I in Items'Range loop
         for J in 1 .. Weight_Limit loop
            if Items (I).Weight > J then
               W (I, J) := W (I - 1, J);
            else
               W (I, J) := Max (W (I - 1, J),
                                W (I - 1, J - Items (I).Weight) + Items (I).Value);
            end if;
         end loop;
      end loop;
      declare
         Rest : Natural := Weight_Limit;
      begin
         for I in reverse Items'Range loop
            if W (I, Rest) /= W (I - 1, Rest) then
               Items (I).Taken := True;
               Rest := Rest - Items (I).Weight;
            end if;
         end loop;
      end;
   end Solve_Knapsack_01;

   All_Items : Item_Array :=
     ( (US.To_Unbounded_String ("map"),                      9, 150, False),
       (US.To_Unbounded_String ("compass"),                 13,  35, False),
       (US.To_Unbounded_String ("water"),                  153, 200, False),
       (US.To_Unbounded_String ("sandwich"),                50, 160, False),
       (US.To_Unbounded_String ("glucose"),                 15,  60, False),
       (US.To_Unbounded_String ("tin"),                     68,  45, False),
       (US.To_Unbounded_String ("banana"),                  27,  60, False),
       (US.To_Unbounded_String ("apple"),                   39,  40, False),
       (US.To_Unbounded_String ("cheese"),                  23,  30, False),
       (US.To_Unbounded_String ("beer"),                    52,  10, False),
       (US.To_Unbounded_String ("suntan cream"),            11,  70, False),
       (US.To_Unbounded_String ("camera"),                  32,  30, False),
       (US.To_Unbounded_String ("t-shirt"),                 24,  15, False),
       (US.To_Unbounded_String ("trousers"),                48,  10, False),
       (US.To_Unbounded_String ("umbrella"),                73,  40, False),
       (US.To_Unbounded_String ("waterproof trousers"),     42,  70, False),
       (US.To_Unbounded_String ("waterproof overclothes"),  43,  75, False),
       (US.To_Unbounded_String ("note-case"),               22,  80, False),
       (US.To_Unbounded_String ("sunglasses"),               7,  20, False),
       (US.To_Unbounded_String ("towel"),                   18,  12, False),
       (US.To_Unbounded_String ("socks"),                    4,  50, False),
       (US.To_Unbounded_String ("book"),                    30,  10, False) );

begin
   Solve_Knapsack_01 (All_Items, 400);
   Ada.Text_IO.Put_Line ("Total Weight: " & Natural'Image (Total_Weight (All_Items)));
   Ada.Text_IO.Put_Line ("Total Value:  " & Natural'Image (Total_Value  (All_Items)));
   Ada.Text_IO.Put_Line ("Items:");
   for I in All_Items'Range loop
      if All_Items (I).Taken then
         Ada.Text_IO.Put_Line ("   " & US.To_String (All_Items (I).Name));
      end if;
   end loop;
end Knapsack_01;


set i to 0

on jsum(i, lo, hi, term)
    set {temp, i's contents} to {0, lo}
    repeat while i's contents ≤ hi
        set {temp, i's contents} to {temp + (term's f(i)), (i's contents) + 1}
    end repeat
    return temp
end jsum

script term_func
    on f(i)
        return 1 / i
    end f
end script

return jsum(a reference to i, 1, 100, term_func)


/* ARM assembly Raspberry PI  */
/*  program jensen.s   */
/* compil as with option  -mcpu=<processor> -mfpu=vfpv4 -mfloat-abi=hard  */
/* link with gcc          */

/* Constantes    */
.equ EXIT,   1                           @ Linux syscall
/* Initialized data */
.data

szFormat: .asciz "Result = %.8f \n"
.align 4

/* UnInitialized data */
.bss

/*  code section */
.text
.global main
main:
    mov r0,#1                                   @ first indice
    mov r1,#100                                 @ last indice
    adr r2,funcdiv                              @ address function
    bl funcSum
    vcvt.f64.f32  d1, s0                        @ conversion double float for print by C
    ldr r0,iAdrszFormat                         @ display format
    vmov r2,r3,d1                               @ parameter function printf for float double
    bl printf                                   @ display float double

100:                                            @ standard end of the program
    mov r0, #0                                  @ return code
    mov r7, #EXIT                               @ request to exit program
    svc 0                                       @ perform system call

iAdrszFormat:             .int szFormat
/******************************************************************/
/*     function sum                                               */
/******************************************************************/
/* r0 contains begin  */
/* r1 contains end */
/* r2 contains address function */

/* r0 return result                      */
funcSum:
    push {r0,r3,lr}                       @ save  registers
    mov r3,r0
    mov r0,#0                             @ init r0
    vmov s3,r0                            @ and s3
    vcvt.f32.s32 s3, s3                   @ convert in float single précision (32bits)
1:                                        @ begin loop
    mov r0,r3                             @ loop indice -> parameter function
    blx r2                                @ call function address in r2
    vadd.f32 s3,s0                        @ addition float
    add r3,#1                             @ increment indice
    cmp r3,r1                             @ end ?
    ble 1b                                @ no loop
    vmov s0,s3                            @ return float result in s0

100:
    pop {r0,r3,lr}                        @ restaur registers
    bx lr                                 @ return
/******************************************************************/
/*     compute 1/r0                                               */
/******************************************************************/
/* r0 contains the value                 */
/* r0 return result                      */
funcdiv:
    push {r1,lr}                       @ save  registers
    vpush {s1}                         @ save float registers
    cmp r0,#0                          @ division by zero -> end
    beq 100f
    ldr r1,fUn                         @ load float constant 1.0
    vmov s0,r1                         @ in float register s3
    vmov s1,r0                         @
    vcvt.f32.s32 s1, s1                @conversion in float single précision (32 bits)
    vdiv.f32 s0,s0,s1                  @ division 1/r0
                                       @ and return result in s0
100:
    vpop {s1}                          @ restaur float registers
    pop {r1,lr}                        @ restaur registers
    bx lr                              @ return
fUn:                .float 1


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <yajl/yajl_tree.h>
#include <yajl/yajl_gen.h>

static void print_callback (void *ctx, const char *str, size_t len)
{
  FILE *f = (FILE *) ctx;
  fwrite (str, 1, len, f);
}

static void check_status (yajl_gen_status status)
{
  if (status != yajl_gen_status_ok)
    {
      fprintf (stderr, "yajl_gen_status was %d\n", (int) status);
      exit (EXIT_FAILURE);
    }
}

static void serialize_value (yajl_gen gen, yajl_val val, int parse_numbers)
{
  size_t i;

  switch (val->type)
    {
    case yajl_t_string:
      check_status (yajl_gen_string (gen,
                                     (const unsigned char *) val->u.string,
                                     strlen (val->u.string)));
      break;
    case yajl_t_number:
      if (parse_numbers  &&  YAJL_IS_INTEGER (val))
        check_status (yajl_gen_integer (gen, YAJL_GET_INTEGER (val)));
      else if (parse_numbers  &&  YAJL_IS_DOUBLE (val))
        check_status (yajl_gen_double (gen, YAJL_GET_DOUBLE (val)));
      else
        check_status (yajl_gen_number (gen, YAJL_GET_NUMBER (val),
                                       strlen (YAJL_GET_NUMBER (val))));
      break;
    case yajl_t_object:
      check_status (yajl_gen_map_open (gen));
      for (i = 0  ;  i < val->u.object.len  ;  i++)
        {
          check_status (yajl_gen_string (gen,
                                         (const unsigned char *) val->u.object.keys[i],
                                         strlen (val->u.object.keys[i])));
          serialize_value (gen, val->u.object.values[i], parse_numbers);
        }
      check_status (yajl_gen_map_close (gen));
      break;
    case yajl_t_array:
      check_status (yajl_gen_array_open (gen));
      for (i = 0  ;  i < val->u.array.len  ;  i++)
        serialize_value (gen, val->u.array.values[i], parse_numbers);
      check_status (yajl_gen_array_close (gen));
      break;
    case yajl_t_true:
      check_status (yajl_gen_bool (gen, 1));
      break;
    case yajl_t_false:
      check_status (yajl_gen_bool (gen, 0));
      break;
    case yajl_t_null:
      check_status (yajl_gen_null (gen));
      break;
    default:
      fprintf (stderr, "unexpectedly got type %d\n", (int) val->type);
      exit (EXIT_FAILURE);
    }
}

static void print_tree (FILE *f, yajl_val tree, int parse_numbers)
{
  yajl_gen gen;

  gen = yajl_gen_alloc (NULL);
  if (! gen)
    {
      fprintf (stderr, "yajl_gen_alloc failed\n");
      exit (EXIT_FAILURE);
    }

  if (0 == yajl_gen_config (gen, yajl_gen_beautify, 1)  ||
      0 == yajl_gen_config (gen, yajl_gen_validate_utf8, 1)  ||
      0 == yajl_gen_config (gen, yajl_gen_print_callback, print_callback, f))
    {
      fprintf (stderr, "yajl_gen_config failed\n");
      exit (EXIT_FAILURE);
    }

  serialize_value (gen, tree, parse_numbers);
  yajl_gen_free (gen);
}

int main (int argc, char **argv)
{
  char err_buf[200];
  const char *json =
    "{\"pi\": 3.14, \"large number\": 123456789123456789123456789, "
    "\"an array\": [-1, true, false, null, \"foo\"]}";
  yajl_val tree;

  tree = yajl_tree_parse (json, err_buf, sizeof (err_buf));
  if (! tree)
    {
      fprintf (stderr, "parsing failed because: %s\n", err_buf);
      return EXIT_FAILURE;
    }

  printf ("Treating numbers as strings...\n");
  print_tree (stdout, tree, 0);
  printf ("Parsing numbers to long long or double...\n");
  print_tree (stdout, tree, 1);

  yajl_tree_free (tree);

  return EXIT_SUCCESS;
}


package main

import (
    "fmt"
    "strings"
)

func js(stones, jewels string) (n int) {
    for _, b := range []byte(stones) {
        if strings.IndexByte(jewels, b) >= 0 {
            n++
        }
    }
    return
}

func main() {
    fmt.Println(js("aAAbbbb", "aA"))
}


jewelCount
  :: Eq a
  => [a] -> [a] -> Int
jewelCount jewels = foldr go 0
  where
    go c
      | c `elem` jewels = succ
      | otherwise = id

--------------------------- TEST -------------------------
main :: IO ()
main = mapM_ print $ uncurry jewelCount <$> [("aA", "aAAbbbb"), ("z", "ZZ")]


   NB. jewels sums a raveled equality table
   NB. use: x jewels y  x are the stones, y are the jewels.
   intersect =: -.^:2
   jewels =: ([: +/ [: , =/~) [email protected]:intersect&Alpha_j_

   'aAAbbbb ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz' jewels&>&;: 'aA ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz'
3 52

   'none' jewels ''
0
   'ZZ' jewels 'z'
0


    ∇ ret←NapSack;sum;b;list;total
[1]   total←400
[2]   list←("map" 9 150)("compass" 13 35)("water" 153 200)("sandwich" 50 160)("glucose" 15 60) ("tin" 68 45)("banana" 27 60)("apple" 39 40)("cheese" 23 30)("beer" 52 10) ("suntan cream" 11 70)("camera" 32 30)("t-shirt" 24 15)("trousers" 48 10) ("umbrella" 73 40)("waterproof trousers" 42 70)("waterproof overclothes" 43 75) ("note-case" 22 80) ("sunglasses" 7 20) ("towel" 18 12) ("socks" 4 50) ("book" 30 10)
[3]   list←list[⍒3⊃¨list]
[4]
[5]   ret←⍬
[6]   :while 0≠⍴list
[7]       ret←ret,(b←total>sum←+\2⊃¨list)/list
[8]       list←1↓(~b)/list
[9]       total←total-sum←¯1↑(total>sum)/sum
[10]  :end
[11]  ret←⊃ret,⊂'TOTALS:' (+/2⊃¨ret)(+/3⊃¨ret)
    ∇


# syntax: GAWK -f KNAPSACK_PROBLEM_0-1.AWK
BEGIN {
#   arr["item,weight"] = value
    arr["map,9"] = 150
    arr["compass,13"] = 35
    arr["water,153"] = 200
    arr["sandwich,50"] = 160
    arr["glucose,15"] = 60
    arr["tin,68"] = 45
    arr["banana,27"] = 60
    arr["apple,39"] = 40
    arr["cheese,23"] = 30
    arr["beer,52"] = 10
    arr["suntan cream,11"] = 70
    arr["camera,32"] = 30
    arr["T-shirt,24"] = 15
    arr["trousers,48"] = 10
    arr["umbrella,73"] = 40
    arr["waterproof trousers,42"] = 70
    arr["waterproof overclothes,43"] = 75
    arr["note-case,22"] = 80
    arr["sunglasses,7"] = 20
    arr["towel,18"] = 12
    arr["socks,4"] = 50
    arr["book,30"] = 10
    sack_size = 400 # dag
    PROCINFO["sorted_in"] = "@val_num_desc"
    for (i in arr) {
      if (total_weight >= sack_size) {
        break
      }
      split(i,tmp,",")
      weight = tmp[2]
      if (total_weight + weight <= sack_size) {
        printf("%s\n",tmp[1])
        total_items++
        total_value += arr[i]
        total_weight += weight
      }
    }
    printf("items=%d (out of %d) weight=%d value=%d\n",total_items,length(arr),total_weight,total_value)
    exit(0)
}


harmonicSum: function [variable, lo, hi, term][
    result: new 0.0
    loop lo..hi 'n ->
        'result + do ~"|variable|: |n| |term|"
    result
]
print ["harmonicSum 1->100:" harmonicSum 'i 1 100 {1.0 / i}]


# syntax: GAWK -f JENSENS_DEVICE.AWK
# converted from FreeBASIC
BEGIN {
    evaluation()
    exit(0)
}
function evaluation(  hi,i,lo,tmp) {
    lo = 1
    hi = 100
    for (i=lo; i<=hi; i++) {
      tmp += (1/i)
    }
    printf("%.15f\n",tmp)
}


subroutine Evaluation()
	lo = 1 : hi = 100 : temp = 0
	for i = lo to hi
		temp += (1/i)  ##r(i)
	next i
	print temp
end subroutine

call Evaluation()
end


      PRINT FNsum(j, 1, 100, FNreciprocal)
      END

      DEF FNsum(RETURN i, lo, hi, RETURN func)
      LOCAL temp
      FOR i = lo TO hi
        temp += FN(^func)
      NEXT
      = temp

      DEF FNreciprocal = 1/i


using System;
using System.Collections.Generic;
using System.Web.Script.Serialization;

class Program
{
    static void Main()
    {
        var people = new Dictionary<string, object> {{"1", "John"}, {"2", "Susan"}};
        var serializer = new JavaScriptSerializer();

        var json = serializer.Serialize(people);
        Console.WriteLine(json);

        var deserialized = serializer.Deserialize<Dictionary<string, object>>(json);
        Console.WriteLine(deserialized["2"]);

        var jsonObject = serializer.DeserializeObject(@"{ ""foo"": 1, ""bar"": [10, ""apples""] }");
        var data = jsonObject as Dictionary<string, object>;
        var array = data["bar"] as object[];
        Console.WriteLine(array[1]);
    }
}


#include "Core/Core.h"

using namespace Upp;

CONSOLE_APP_MAIN
{
	JsonArray a;
	a << Json("name", "John")("phone", "1234567") << Json("name", "Susan")("phone", "654321");
	String txt = ~a;
	Cout() << txt << '\n';
	Value v = ParseJSON(txt);
	for(int i = 0; i < v.GetCount(); i++)
		Cout() << v[i]["name"] << ' ' << v[i]["phone"] << '\n';
}


import java.util.HashSet;
import java.util.Set;

public class App {
    private static int countJewels(String stones, String jewels) {
        Set<Character> bag = new HashSet<>();
        for (char c : jewels.toCharArray()) {
            bag.add(c);
        }

        int count = 0;
        for (char c : stones.toCharArray()) {
            if (bag.contains(c)) {
                count++;
            }
        }

        return count;
    }

    public static void main(String[] args) {
        System.out.println(countJewels("aAAbbbb", "aA"));
        System.out.println(countJewels("ZZ", "z"));
    }
}


$ jq -n --arg stones aAAbbbb --arg jewels aA '
  [$stones|split("") as $s|$jewels|split("") as $j|$s[]|
  select(. as $c|$j|contains([$c]))]|length'


N = 7: G = 5: a = 2 ^ (N + 1) ' Author: DANILIN & Editor: Jjuanhdez or Unknow
RANDOMIZE TIMER
DIM L(N), C(N), j(N), q(a), d(a), q$(a)

FOR i = a - 1 TO (a - 1) \ 2 STEP -1
    k = i
    DO  ' cipher 0-1
        q$(i) = LTRIM$(STR$(k MOD 2)) + q$(i)
        k = INT(k / 2)
    LOOP UNTIL k = 0
    q$(i) = MID$(q$(i), 2, LEN(q$(i)))
NEXT i

PRINT " #            Mass          Cost"
FOR i = 1 TO N
    L(i) = INT(RND * 3 + 1)' mass & cost
    C(i) = 10 + INT(RND * 9)
    PRINT i, L(i), C(i)
NEXT i  ' origin

PRINT CHR$(10) + "Mass          Cost           Chifer"
FOR h = a - 1 TO (a - 1) / 2 STEP -1
    FOR k = 1 TO N
        j(k) = VAL(MID$(q$(h), k, 1))    ' j() = cipher
        q(h) = q(h) + L(k) * j(k) * C(k) ' 0 or 1
        d(h) = d(h) + L(k) * j(k)
    NEXT k
    IF d(h) <= G THEN PRINT d(h), q(h), q$(h)
NEXT h

PRINT CHR$(10) + "Mass          MAX            Chifer"
max = 0: h = 1
FOR i = 1 TO a
    IF d(i) <= G AND q(i) > max THEN max = q(i): h = i
NEXT i
PRINT d(h), q(h), q$(h)


#include <stdio.h>

int i;
double sum(int *i, int lo, int hi, double (*term)()) {
    double temp = 0;
    for (*i = lo; *i <= hi; (*i)++)
        temp += term();
    return temp;
}

double term_func() { return 1.0 / i; }

int main () {
    printf("%f\n", sum(&i, 1, 100, term_func));
    return 0;
}


using System;

class JensensDevice
{
    public static double Sum(ref int i, int lo, int hi, Func<double> term)
    {
        double temp = 0.0;
        for (i = lo; i <= hi; i++)
        {
            temp += term();
        }
        return temp;
    }

    static void Main()
    {
        int i = 0;
        Console.WriteLine(Sum(ref i, 1, 100, () => 1.0 / i));
    }
}


#include <iostream>

#define SUM(i,lo,hi,term)\
[&](const int _lo,const int _hi){\
  decltype(+(term)) sum{};\
  for (i = _lo; i <= _hi; ++i) sum += (term);\
  return sum;\
}((lo),(hi))

int i;
double sum(int &i, int lo, int hi, double (*term)()) {
    double temp = 0;
    for (i = lo; i <= hi; i++)
        temp += term();
    return temp;
}
double term_func() { return 1.0 / i; }

int main () {
    std::cout << sum(i, 1, 100, term_func) << std::endl;
    std::cout << SUM(i,1,100,1.0/i) << "\n";
    return 0;
}


Class Sample.JSON [ Abstract ]
{

ClassMethod GetPerson(ByRef pParms, Output pObject As %RegisteredObject) As %Status
{
	Set pObject=##class(Sample.Person).%OpenId(pParms("oid"))
	Quit $$$OK
}

}


(use 'clojure.data.json)

 ; Load as Clojure data structures and bind the resulting structure to 'json-map'.
(def json-map (read-json "{ \"foo\": 1, \"bar\": [10, \"apples\"] }"))

; Use pr-str to print out the Clojure representation of the JSON created by read-json.
(pr-str json-map)

; Pretty-print the Clojure representation of JSON. We've come full circle.
(pprint-json json-map)


sample =
  blue: [1, 2]
  ocean: 'water'

json_string = JSON.stringify sample
json_obj = JSON.parse json_string

console.log json_string
console.log json_obj


module Jewels

count(s, j) = Base.count(x ∈ j for x in s)

end  # module Jewels


// Version 1.2.40

fun countJewels(s: String, j: String) = s.count { it in j }

fun main(args: Array<String>) {
    println(countJewels("aAAbbbb", "aA"))
    println(countJewels("ZZ", "z"))
}


{def countjewels
 {def countjewels.r
  {lambda {:a :b :c}
   {if {A.empty? :a}
    then :c
    else {countjewels.r {A.rest :a}
                        :b
                        {if {= {A.in? {A.first :a} :b} -1}
                         then :c
                         else {+ :c 1}}}}}}
 {lambda {:a :b}
  {countjewels.r {A.split :a} {A.split :b} 0}}}
-> countjewels

{countjewels aAAbbbb aA} -> 3
{countjewels ZZ z}       -> 0


function count_jewels(s, j)
    local count = 0
    for i=1,#s do
        local c = s:sub(i,i)
        if string.match(j, c) then
            count = count + 1
        end
    end
    return count
end

print(count_jewels("aAAbbbb", "aA"))
print(count_jewels("ZZ", "z"))


:: Initiate command line environment
@echo off
setlocal enabledelayedexpansion

:: Establish arrays we'll be using
set items=map compass water sandwich glucose tin banana apple cheese beer suntancream camera tshirt trousers umbrella waterprooftrousers waterproofoverclothes notecase sunglasses towel socks book
set weight=9 13 153 50 15 68 27 39 23 52 11 32 24 48 73 42 43 22 7 18 4 30
set importance=150 35 200 160 60 45 60 40 30 10 70 30 15 10 40 70 75 80 20 12 50 10

:: Put the above 3 arrays into their own variables with the form of "item[]", "w[]" and "i[]"
set tempnum=0
for %%i in (%items%) do (
  set /a tempnum+=1
  set item!tempnum!=%%i
)
set tempnum=0
for %%i in (%weight%) do (
  set /a tempnum+=1
  set w!tempnum!=%%i
)
set tempnum=0
for %%i in (%importance%) do (
  set /a tempnum+=1
  set i!tempnum!=%%i
)
:: Define the array "r[]" as the ratio between the importance ("i[]") and the weight ("w[]").
for /l %%i in (1,1,22) do set /a r%%i=!i%%i!*100/!w%%i! & rem batch doesn't support decimals, so the numerator is multiplied by 100 to get past this

set totalimportance=0
set totalweight=0
set amount=0

:: Find the largest number in "r[]" and define some temp variables based off it
:load
set tempr=0
set tempitem=0
for /l %%i in (1,1,22) do (
  if !r%%i! gtr !tempr! (
    set tempr=!r%%i!
    set tempitem=%%i
    set /a testweight=%totalweight%+!w%%i!
    if !tempr!==0 goto end
    if !testweight! geq 400 goto end
  )
)

:: Do basic error checking using the temp variables from above and either output and end the program or send back to load
set /a totaltempweight=%totalweight%+!w%tempitem%!

if %totaltempweight% gtr 400 (
  set !r%tempitem%!=0
  goto load
)

set totalweight=%totaltempweight%
set /a totalimportance+=!i%tempitem%!
set taken=%taken% !item%tempitem%!
set /a amount+=1
set r%tempitem%=0 & rem set the ratio variable of the item we just added to the knapsack as 0 to stop it repeat

goto load

:end
echo List of things taken [%amount%]: %taken%
echo Total Value: %totalimportance%  Total Weight: %totalweight%
pause>nul


// Jensen's device in Clipper (or Harbour)
//    A fairly direct translation of the Algol 60
// John M Skelton 11-Feb-2012

function main()
local i
? transform(sum(@i, 1, 100, {|| 1 / i}), "##.###############")
   // @ is the quite rarely used pass by ref, {|| ...} is a
   // code block (an anonymous function, here without arguments)
   // The @i makes it clear that something unusual is occurring;
   // a called function which modifies a parameter is commonly
   // poor design!
return 0

function sum(i, lo, hi, bFunc)
local temp := 0
for i = lo to hi
   temp += eval(bFunc)
next i
return temp


(declaim (inline %sum))

(defun %sum (lo hi func)
  (loop for i from lo to hi sum (funcall func i)))

(defmacro sum (i lo hi term)
  `(%sum ,lo ,hi (lambda (,i) ,term)))


double sum(ref int i, in int lo, in int hi, lazy double term)
pure @safe /*nothrow @nogc*/ {
    double result = 0.0;
    for (i = lo; i <= hi; i++)
        result += term();
    return result;
}

void main() {
    import std.stdio;

    int i;
    sum(i, 1, 100, 1.0/i).writeln;
}


function sum(var i : Integer; lo, hi : Integer; lazy term : Float) : Float;
begin
   i:=lo;
   while i<=hi do begin
      Result += term;
      Inc(i);
   end;
end;

var i : Integer;

PrintLn(sum(i, 1, 100, 1.0/i));


<!--- Create sample JSON structure --->
<cfset json = {
  string: "Hello",
  number: 42,
  arrayOfNumbers: [1, 2, 3, 4],
  arrayOfStrings: ["One", "Two", "Three", "Four"],
  arrayOfAnything: [1, "One", [1, "One"], { one: 1 }],
  object: {
    key: "value"
  }
} />

<!--- Convert to JSON string --->
<cfset jsonSerialized = serializeJSON(json) />
<!--- Convert back to ColdFusion --->
<cfset jsonDeserialized = deserializeJSON(jsonSerialized) />

<!--- Output examples --->
<cfdump var="#jsonSerialized#" />
<cfdump var="#jsonDeserialized#" />


(ql:quickload '("cl-json"))

(json:encode-json
 '#( ((foo . (1 2 3)) (bar . t) (baz . #\!))
    "quux" 4/17 4.25))

(print (with-input-from-string
	   (s "{\"foo\": [1, 2, 3], \"bar\": true, \"baz\": \"!\"}")
	 (json:decode-json s)))


count_jewel := proc(stones, jewels)
	local count, j, letter:
	j := convert(jewels,set):
	count := 0:
	for letter in stones do
		if (member(letter, j)) then
			count++:
		end if:
	end do:
	return count:
end proc:
count_jewel("aAAbbbb", "aA")


JewelsStones[j_String, s_String] := Count[MemberQ[Characters[j], #] & /@ Characters[s], True]
JewelsStones["aA", "aAAbbbb"]
JewelsStones["ZZ", "z"]


    function s = count_jewels(stones,jewels)
    s=0;
    for c=jewels
        s=s+sum(c==stones);
    end
    %!test
    %! assert(count_jewels('aAAbbbb','aA'),3)
    %!test
    %! assert(count_jewels('ZZ','z'),0)


(('' '' '') => spread if) :if?

((1 0 if?) concat map sum) :count

(swap indexof -1 !=) :member?

(("" split) dip 'member? cons count) :count-jewels

"aAAbbbb" "aA" count-jewels puts!
"ZZ" "z" count-jewels puts!


MODULE Jewels;
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;

PROCEDURE WriteInt(n : INTEGER);
VAR buf : ARRAY[0..15] OF CHAR;
BEGIN
    FormatString("%i", buf, n);
    WriteString(buf)
END WriteInt;

PROCEDURE CountJewels(s,j : ARRAY OF CHAR) : INTEGER;
VAR c,i,k : CARDINAL;
BEGIN
    c :=0;

    FOR i:=0 TO HIGH(s) DO
        FOR k:=0 TO HIGH(j) DO
            IF (j[k]#0C) AND (s[i]#0C) AND (j[k]=s[i]) THEN
                INC(c);
                BREAK
            END
        END
    END;

    RETURN c
END CountJewels;

BEGIN
    WriteInt(CountJewels("aAAbbbb", "aA"));
    WriteLn;
    WriteInt(CountJewels("ZZ", "z"));
    WriteLn;

    ReadChar
END Jewels.


      HIMEM = PAGE + 8000000
      nItems% = 22
      maxWeight% = 400

      DIM Tag{ivalue%, list%(nItems%-1), lp%}
      DIM items{(nItems%-1)name$, weight%, ivalue%}
      FOR item% = 0 TO nItems%-1
        READ items{(item%)}.name$, items{(item%)}.weight%, items{(item%)}.ivalue%
      NEXT

      DATA "map", 9, 150, "compass", 13, 35, "water", 153, 200, "sandwich", 50, 160
      DATA "glucose", 15, 60, "tin", 68, 45, "banana", 27, 60, "apple", 39, 40
      DATA "cheese", 23, 30, "beer", 52, 10, "suntan cream", 11, 70, "camera", 32, 30
      DATA "t-shirt", 24, 15, "trousers", 48, 10, "umbrella", 73, 40, "book", 30, 10
      DATA "waterproof trousers", 42, 70, "waterproof overclothes", 43, 75
      DATA "note-case", 22, 80, "sunglasses", 7, 20, "towel", 18, 12, "socks", 4, 50

      carry% = FN_Knapsack(items{()}, nItems% - 1, maxWeight%, cache{()})
      FOR i% = 0 TO cache{(carry%)}.lp%-1
        n% = cache{(carry%)}.list%(i%)
        TotalWeight% += items{(n%)}.weight%
        TotalValue% += items{(n%)}.ivalue%
        PRINT items{(n%)}.name$ " "
      NEXT
      PRINT '"Total weight = " ; TotalWeight%
      PRINT "Total value  = " ; TotalValue%
      END

      DEF FN_Knapsack(i{()}, i%, w%, RETURN m{()})
      LOCAL included{}, excluded{}, tmp%, index%
      DIM m{(16384)} = Tag{}, included{} = Tag{}, excluded{} = Tag{}

      index% = i% << 9 OR w%
      IF m{(index%)}.ivalue% THEN = index%

      IF i% = 0 THEN
        IF i{(0)}.weight% > w% THEN
          m{(index%)}.ivalue% = 0 : REM Item doesn't fit
        ELSE
          m{(index%)}.ivalue% = i{(0)}.ivalue%
          m{(index%)}.list%(m{(index%)}.lp%) = 0
          m{(index%)}.lp% += 1
        ENDIF
        = index%
      ENDIF

      tmp% = FN_Knapsack(i{()}, i% - 1, w%, m{()})
      excluded{} = m{(tmp%)}
      IF i{(i%)}.weight% > w% THEN
        m{(index%)} = excluded{} : REM Item weighs too much
        = index%
      ELSE
        tmp% = FN_Knapsack(i{()}, i% - 1, w% - i{(i%)}.weight%, m{()})
        included{} = m{(tmp%)}
        included.ivalue% += i{(i%)}.ivalue%
        included.list%(included.lp%) = i%
        included.lp% += 1
      ENDIF

      IF included.ivalue% > excluded.ivalue% THEN
        m{(index%)} = included{}
      ELSE
        m{(index%)} = excluded{}
      ENDIF
      = index%


(knapsack=
  ( things
  =   (map.9.150)
      (compass.13.35)
      (water.153.200)
      (sandwich.50.160)
      (glucose.15.60)
      (tin.68.45)
      (banana.27.60)
      (apple.39.40)
      (cheese.23.30)
      (beer.52.10)
      ("suntan cream".11.70)
      (camera.32.30)
      (T-shirt.24.15)
      (trousers.48.10)
      (umbrella.73.40)
      ("waterproof trousers".42.70)
      ("waterproof overclothes".43.75)
      (note-case.22.80)
      (sunglasses.7.20)
      (towel.18.12)
      (socks.4.50)
      (book.30.10)
  )
& 0:?maxvalue
& :?sack
& ( add
  =     cumwght
        cumvalue
        cumsack
        name
        wght
        val
        tings
        n
        ncumwght
        ncumvalue
    .     !arg
        : (?cumwght.?cumvalue.?cumsack.(?name.?wght.?val) ?tings)
      & -1:?n
      &   whl
        ' ( 1+!n:~>1:?n
          & !cumwght+!n*!wght:~>400:?ncumwght
          & !cumvalue+!n*!val:?ncumvalue
          & (   !tings:
              & (   !ncumvalue:>!maxvalue:?maxvalue
                  &     !cumsack
                        (!n:0&|!name)
                    : ?sack
                |
                )
            |   add
              $ ( !ncumwght
                . !ncumvalue
                .   !cumsack
                    (!n:0&|!name)
                . !tings
                )
            )
          )
  )
& add$(0.0..!things)
& out$(!maxvalue.!sack));

!knapsack;


pragma.enable("one-method-object") # "def _.get" is experimental shorthand
def sum(&i, lo, hi, &term) {   # bind i and term to passed slots
    var temp := 0
    i := lo
    while (i <= hi) {          # E has numeric-range iteration but it creates a distinct
        temp += term           # variable which would not be shared with the passed i
        i += 1
    }
    return temp
}
{
    var i := null
    sum(&i, 1, 100, def _.get() { return 1/i })
}


defmodule JensenDevice do
  def task, do: sum( 1, 100, fn i -> 1 / i end )

  defp sum( i, high, _term ) when i > high, do: 0
  defp sum( i, high, term ) do
    temp = term.( i )
    temp + sum( i + 1, high, term )
  end
end

IO.puts JensenDevice.task


-module( jensens_device ).

-export( [task/0] ).

task() ->
    sum( 1, 100, fun (I) -> 1 / I end ).

sum( I, High, _Term ) when I > High -> 0;
sum( I, High, Term ) ->
    Temp = Term( I ),
    Temp + sum( I + 1, High, Term ).


require "json_mapping"

class Foo
  JSON.mapping(
    num: Int64,
    array: Array(String),
  )
end

def json
  foo = Foo.from_json(%({"num": 1, "array": ["a", "b"]}))
  puts("#{foo.num} #{foo.array}")
  puts(foo.to_json)
end


import std.stdio, std.json;

void main() {
    auto j = parseJSON(`{ "foo": 1, "bar": [10, "apples"] }`);
    writeln(toJSON(&j));
}


import 'dart:convert' show jsonDecode, jsonEncode;

main(){
	var json_string = '''
	{
		"rosetta_code": {
			"task": "json",
			"language": "dart",
			"descriptions": [ "fun!", "easy to learn!", "awesome!" ]
		}
	}
	''';

	// decode string into Map<String, dynamic>
	var json_object = jsonDecode(json_string);

	for ( var description in json_object["rosetta_code"]["descriptions"] )
		print( "dart is $description" );

	var dart = {
		"compiled": true,
		"interpreted": true,
		"creator(s)":[ "Lars Bak", "Kasper Lund"],
		"development company": "Google"
	};

	var as_json_text = jsonEncode(dart);

	assert(as_json_text == '{"compiled":true,"interpreted":true,"creator(s)":["Lars Bak","Kasper Lund"],"development company":"Google"}');
}


import sequtils

func countJewels(stones, jewels: string): Natural =
  stones.countIt(it in jewels)

echo countJewels("aAAbbbb", "aA")
echo countJewels("ZZ", "z")


use Collection.Generic;

class JewelsStones {
  function : Main(args : String[]) ~ Nil {
    Count("aAAbbbb", "aA")->PrintLine();
    Count("ZZ", "z")->PrintLine();
  }

  function : Count(stones : String, jewels : String) ~ Int {
    bag := Set->New()<CharHolder>;

    each(i : jewels) {
      bag->Insert(jewels->Get(i));
    };

    count := 0;
    each(i : stones) {
      if(bag->Has(stones->Get(i))) {
        count++;
      };
    };

    return count;
  }
}


sub count_jewels {
    my( $j, $s ) = @_;
    my($c,%S);

    $S{$_}++     for split //, $s;
    $c += $S{$_} for split //, $j;
    return "$c\n";
}

print count_jewels 'aA' , 'aAAbbbb';
print count_jewels 'z'  , 'ZZ';


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

typedef struct {
    char *name;
    int weight;
    int value;
} item_t;

item_t items[] = {
    {"map",                      9,   150},
    {"compass",                 13,    35},
    {"water",                  153,   200},
    {"sandwich",                50,   160},
    {"glucose",                 15,    60},
    {"tin",                     68,    45},
    {"banana",                  27,    60},
    {"apple",                   39,    40},
    {"cheese",                  23,    30},
    {"beer",                    52,    10},
    {"suntan cream",            11,    70},
    {"camera",                  32,    30},
    {"T-shirt",                 24,    15},
    {"trousers",                48,    10},
    {"umbrella",                73,    40},
    {"waterproof trousers",     42,    70},
    {"waterproof overclothes",  43,    75},
    {"note-case",               22,    80},
    {"sunglasses",               7,    20},
    {"towel",                   18,    12},
    {"socks",                    4,    50},
    {"book",                    30,    10},
};

int *knapsack (item_t *items, int n, int w) {
    int i, j, a, b, *mm, **m, *s;
    mm = calloc((n + 1) * (w + 1), sizeof (int));
    m = malloc((n + 1) * sizeof (int *));
    m[0] = mm;
    for (i = 1; i <= n; i++) {
        m[i] = &mm[i * (w + 1)];
        for (j = 0; j <= w; j++) {
            if (items[i - 1].weight > j) {
                m[i][j] = m[i - 1][j];
            }
            else {
                a = m[i - 1][j];
                b = m[i - 1][j - items[i - 1].weight] + items[i - 1].value;
                m[i][j] = a > b ? a : b;
            }
        }
    }
    s = calloc(n, sizeof (int));
    for (i = n, j = w; i > 0; i--) {
        if (m[i][j] > m[i - 1][j]) {
            s[i - 1] = 1;
            j -= items[i - 1].weight;
        }
    }
    free(mm);
    free(m);
    return s;
}

int main () {
    int i, n, tw = 0, tv = 0, *s;
    n = sizeof (items) / sizeof (item_t);
    s = knapsack(items, n, 400);
    for (i = 0; i < n; i++) {
        if (s[i]) {
            printf("%-22s %5d %5d\n", items[i].name, items[i].weight, items[i].value);
            tw += items[i].weight;
            tv += items[i].value;
        }
    }
    printf("%-22s %5d %5d\n", "totals:", tw, tv);
    return 0;
}


: sum ( lo hi term -- x ) [ [a,b] ] dip map-sum ; inline

1 100 [ recip ] sum .


: sum 0 s>f 1+ swap ?do i over execute f+ loop drop ;
:noname s>f 1 s>f fswap f/ ; 1 100 sum f.


      FUNCTION SUM(I,LO,HI,TERM)
        SUM = 0
        DO I = LO,HI
          SUM = SUM + TERM
        END DO
      END FUNCTION SUM
      WRITE (6,*) SUM(I,1,100,1.0/I)
      END


Sub Evaluation
    Dim As Integer i, lo = 1, hi = 100
    Dim As Double temp = 0
    For i = lo To hi
        temp += (1/i)  ''r(i)
    Next i
    Print temp
End Sub

Evaluation
Sleep


package main

import "fmt"

var i int

func sum(i *int, lo, hi int, term func() float64) float64 {
    temp := 0.0
    for *i = lo; *i <= hi; (*i)++ {
        temp += term()
    }
    return temp
}

func main() {
    fmt.Printf("%f\n", sum(&i, 1, 100, func() float64 { return 1.0 / float64(i) }))
}


program JsonTest;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.SysUtils,
  Json;

type
  TJsonObjectHelper = class helper for TJsonObject
  public
    class function Deserialize(data: string): TJsonObject; static;
    function Serialize: string;
  end;

{ TJsonObjectHelper }

class function TJsonObjectHelper.Deserialize(data: string): TJsonObject;
begin
  Result := TJSONObject.ParseJSONValue(data) as TJsonObject;
end;

function TJsonObjectHelper.Serialize: string;
begin
  Result := ToJson;
end;

var
  people, deserialized: TJsonObject;
  bar: TJsonArray;
  _json: string;

begin
  people := TJsonObject.Create();
  people.AddPair(TJsonPair.Create('1', 'John'));
  people.AddPair(TJsonPair.Create('2', 'Susan'));

  _json := people.Serialize;
  Writeln(_json);

  deserialized := TJSONObject.Deserialize(_json);
  Writeln(deserialized.Values['2'].Value);

  deserialized := TJSONObject.Deserialize('{"foo":1 , "bar":[10,"apples"]}');

  bar := deserialized.Values['bar'] as TJSONArray;
  Writeln(bar.Items[1].Value);

  deserialized.Free;
  people.Free;

  Readln;
end.


;; JSON standard types : strings, numbers, and arrays (vectors)
(export-json #(6 7 8 9))  →   "[6,7,8,9]"
(export-json #("alpha" "beta" "gamma"))  →   "["alpha","beta","gamma"]"

(json-import "[6,7,8,9]")  →   #( 6 7 8 9)
(json-import #<< ["alpha","beta","gamma"] >>#)  →   #( "alpha" "beta" "gamma")

;; EchoLisp types : dates, rational, complex, big int
(export-json 3/4)  →   "{"_instanceof":"Rational","a":3,"b":4}"
(json-import #<< {"_instanceof":"Rational","a":666,"b":42} >>#)  →   111/7

;; Symbols
(export-json 'Simon-Gallubert)  →   "{"_instanceof":"Symbol","name":"Simon-Gallubert"}"
(json-import #<< {"_instanceof":"Symbol","name":"Antoinette-de-Gabolde"} >>#)
    →   Antoinette-de-Gabolde

;; Lists
(define my-list
    (export-json '( 43 4 5 ( 6 7 ( 8 9 )))))
    →    "{"_instanceof":"List" ,"array":[43,4,5,{"_instanceof":"List",
    "array":[6,7,{"_instanceof":"List",
    "array":[8,9],"circular":false}],"circular":false}],"circular":false}"

(json-import my-list)  →   (43 4 5 (6 7 (8 9)))

;; Structures
(struct Person (name pict))  →   #struct:Person [name pict]
(define antoinette (Person "antoinette" "👰"))   →   # (antoinette 👰)

(export-json antoinette)  →
    "{"_instanceof":"Struct", "struct":"Person","id":17,"fields":["antoinette","👰"]}"
(json-import
    #<< {"_instanceof":"Struct","struct":"Person","id":18,"fields":["simon","🎩"]} >>#)
	→   # (simon 🎩)


function count_jewels(string stones, jewels)
    integer res = 0
    for i=1 to length(stones) do
        res += find(stones[i],jewels)!=0
    end for
    return res
end function
?count_jewels("aAAbbbb","aA")
?count_jewels("ZZ","z")


jewels_and_stones1(Jewels,Stones) = sum([1 : S in Stones, J in Jewels, S == J]).


100H:

/* FIND JEWELS AMONG STONES */
COUNT$JEWELS: PROCEDURE (JEWELS, STONES) BYTE;
    DECLARE (JEWELS, STONES) ADDRESS;
    DECLARE (J BASED JEWELS, S BASED STONES) BYTE;
    DECLARE JFLAG (256) BYTE, I BYTE;

    /* ZERO JEWEL FLAGS */
    DO I=0 TO 255;
        JFLAG(I) = 0;
    END;

    /* LOOP THROUGH JEWELS AND MARK THEM */
    DO WHILE J <> '$';
        JFLAG(J) = 1;
        JEWELS = JEWELS + 1;
    END;

    /* COUNT THE JEWELS AMONG THE STONES */
    I = 0;
    DO WHILE S <> '$';
        I = I + JFLAG(S);
        STONES = STONES + 1;
    END;
    RETURN I;
END COUNT$JEWELS;

/* CP/M BDOS CALL */
BDOS: PROCEDURE (FN, ARG);
    DECLARE FN BYTE, ARG ADDRESS;
    GO TO 5;
END BDOS;

PRINT: PROCEDURE (STR);
    DECLARE STR ADDRESS;
    CALL BDOS(9, STR);
END PRINT;

/* NUMERIC OUTPUT */
PRINT$NUMBER: PROCEDURE (N);
    DECLARE S (4) BYTE INITIAL ('...$');
    DECLARE P ADDRESS, (N, C BASED P) BYTE;
    P = .S(3);
DIGIT:
    P = P-1;
    C = N MOD 10 + '0';
    N = N/10;
    IF N > 0 THEN GO TO DIGIT;
    CALL PRINT(P);
END PRINT$NUMBER;

/* PRINT JEWELS, STONES, AND AMOUNT OF JEWELS IN STONES */
TEST: PROCEDURE (J, S);
    DECLARE (J, S) ADDRESS;
    CALL PRINT(.'''$');
    CALL PRINT(J);
    CALL PRINT(.''' IN ''$');
    CALL PRINT(S);
    CALL PRINT(.''': $');
    CALL PRINT$NUMBER(COUNT$JEWELS(J, S));
    CALL PRINT(.(13,10,'$'));
END TEST;

/* UNFORTUNATELY, THE PL/M COMPILER ACCEPTS A VERY RESTRICTED CHARACTER SET
   IN THE SOURCE CODE. (IT IS THE INTERSECTION OF VARIOUS POPULAR CHARSETS
   FROM THE 1960S.) THIS CHARACTER SET DOES NOT INCLUDE LOWERCASE LETTERS.
   HOWEVER, THIS CODE ASSUMES THE ASCII CHARACTER SET ANYWAY.
   WE CAN INCLUDE LOWERCASE LETTERS ... BY WRITING THEIR ASCII CODES.
   THE OUTPUT WILL BE CORRECT OF COURSE. */

CALL TEST(.( 97,'A$' ), .( 97,'AA',98,98,98,98,'$' ));
CALL TEST(.( 122,'$' ), .( 'ZZZZ$' ));

CALL BDOS(0,0);
EOF


:- system:set_prolog_flag(double_quotes,codes) .

count_jewels(STONEs0,JEWELs0,COUNT)
:-
findall(X,(member(X,JEWELs0),member(X,STONEs0)),ALLs) ,
length(ALLs,COUNT)
.


def countJewels(s, j):
    return sum(x in j for x in s)

print countJewels("aAAbbbb", "aA")
print countJewels("ZZ", "z")


using System;
using System.Collections.Generic;

namespace Tests_With_Framework_4
{

class Bag : IEnumerable<Bag.Item>
        {
            List<Item> items;
            const int MaxWeightAllowed = 400;

            public Bag()
            {
                items = new List<Item>();
            }

            void AddItem(Item i)
            {
                if ((TotalWeight + i.Weight) <= MaxWeightAllowed)
                    items.Add(i);
            }

            public void Calculate(List<Item> items)
            {
                foreach (Item i in Sorte(items))
                {
                    AddItem(i);
                }
            }

            List<Item> Sorte(List<Item> inputItems)
            {
                List<Item> choosenItems = new List<Item>();
                for (int i = 0; i < inputItems.Count; i++)
                {
                    int j = -1;
                    if (i == 0)
                    {
                        choosenItems.Add(inputItems[i]);
                    }
                    if (i > 0)
                    {
                        if (!RecursiveF(inputItems, choosenItems, i, choosenItems.Count - 1, false, ref j))
                        {
                            choosenItems.Add(inputItems[i]);
                        }
                    }
                }
                return choosenItems;
            }

            bool RecursiveF(List<Item> knapsackItems, List<Item> choosenItems, int i, int lastBound, bool dec, ref int indxToAdd)
            {
                if (!(lastBound < 0))
                {
                    if ( knapsackItems[i].ResultWV < choosenItems[lastBound].ResultWV )
                    {
                        indxToAdd = lastBound;
                    }
                    return RecursiveF(knapsackItems, choosenItems, i, lastBound - 1, true, ref indxToAdd);
                }
                if (indxToAdd > -1)
                {
                    choosenItems.Insert(indxToAdd, knapsackItems[i]);
                    return true;
                }
                return false;
            }

            #region IEnumerable<Item> Members
            IEnumerator<Item> IEnumerable<Item>.GetEnumerator()
            {
                foreach (Item i in items)
                    yield return i;
            }
            #endregion

            #region IEnumerable Members
            System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
            {
                return items.GetEnumerator();
            }
            #endregion

            public int TotalWeight
            {
                get
                {
                    var sum = 0;
                    foreach (Item i in this)
                    {
                        sum += i.Weight;
                    }
                    return sum;
                }
            }

            public class Item
            {
                public string Name { get; set; } public int Weight { get; set; } public int Value { get; set; } public int ResultWV { get { return  Weight-Value; } }
                public override string ToString()
                {
                    return "Name : " + Name + "        Wieght : " + Weight + "       Value : " + Value + "     ResultWV : " + ResultWV;
                }
            }
        }

    class Program
    {
        static void Main(string[] args)
        {List<Bag.Item> knapsackItems = new List<Bag.Item>();
            knapsackItems.Add(new Bag.Item() { Name = "Map", Weight = 9, Value = 150 });
            knapsackItems.Add(new Bag.Item() { Name = "Water", Weight = 153, Value = 200 });
            knapsackItems.Add(new Bag.Item() { Name = "Compass", Weight = 13, Value = 35 });
            knapsackItems.Add(new Bag.Item() { Name = "Sandwitch", Weight = 50, Value = 160 });
            knapsackItems.Add(new Bag.Item() { Name = "Glucose", Weight = 15, Value = 60 });
            knapsackItems.Add(new Bag.Item() { Name = "Tin", Weight = 68, Value = 45 });
            knapsackItems.Add(new Bag.Item() { Name = "Banana", Weight = 27, Value = 60 });
            knapsackItems.Add(new Bag.Item() { Name = "Apple", Weight = 39, Value = 40 });
            knapsackItems.Add(new Bag.Item() { Name = "Cheese", Weight = 23, Value = 30 });
            knapsackItems.Add(new Bag.Item() { Name = "Beer", Weight = 52, Value = 10 });
            knapsackItems.Add(new Bag.Item() { Name = "Suntan Cream", Weight = 11, Value = 70 });
            knapsackItems.Add(new Bag.Item() { Name = "Camera", Weight = 32, Value = 30 });
            knapsackItems.Add(new Bag.Item() { Name = "T-shirt", Weight = 24, Value = 15 });
            knapsackItems.Add(new Bag.Item() { Name = "Trousers", Weight = 48, Value = 10 });
            knapsackItems.Add(new Bag.Item() { Name = "Umbrella", Weight = 73, Value = 40 });
            knapsackItems.Add(new Bag.Item() { Name = "WaterProof Trousers", Weight = 42, Value = 70 });
            knapsackItems.Add(new Bag.Item() { Name = "Note-Case", Weight = 22, Value = 80 });
            knapsackItems.Add(new Bag.Item() { Name = "Sunglasses", Weight = 7, Value = 20 });
            knapsackItems.Add(new Bag.Item() { Name = "Towel", Weight = 18, Value = 12 });
            knapsackItems.Add(new Bag.Item() { Name = "Socks", Weight = 4, Value = 50 });
            knapsackItems.Add(new Bag.Item() { Name = "Book", Weight = 30, Value = 10 });
            knapsackItems.Add(new Bag.Item() { Name = "waterproof overclothes ", Weight = 43, Value = 75 });

            Bag b = new Bag();
            b.Calculate(knapsackItems);
            b.All(x => { Console.WriteLine(x); return true; });
            Console.WriteLine(b.Sum(x => x.Weight));
            Console.ReadKey();
        }
    }
}


def sum = { i, lo, hi, term ->
    (lo..hi).sum { i.value = it; term() }
}
def obj = [:]
println (sum(obj, 1, 100, { 1 / obj.value }))


import Control.Monad.ST
import Data.STRef

sum_ :: STRef s Double -> Double -> Double -> ST s Double -> ST s Double
sum_ ref_i lo hi term = sum <$> mapM ((>> term) . writeSTRef ref_i) [lo .. hi]

foo :: Double
foo =
  runST $
  do i <- newSTRef undefined -- initial value doesn't matter
     sum_ i 1 100 $ recip <$> readSTRef i

main :: IO ()
main = print foo


record mutable(value)   # record wrapper to provide mutable access to immutable types

procedure main()
    A := mutable()
    write( sum(A, 1, 100, create 1.0/A.value) )
end

procedure sum(A, lo, hi, term)
    temp := 0
    every A.value := lo to hi do
        temp +:= @^term
    return temp
end


record familyMember
	person person;
	relationships relationship[]?;
end

record person
	firstName string;
	lastName string;
	age int;
end

record relationship
	relationshipType string;
	id int;
end


import extensions;
import extensions'dynamic;

public program()
{
    var json := "{ ""foo"": 1, ""bar"": [10, ""apples""] }";

    var o := json.fromJson();

    console.printLine("json.foo=",o.foo);
    console.printLine("json.bar=",o.bar)
}


(require 'cl-lib)

(cl-assert (fboundp 'json-parse-string))
(cl-assert (fboundp 'json-serialize))

(defvar example "{\"foo\": \"bar\", \"baz\": [1, 2, 3]}")
(defvar example-object '((foo . "bar") (baz . [1 2 3])))

;; decoding
(json-parse-string example) ;=> #s(hash-table [...]))
;; using json.el-style options
(json-parse-string example :object-type 'alist :null-object nil :false-object :json-false)
;;=> ((foo . "bar") (baz . [1 2 3]))
;; using plists for objects
(json-parse-string example :object-type 'plist) ;=> (:foo "bar" :baz [1 2 3])

;; encoding
(json-serialize example-object) ;=> "{\"foo\":\"bar\",\"baz\":[1,2,3]}"


J_n_S <- function(stones  ="aAAbbbb", jewels = "aA") {
  stones <- unlist(strsplit(stones, split = "")) # obtain a character vector
  jewels <- unlist(strsplit(jewels, split = ""))
  count <- sum(stones %in% jewels)
}

print(J_n_S("aAAbbbb", "aA"))
print(J_n_S("ZZ", "z"))
print(J_n_S("lgGKJGljglghGLGHlhglghoIPOgfdtrdDCHnvbnmBVC", "fFgGhH"))


  [ 0 0 rot
    witheach [ bit | ]
    rot witheach
      [ bit over & if
          [ dip 1+ ] ]
    drop ]             is j&s ( $ $ --> n )

  $ "aAAbbbb" $  "aA" j&s echo


#lang racket

(define (jewels-and-stones stones jewels)
  (length (filter (curryr member (string->list jewels)) (string->list stones))))

(module+ main
  (jewels-and-stones "aAAbbbb" "aA")
  (jewels-and-stones "ZZ" "z"))


sub count-jewels ( Str $j, Str $s --> Int ) {
    my %counts_of_all = $s.comb.Bag;
    my @jewel_list    = $j.comb.unique;

    return %counts_of_all ∩ @jewel_list.Bag ?? %counts_of_all{ @jewel_list }.sum !! 0;
}

say count-jewels 'aA' , 'aAAbbbb';
say count-jewels 'z'  , 'ZZ';


Red [
    title: "Jewels and stones"
    red-version: 0.6.4
]

count: function [
    "Returns the number of values in a block for which a function returns true"
    values [any-list! string!] "The values from which to count"
    fn [function!] "A function that returns true or false"
][
    count: 0
    foreach value values [if fn value [count: count + 1]]
    count
]

count-jewels: function [
    "Returns the count of 'jewels' in the 'stones'"
    stones "The values to search for jewels"
    jewels "The values to count in the stones"
][
    result: 0
    foreach jewel jewels [
        result: result + count stones function [stone][stone = jewel]
    ]
]

print count-jewels "aAAbbbb" "aA"
print count-jewels "ZZ" "z"


#include <vector>
#include <string>
#include <iostream>
#include <boost/tuple/tuple.hpp>
#include <set>

int findBestPack( const std::vector<boost::tuple<std::string , int , int> > & ,
      std::set<int> & , const int  ) ;

int main( ) {
   std::vector<boost::tuple<std::string , int , int> > items ;
   //===========fill the vector with data====================
   items.push_back( boost::make_tuple( "" , 0  ,  0 ) ) ;
   items.push_back( boost::make_tuple( "map" , 9 , 150 ) ) ;
   items.push_back( boost::make_tuple( "compass" , 13 , 35 ) ) ;
   items.push_back( boost::make_tuple( "water" , 153 , 200 ) ) ;
   items.push_back( boost::make_tuple( "sandwich", 50 , 160 ) ) ;
   items.push_back( boost::make_tuple( "glucose" , 15 , 60 ) ) ;
   items.push_back( boost::make_tuple( "tin", 68 , 45 ) ) ;
   items.push_back( boost::make_tuple( "banana", 27 , 60 ) ) ;
   items.push_back( boost::make_tuple( "apple" , 39 , 40 ) ) ;
   items.push_back( boost::make_tuple( "cheese" , 23 , 30 ) ) ;
   items.push_back( boost::make_tuple( "beer" , 52 , 10 ) ) ;
   items.push_back( boost::make_tuple( "suntan creme" , 11 , 70 ) ) ;
   items.push_back( boost::make_tuple( "camera" , 32 , 30 ) ) ;
   items.push_back( boost::make_tuple( "T-shirt" , 24 , 15 ) ) ;
   items.push_back( boost::make_tuple( "trousers" , 48 , 10 ) ) ;
   items.push_back( boost::make_tuple( "umbrella" , 73 , 40 ) ) ;
   items.push_back( boost::make_tuple( "waterproof trousers" , 42 , 70 ) ) ;
   items.push_back( boost::make_tuple( "waterproof overclothes" , 43 , 75 ) ) ;
   items.push_back( boost::make_tuple( "note-case" , 22 , 80 ) ) ;
   items.push_back( boost::make_tuple( "sunglasses" , 7 , 20 ) ) ;
   items.push_back( boost::make_tuple( "towel" , 18 , 12 ) ) ;
   items.push_back( boost::make_tuple( "socks" , 4 , 50 ) ) ;
   items.push_back( boost::make_tuple( "book" , 30 , 10 ) ) ;
   const int maximumWeight = 400 ;
   std::set<int> bestItems ; //these items will make up the optimal value
   int bestValue = findBestPack( items , bestItems , maximumWeight ) ;
   std::cout << "The best value that can be packed in the given knapsack is " <<
      bestValue << " !\n" ;
   int totalweight = 0 ;
   std::cout << "The following items should be packed in the knapsack:\n" ;
   for ( std::set<int>::const_iterator si = bestItems.begin( ) ;
	 si != bestItems.end( ) ; si++ ) {
      std::cout << (items.begin( ) + *si)->get<0>( ) << "\n" ;
      totalweight += (items.begin( ) + *si)->get<1>( ) ;
   }
   std::cout << "The total weight of all items is " << totalweight << " !\n" ;
   return 0 ;
}

int findBestPack( const std::vector<boost::tuple<std::string , int , int> > & items ,std::set<int> & bestItems , const int weightlimit ) {
   //dynamic programming approach sacrificing storage space for execution
   //time , creating a table of optimal values for every weight and a
   //second table of sets with the items collected so far in the knapsack
   //the best value is in the bottom right corner of the values table,
   //the set of items in the bottom right corner of the sets' table.
   const int n = items.size( ) ;
   int bestValues [ n ][ weightlimit ] ;
   std::set<int> solutionSets[ n ][ weightlimit ] ;
   std::set<int> emptyset ;
   for ( int i = 0 ; i < n ; i++ ) {
      for ( int j = 0 ; j < weightlimit  ; j++ ) {
	 bestValues[ i ][ j ] = 0 ;
	 solutionSets[ i ][ j ] = emptyset ;
       }
    }
    for ( int i = 0 ; i < n ; i++ ) {
       for ( int weight = 0 ; weight < weightlimit ; weight++ ) {
	  if ( i == 0 )
	     bestValues[ i ][ weight ] = 0 ;
	  else  {
	     int itemweight = (items.begin( ) + i)->get<1>( ) ;
	     if ( weight < itemweight ) {
		bestValues[ i ][ weight ] = bestValues[ i - 1 ][ weight ] ;
		solutionSets[ i ][ weight ] = solutionSets[ i - 1 ][ weight ] ;
	     } else { // weight >= itemweight
		if ( bestValues[ i - 1 ][ weight - itemweight ] +
		   (items.begin( ) + i)->get<2>( ) >
		        bestValues[ i - 1 ][ weight ] ) {
		   bestValues[ i ][ weight ] =
		       bestValues[ i - 1 ][ weight - itemweight ] +
	        	(items.begin( ) + i)->get<2>( ) ;
		  solutionSets[ i ][ weight ] =
		      solutionSets[ i - 1 ][ weight - itemweight ] ;
		  solutionSets[ i ][ weight ].insert( i ) ;
	     }
	     else {
		bestValues[ i ][ weight ] = bestValues[ i - 1 ][ weight ] ;
		solutionSets[ i ][ weight ] = solutionSets[ i - 1 ][ weight ] ;
	     }
	  }
       }
      }
    }
    bestItems.swap( solutionSets[ n - 1][ weightlimit - 1 ] ) ;
    return bestValues[ n - 1 ][ weightlimit - 1 ] ;
}


jensen=: monad define
  'name lo hi expression'=. y
  temp=. 0
  for_n. lo+i.1+hi-lo do.
    (name)=. n
    temp=. temp + ".expression
  end.
)


import java.util.function.*;
import java.util.stream.*;

public class Jensen {
    static double sum(int lo, int hi, IntToDoubleFunction f) {
        return IntStream.rangeClosed(lo, hi).mapToDouble(f).sum();
    }

    public static void main(String args[]) {
        System.out.println(sum(1, 100, (i -> 1.0/i)));
    }
}


var obj;

function sum(o, lo, hi, term) {
  var tmp = 0;
  for (o.val = lo; o.val <= hi; o.val++)
    tmp += term();
  return tmp;
}

obj = {val: 0};
alert(sum(obj, 1, 100, function() {return 1 / obj.val}));


-module(json).
-export([main/0]).

main() ->
	JSON =
		"{
		    \"firstName\": \"John\",
		    \"lastName\": \"Smith\",
		    \"age\": 25,
		    \"address\": {
		        \"streetAddress\": \"21 2nd Street\",
		        \"city\": \"New York\",
		        \"state\": \"NY\",
		        \"postalCode\": \"10021\"
		    },
		    \"phoneNumber\": [
		        {
		            \"type\": \"home\",
		            \"number\": \"212 555-1234\"
		        },
		        {
		            \"type\": \"fax\",
		            \"number\": \"646 555-4567\"
		        }
		    ]
		}",
	Erlang =
		{struct,
			[{"firstName","John"},
	         {"lastName","Smith"},
	         {"age",25},
	         {"address",
	          {struct,[{"streetAddress","21 2nd Street"},
	                   {"city","New York"},
	                   {"state","NY"},
	                   {"postalCode","10021"}]}},
	         {"phoneNumber",
	          {array,[{struct,[{"type","home"},{"number","212 555-1234"}]},
	                  {struct,[{"type","fax"},{"number","646 555-4567"}]}]}}]},
	io:format("JSON -> Erlang\n~p\n",[mochijson:decode(JSON)]),
	io:format("Erlang -> JSON\n~s\n",[mochijson:encode(Erlang)]).


open Newtonsoft.Json
type Person = {ID: int; Name:string}
let xs = [{ID = 1; Name = "First"} ; { ID = 2; Name = "Second"}]

let json = JsonConvert.SerializeObject(xs)
json |> printfn "%s"

let xs1 = JsonConvert.DeserializeObject<Person list>(json)
xs1 |> List.iter(fun x -> printfn "%i  %s" x.ID x.Name)


/*REXX pgm counts how many letters (in the 1st string) are in common with the 2nd string*/
say  count('aAAbbbb', "aA")
say  count('ZZ'     , "z" )
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
count: procedure;  parse arg stones,jewels       /*obtain the two strings specified.    */
       #= 0                                      /*initialize the variable  #  to  zero.*/
                   do j=1  for length(stones)    /*scan STONES for matching JEWELS chars*/
                   x= substr(stones, j, 1)       /*obtain a character of the STONES var.*/
                   if datatype(x, 'M')  then if pos(x, jewels)\==0  then #= # + 1
                   end   /*j*/                   /* [↑]  if a letter and a match, bump #*/
       return #                                  /*return the number of common letters. */


# Project  Jewels and Stones

jewels = "aA"
stones = "aAAbbbb"
see jewelsandstones(jewels,stones) + nl
jewels = "z"
stones = "ZZ"
see jewelsandstones(jewels,stones) + nl

func jewelsandstones(jewels,stones)
        num = 0
        for n = 1 to len(stones)
             pos = substr(jewels,stones[n])
             if pos > 0
                num = num + 1
             ok
        next
        return num


stones, jewels = "aAAbbbb", "aA"

stones.count(jewels)  # => 3


fn count_jewels(stones: &str, jewels: &str) -> u8 {
    let mut count: u8 = 0;
    for cur_char in stones.chars() {
        if jewels.contains(cur_char) {
            count += 1;
        }
    }
    count
}
fn main() {
    println!("{}", count_jewels("aAAbbbb", "aA"));
    println!("{}", count_jewels("ZZ", "z"));
}


object JewelsStones extends App {
  def countJewels(s: String, j: String): Int = s.count(i => j.contains(i))

  println(countJewels("aAAbbbb", "aA"))
  println(countJewels("ZZ", "z"))
}


using System;  // [email protected]
using System.Threading.Tasks;
class Program
{
    static void Main()
    {
        var sw = System.Diagnostics.Stopwatch.StartNew();
        Console.Write(knapSack(400) + "\n" + sw.Elapsed);  // 60 ms
        Console.Read();
    }

    static string knapSack(uint w1)
    {
        uint sol = 0, v1 = 0;
        Parallel.For(1, 9, t =>
        {
            uint j, wi, k, vi, i1 = 1u << w.Length;
            for (uint i = (uint)t; i < i1; i += 8)
            {
                k = wi = vi = 0;
                for (j = i; j > 0; j >>= 1, k++)
                    if ((j & 1) > 0)
                    {
                        if ((wi += w[k]) > w1) break;
                        vi += v[k];
                    }
                if (wi <= w1 && v1 < vi)
                    lock (locker)
                        if (v1 < vi) { v1 = vi; sol = i; }
            }
        });
        string str = "";
        for (uint k = 0; sol > 0; sol >>= 1, k++)
            if ((sol & 1) > 0) str += items[k] + "\n";
        return str;
    }

    static readonly object locker = new object();

    static byte[] w = { 9, 13, 153, 50, 15, 68, 27, 39, 23, 52, 11,
                          32, 24, 48, 73, 42, 43, 22, 7, 18, 4, 30 },

                  v = { 150, 35, 200, 160, 60, 45, 60, 40, 30, 10, 70,
                          30, 15, 10, 40, 70, 75, 80, 20, 12, 50, 10 };

    static string[] items = {"map","compass","water","sandwich","glucose","tin",
                             "banana","apple","cheese","beer","suntan cream",
                             "camera","T-shirt","trousers","umbrella",
                             "waterproof trousers","waterproof overclothes",
                             "note-case","sunglasses","towel","socks","book"};
}


def sum(lo; hi; term):
  reduce range(lo; hi+1) as $i (0; . + ($i|term));

# The task:
sum(1;100;1/.)


macro sum(i, loname, hiname, term)
    return quote
        lo = $loname
        hi = $hiname
        tmp = 0.0
        for i in lo:hi
            tmp += $term
        end
        return tmp
    end
end

i = 0
@sum(i, 1, 100, 1.0 / i)


fun sum(lo: Int, hi: Int, f: (Int) -> Double) = (lo..hi).sumByDouble(f)

fun main(args: Array<String>) = println(sum(1, 100, { 1.0 / it }))


function sum(var, a, b, str)
  local ret = 0
  for i = a, b do
    ret = ret + setfenv(loadstring("return "..str), {[var] = i})()
  end
  return ret
end
print(sum("i", 1, 100, "1/i"))


Module Jensen`s_Device {
      Def double i
      Report Lazy$(1/i)  ' display the definition of the lazy function
      Function Sum (&i, lo, hi, &f()) {
            def double temp
            For i= lo to hi {
                  temp+=f()
            }
            =temp
      }
      Print Sum(&i, 1, 100, Lazy$(1/i))==5.1873775176392  ' true
      Print i=101 ' true
}
Jensen`s_Device


USING: json.writer json.reader ;

SYMBOL: foo

! Load a JSON string into a data structure
"[[\"foo\",1],[\"bar\",[10,\"apples\"]]]" json> foo set

! Create a new data structure and serialize into JSON
{ { "blue" { "ocean" "water" } } >json


using util

class Json
{
  public static Void main ()
  {
    Str input := """{"blue": [1, 2], "ocean": "water"}"""
    Map jsonObj := JsonInStream(input.in).readJson

    echo ("Value for 'blue' is: " + jsonObj["blue"])
    jsonObj["ocean"] = ["water":["cold", "blue"]]
    Map ocean := jsonObj["ocean"]
    echo ("Value for 'ocean/water' is: " + ocean["water"])
    output := JsonOutStream(Env.cur.out)
    output.writeJson(jsonObj)
    echo ()
  }
}


func countJewels(s, j) {
    s.chars.count { |c|
        j.contains(c)
    }
}

say countJewels("aAAbbbb", "aA")    #=> 3
say countJewels("ZZ", "z")          #=> 0


*       See how many jewels are among the stones
        DEFINE('JEWELS(JWL,STN)')               :(JEWELS_END)
JEWELS  JEWELS = 0
        JWL = ANY(JWL)
JMATCH  STN JWL = ''                            :F(RETURN)
        JEWELS = JEWELS + 1                     :(JMATCH)
JEWELS_END

*       Example from the task (prints 3)
        OUTPUT = JEWELS('aA','aAAbbbb')
*       Example with no jewels (prints 0)
        OUTPUT = JEWELS('z','ZZ')
END


-- See how many jewels are among the stones
DECLARE @S VARCHAR(1024) 	=	'AaBbCcAa'
,	@J VARCHAR(1024)	=	'aA';

DECLARE @SLEN	INT = len(@S);
DECLARE @JLEN	INT = len(@J);
DECLARE @TCNT	INT = 0;

DECLARE @SPOS	INT = 1;	-- curr position in @S
DECLARE @JPOS	INT = 1;	-- curr position in @J
DECLARE @FCHR	CHAR(1);	-- char to find

while @JPOS <= @JLEN
BEGIN

	SET @FCHR = SUBSTRING(@J, @JPOS, 1);

	SET @SPOS = 1;

	while @SPOS > 0 AND @SPOS <= @SLEN
	BEGIN

		SET @SPOS = charindex(@FCHR, @S COLLATE Latin1_General_CS_AS, @SPOS);

		IF @SPOS > 0 BEGIN
			SET @TCNT = @TCNT + 1;
			SET @SPOS = @SPOS + 1;
		END
	END

	SET @JPOS = @JPOS + 1;
END
print 'J='+@J+' S='+@S+' TOTAL = '+CAST(@TCNT AS VARCHAR(8));


func countJewels(_ stones: String, _ jewels: String) -> Int {
  return stones.map({ jewels.contains($0) ? 1 : 0 }).reduce(0, +)
}

print(countJewels("aAAbbbb", "aA"))
print(countJewels("ZZ", "z"))


(def item-data
  [ "map"         9 150
    "compass"    13  35
    "water"     153 200
    "sandwich"   50 160
    "glucose"    15  60
    "tin"        68  45
    "banana"     27  60
    "apple"      39  40
    "cheese"     23  30
    "beer"       52  10
    "suntan cream"   11  70
    "camera"     32  30
    "t-shirt"    24  15
    "trousers"   48  10
    "umbrella"   73  40
    "waterproof trousers"    42  70
    "waterproof overclothes" 43  75
    "note-case"  22  80
    "sunglasses"  7  20
    "towel"      18  12
    "socks"       4  50
    "book"       30  10])

(defstruct item :name :weight :value)

(def items (vec (map #(apply struct item %) (partition 3 item-data))))


sum[term_, i_, lo_, hi_] := Block[{temp = 0},
   				Do[temp = temp + term, {i, lo, hi}];
   				temp];
SetAttributes[sum, HoldFirst];


mysum(e, v, lo, hi) := block([s: 0], for i from lo thru hi do s: s + subst(v=i, e), s)$

mysum(1/n, n, 1, 10);
7381/2520

/* compare with builtin sum */
sum(1/n, n, 1, 10);
7381/2520

/* what if n is assigned a value ? */
n: 200$

/* still works */
mysum(1/n, n, 1, 10);
7381/2520


import COM.ibm.netrexx.process.

class JensensDevice

  properties static
  interpreter=NetRexxA
  exp=Rexx ""
  termMethod=Method

  method main(x=String[]) static
    say sum('i',1,100,'1/i')

  method sum(i,lo,hi,term) static SIGNALS IOException,NoSuchMethodException,IllegalAccessException,InvocationTargetException
    sum=0
    loop iv=lo to hi
      sum=sum+termeval(i,iv,term)
    end
    return sum

  method termeval(i,iv,e) static returns Rexx SIGNALS IOException,NoSuchMethodException,IllegalAccessException,InvocationTargetException
    if e\=exp then interpreter=null
    exp=e

    if interpreter=null then do
      termpgm='method term('i'=Rexx) static returns rexx;return' e
      fw=FileWriter("termpgm.nrx")
      fw.write(termpgm,0,termpgm.length)
      fw.close
      interpreter=NetRexxA()
      interpreter.parse([String 'termpgm.nrx'],[String 'nocrossref'])
      termClass=interpreter.getClassObject(null,'termpgm')
      classes=[interpreter.getClassObject('netrexx.lang', 'Rexx', 0)]
      termMethod=termClass.getMethod('term', classes)
    end

    return Rexx termMethod.invoke(null,[iv])


var i: int

proc harmonicSum(i: var int; lo, hi: int; term: proc: float): float =
  i = lo
  while i <= hi:
    result += term()
    inc i

echo harmonicSum(i, 1, 100, proc: float = 1 / i)


bundle Default {
  class Jensens {
    i : static : Int;

    function : Sum(lo : Int, hi : Int, term : () ~ Float) ~ Float {
      temp := 0.0;

      for(i := lo; i <= hi; i += 1;) {
        temp += term();
      };

      return temp;
    }

    function : term() ~ Float {
      return 1.0 / i;
    }

    function : Main(args : String[]) ~ Nil {
      Sum(1, 100, term() ~ Float)->PrintLine();
    }
  }
}


println( eval('{ "foo": 1, "bar": [10, "apples"] }') )


package main

import "encoding/json"
import "fmt"

func main() {
    var data interface{}
    err := json.Unmarshal([]byte(`{"foo":1, "bar":[10, "apples"]}`), &data)
    if err == nil {
        fmt.Println(data)
    } else {
        fmt.Println(err)
    }

    sample := map[string]interface{}{
        "blue":  []interface{}{1, 2},
        "ocean": "water",
    }
    json_string, err := json.Marshal(sample)
    if err == nil {
        fmt.Println(string(json_string))
    } else {
        fmt.Println(err)
    }
}


gw.lang.reflect.json.Json#fromJson( String json ) : javax.script.Bindings


proc shavej {stones jewels} {
    set n 0
    foreach c [split $stones {}] {
        incr n [expr { [string first $c $jewels] >= 0 }]
    }
    return $n
}
puts [shavej aAAbbbb aA]
puts [shavej ZZ z]


variable "jewels" {
  default = "aA"
}

variable "stones" {
  default = "aAAbbbb"
}

locals {
   jewel_list = split("", var.jewels)
   stone_list = split("", var.stones)
   found_jewels = [for s in local.stone_list: s if contains(local.jewel_list, s)]
}

output "jewel_count" {
  value = length(local.found_jewels)
}


#lang transd

MainModule: {
    countJewels: (λ j String() st String() locals: n 0
        (for s in st do
            (if (contains j s) (+= n 1)))
        (ret n)
    ),
    _start: (λ (lout (countJewels "aA" "aAAbbbb"))
               (lout (countJewels "b" "BB")))
}


Function count_jewels(stones As String, jewels As String) As Integer
    Dim res As Integer: res = 0
    For i = 1 To Len(stones)
        res = res - (InStr(1, jewels, Mid(stones, i, 1), vbBinaryCompare) <> 0)
    Next i
    count_jewels = res
End Function
Public Sub main()
    Debug.Print count_jewels("aAAbbbb", "aA")
    Debug.Print count_jewels("ZZ", "z")
End Sub


Module Module1

    Function Count(stones As String, jewels As String) As Integer
        Dim bag = jewels.ToHashSet
        Return stones.Count(AddressOf bag.Contains)
    End Function

    Sub Main()
        Console.WriteLine(Count("aAAbbbb", "Aa"))
        Console.WriteLine(Count("ZZ", "z"))
    End Sub

End Module


;;; memoize
(defmacro mm-set (p v) `(if ,p ,p (setf ,p ,v)))

(defun knapsack (max-weight items)
  (let ((cache (make-array (list (1+ max-weight) (1+ (length items)))
			   :initial-element nil)))

    (labels ((knapsack1 (spc items)
	(if (not items) (return-from knapsack1 (list 0 0 '())))
	(mm-set (aref cache spc (length items))
		(let* ((i (first items))
		       (w (second i))
		       (v (third i))
		       (x (knapsack1 spc (cdr items))))
		  (if (> w spc) x
		    (let* ((y (knapsack1 (- spc w) (cdr items)))
			   (v (+ v (first y))))
		      (if (< v (first x)) x
			(list v (+ w (second y)) (cons i (third y))))))))))

      (knapsack1 max-weight items))))

(print
  (knapsack 400
	    '((map 9 150) (compass 13 35) (water 153 200) (sandwich 50 160)
	      (glucose 15 60) (tin 68 45)(banana 27 60) (apple 39 40)
	      (cheese 23 30) (beer 52 10) (cream 11 70) (camera 32 30)
	      (T-shirt 24 15) (trousers 48 10) (umbrella 73 40)
	      (trousers 42 70) (overclothes 43 75) (notecase 22 80)
	      (glasses 7 20) (towel 18 12) (socks 4 50) (book 30 10))))


let i = ref 42 (* initial value doesn't matter *)

let sum' i lo hi term =
  let result = ref 0. in
    i := lo;
    while !i <= hi do
      result := !result +. term ();
      incr i
    done;
    !result

let () =
  Printf.printf "%f\n" (sum' i 1 100 (fun () -> 1. /. float !i))


: mysum(lo, hi, term)  | i | 0 lo hi for: i [ i term perform + ] ;


declare
  fun {Sum I Lo Hi Term}
     Temp = {NewCell 0.0}
  in
     I := Lo
     for while:@I =< Hi do
        Temp := @Temp + {Term}
        I := @I + 1
     end
     @Temp
  end
  I = {NewCell unit}
in
  {Show {Sum I 1 100 fun {$} 1.0 / {Int.toFloat @I} end}}


program Jensens_Device;

{$IFDEF FPC}
  {$MODE objFPC}
{$ENDIF}

type
  tTerm = function(i: integer): real;

function term(i: integer): real;
begin
  term := 1 / i;
end;

function sum(var i: LongInt; lo, hi: integer; term: tTerm): real;
begin
  result := 0;
  i := lo;
  while i <= hi do
  begin
    result := result + term(i);
    inc(i);
  end;
end;

var
  i: LongInt;

begin
  writeln(sum(i, 1, 100, @term));
  {$IFNDEF UNIX}  readln; {$ENDIF}
end.


def slurper = new groovy.json.JsonSlurper()
def result = slurper.parseText('''
{
    "people":[
        {"name":{"family":"Flintstone","given":"Frederick"},"age":35,"relationships":{"wife":"people[1]","child":"people[4]"}},
        {"name":{"family":"Flintstone","given":"Wilma"},"age":32,"relationships":{"husband":"people[0]","child":"people[4]"}},
        {"name":{"family":"Rubble","given":"Barnard"},"age":30,"relationships":{"wife":"people[3]","child":"people[5]"}},
        {"name":{"family":"Rubble","given":"Elisabeth"},"age":32,"relationships":{"husband":"people[2]","child":"people[5]"}},
        {"name":{"family":"Flintstone","given":"Pebbles"},"age":1,"relationships":{"mother":"people[1]","father":"people[0]"}},
        {"name":{"family":"Rubble","given":"Bam-Bam"},"age":1,"relationships":{"mother":"people[3]","father":"people[2]"}},
    ]
}
''')


$data = json_decode(''{ "foo": 1, "bar": [10, "apples"] }'');

$sample = ["blue" => [1, 2], "ocean" => "water"];
$jsonstring = json_encode($sample, ["pretty_print" => true]);


LOCAL arr
hb_jsonDecode( '[101,[26,"Test1"],18,false]', @arr )


{-# LANGUAGE OverloadedStrings #-}

import Data.Aeson
import Data.Attoparsec (parseOnly)
import Data.Text
import qualified Data.ByteString.Lazy.Char8 as B
import qualified Data.ByteString.Char8 as S

testdoc = object [
    "foo"   .= (1 :: Int),
    "bar"   .= ([1.3, 1.6, 1.9] :: [Double]),
    "baz"   .= ("some string" :: Text),
    "other" .= object [
        "yes" .= ("sir" :: Text)
        ]
    ]

main = do
    let out = encode testdoc
    B.putStrLn out
    case parseOnly json (S.concat $ B.toChunks out) of
        Left e -> error $ "strange error re-parsing json: " ++ (show e)
        Right v | v /= testdoc -> error "documents not equal!"
        Right v | otherwise    -> print v


fn js(stones string, jewels string) int {
	mut n := 0
    for b in stones.bytes() {
        if jewels.index_u8(b) >= 0 {
            n++
        }
    }
    return n
}

fn main() {
    println(js("aAAbbbb", "aA"))
}


var countJewels = Fn.new { |s, j| s.count { |c| j.contains(c) } }

System.print(countJewels.call("aAAbbbb", "aA"))
System.print(countJewels.call("ZZ", "z"))


string 0;       \Use zero-terminated strings

func Count(Stones, Jewels);
\Return number of letters in Stones that match letters in Jewels
char Stones, Jewels;
int  Cnt, I, J;
[Cnt:= 0;
I:= 0;
while Jewels(I) do
    [J:= 0;
    while Stones(J) do
        [if Stones(J) = Jewels(I) then Cnt:= Cnt+1;
        J:= J+1;
        ];
    I:= I+1;
    ];
return Cnt;
];

[IntOut(0, Count("aAAbbbb", "aA"));  CrLf(0);
 IntOut(0, Count("ZZ", "z"));  CrLf(0);
 IntOut(0, Count("pack my box with five dozen liquor jugs", "aeiou"));  CrLf(0);
]


fcn countJewels(a,b){ a.inCommon(b).len() }


require "bit_array"

struct BitArray
  def clone
    BitArray.new(size).tap { |new| new.to_slice.copy_from (to_slice) }
  end
end

record Item, name : String, weight : Int32, value : Int32

record Selection, mask : BitArray, cur_index : Int32, total_value : Int32

class Knapsack
  @threshold_value = 0
  @threshold_choice : Selection?
  getter checked_nodes = 0

  def knapsack_step(taken, items, remaining_weight)
    if taken.total_value > @threshold_value
      @threshold_value = taken.total_value
      @threshold_choice = taken
    end
    candidate_index = items.index(taken.cur_index) { |item| item.weight <= remaining_weight }
    return nil unless candidate_index
    @checked_nodes += 1
    candidate = items[candidate_index]
    # candidate is a best of available items, so if we fill remaining value with it
    # and still don't reach the threshold, the branch is wrong
    return nil if taken.total_value + 1.0 * candidate.value / candidate.weight * remaining_weight < @threshold_value
    # now recursively check both variants
    mask = taken.mask.clone
    mask[candidate_index] = true
    knapsack_step Selection.new(mask, candidate_index + 1, taken.total_value + candidate.value), items, remaining_weight - candidate.weight
    mask = taken.mask.clone
    mask[candidate_index] = false
    knapsack_step Selection.new(mask, candidate_index + 1, taken.total_value), items, remaining_weight
  end

  def select(items, max_weight)
    @checked_variants = 0
    # sort by descending relative value
    list = items.sort_by { |item| -1.0 * item.value / item.weight }
    # use heuristic of relative value as an initial estimate for branch&bounds
    w = max_weight
    heur_list = list.take_while { |item| w -= item.weight; w > 0 }
    nothing = Selection.new(BitArray.new(items.size), 0, 0)
    @threshold_value = heur_list.sum(&.value) - 1
    @threshold_choice = nothing
    knapsack_step(nothing, list, max_weight)
    selected = @threshold_choice.not_nil!
    result = [] of Item
    selected.mask.each_with_index { |v, i| result << list[i] if v }
    result
  end
end

possible = [
  Item.new("map", 9, 150),
  Item.new("compass", 13, 35),
  Item.new("water", 153, 200),
  Item.new("sandwich", 50, 160),
  Item.new("glucose", 15, 60),
  Item.new("tin", 68, 45),
  Item.new("banana", 27, 60),
  Item.new("apple", 39, 40),
  Item.new("cheese", 23, 30),
  Item.new("beer", 52, 10),
  Item.new("suntan cream", 11, 70),
  Item.new("camera", 32, 30),
  Item.new("T-shirt", 24, 15),
  Item.new("trousers", 48, 10),
  Item.new("umbrella", 73, 40),
  Item.new("waterproof trousers", 42, 70),
  Item.new("waterproof overclothes", 43, 75),
  Item.new("note-case", 22, 80),
  Item.new("sunglasses", 7, 20),
  Item.new("towel", 18, 12),
  Item.new("socks", 4, 50),
  Item.new("book", 30, 10),
]

solver = Knapsack.new
used = solver.select(possible, 400)
puts "optimal choice: #{used.map(&.name)}"
puts "total weight #{used.sum(&.weight)}, total value #{used.sum(&.value)}"
puts "checked nodes: #{solver.checked_nodes}"


with javascript_semantics
function sumr(integer lo, hi, rid)
    atom res = 0
    for i=lo to hi do
        res += rid(i)
    end for
    return res
end function

function reciprocal(atom i) return 1/i end function

?sumr(1, 100, reciprocal)


:-  %say
|=  [^ [[email protected] ~] ~]
:-  %noun
  =+  obj=(need (poja in))                              :: try parse to json
  =+  typ=$:([email protected] [email protected])                         :: datastructure
  =+  spec=(ot name/so age/ni ~):jo                     :: parsing spec
  ?.  ?=([%o *] obj)                                    :: isnt an object?
    ~
  =+  ^=  o
    %.  %.  (spec obj)                                  :: parse with spec
      need                                              :: panic if failed
    ,typ                                                :: cast to type
  =.  age.o  +(age.o)                                   :: increment its age...
  %:  crip  %:  pojo                                    :: pretty-print result
    (jobe [%name s/name.o] [%age n/(crip <age.o>)] ~)   :: convert back to json


NB.               character classes:
NB. 0: whitespace
NB. 1: "
NB. 2: \
NB. 3: [ ] , { } :
NB. 4: ordinary
classes=.3<. '"\[],{}:' (#@[ |&>: i.) a.
classes=.0 (I.a.e.' ',CRLF,TAB)} (]+4*0=])classes

words=:(0;(0 10#:10*".;._2]0 :0);classes)&;: NB. states:
  0.0  1.1  2.1  3.1  4.1  NB. 0 whitespace
  1.0  5.0  6.0  1.0  1.0  NB. 1 "
  4.0  4.0  4.0  4.0  4.0  NB. 2 \
  0.3  1.2  2.2  3.2  4.2  NB. 3 { : , } [ ]
  0.3  1.2  2.0  3.2  4.0  NB. 4 ordinary
  0.3  1.2  2.2  3.2  4.2  NB. 5 ""
  1.0  1.0  1.0  1.0  1.0  NB. 6 "\
)

tokens=. ;:'[ ] , { } :'
actions=: lBra`rBracket`comma`lBra`rBrace`colon`value

NB. action verbs argument conventions:
NB.   x -- boxed json word
NB.   y -- boxed json state stack
NB.   result -- new boxed json state stack
NB.
NB. json state stack is an list of boxes of incomplete lists
NB. (a single box for complete, syntactically valid json)
jsonParse=: 0 {:: (,a:) ,&.> [: [email protected](tokens&[email protected][)/ [:|.a:,words

lBra=: a: ,~ ]
rBracket=: _2&}[email protected]], [:< _2&{::@], _1&{@]
comma=: ]
rBrace=: _2&}[email protected]], [:< _2&{::@](, <)  [:|: (2,~ [: -:@$ _1&{::@]) $ _1&{::@]
colon=: ]
value=: _1&}[email protected]], [:< _1&{::@], jsonValue&.>@[

NB. hypothetically, jsonValue should strip double quotes
NB. interpret back slashes
NB. and recognize numbers
jsonValue=:]

require'strings'
jsonSer2=: [email protected](<"_1^:(0>.#@$-1:))
jsonSer1=: ']' ,~ '[' }:@;@; (',' ,~ jsonSerialize)&.>
jsonSer0=: '"', [email protected]:":, '"'"_
jsonEsc=: rplc&(<;._1' \ \\ " \"')
jsonSerialize=:jsonSer0`[email protected](*@L.)


import std.stdio, std.algorithm, std.typecons, std.array, std.range;

struct Item { string name; int weight, value; }

Item[] knapsack01DinamicProgramming(immutable Item[] items, in int limit)
pure nothrow @safe {
    auto tab = new int[][](items.length + 1, limit + 1);

    foreach (immutable i, immutable it; items)
        foreach (immutable w; 1 .. limit + 1)
            tab[i + 1][w] = (it.weight > w) ? tab[i][w] :
                max(tab[i][w], tab[i][w - it.weight] + it.value);

    typeof(return) result;
    int w = limit;
    foreach_reverse (immutable i, immutable it; items)
        if (tab[i + 1][w] != tab[i][w]) {
            w -= it.weight;
            result ~= it;
        }

    return result;
}

void main() @safe {
    enum int limit = 400;
    immutable Item[] items = [
        {"apple",      39,  40}, {"banana",        27,  60},
        {"beer",       52,  10}, {"book",          30,  10},
        {"camera",     32,  30}, {"cheese",        23,  30},
        {"compass",    13,  35}, {"glucose",       15,  60},
        {"map",         9, 150}, {"note-case",     22,  80},
        {"sandwich",   50, 160}, {"socks",          4,  50},
        {"sunglasses",  7,  20}, {"suntan cream",  11,  70},
        {"t-shirt",    24,  15}, {"tin",           68,  45},
        {"towel",      18,  12}, {"trousers",      48,  10},
        {"umbrella",   73,  40}, {"water",        153, 200},
        {"waterproof overclothes", 43, 75},
        {"waterproof trousers",    42, 70}];

    immutable bag = knapsack01DinamicProgramming(items, limit);
    writefln("Items:\n%-(  %s\n%)", bag.map!q{ a.name }.retro);
    const t = reduce!q{ a[] += [b.weight, b.value] }([0, 0], bag);
    writeln("\nTotal weight and value: ", t[0] <= limit ? t : [0, 0]);
}


(scl 6)

(de jensen (I Lo Hi Term)
   (let Temp 0
      (set I Lo)
      (while (>= Hi (val I))
         (inc 'Temp (Term))
         (inc I) )
      Temp ) )

(let I (box)  # Create indirect reference
   (format
      (jensen I 1 100 '(() (*/ 1.0 (val I))))
      *Scl ) )


Prototype.d func()

Global i

Procedure.d Sum(*i.Integer, lo, hi, *term.func)
  Protected Temp.d
  For i=lo To hi
    temp + *term()
  Next
  ProcedureReturn Temp
EndProcedure

Procedure.d term_func()
  ProcedureReturn 1/i
EndProcedure

Answer.d = Sum(@i, 1, 100, @term_func())


class Ref(object):
    def __init__(self, value=None):
        self.value = value

def harmonic_sum(i, lo, hi, term):
    # term is passed by-name, and so is i
    temp = 0
    i.value = lo
    while i.value <= hi:  # Python "for" loop creates a distinct which
        temp += term() # would not be shared with the passed "i"
        i.value += 1   # Here the actual passed "i" is incremented.
    return temp

i = Ref()

# note the correspondence between the mathematical notation and the
# call to sum it's almost as good as sum(1/i for i in range(1,101))
print harmonic_sum(i, 1, 100, lambda: 1.0/i.value)


import com.google.gson.Gson;

public class JsonExample {

	public static void main(String[] args) {
		Gson gson = new Gson();
		String json = "{ \"foo\": 1, \"bar\": [ \"10\", \"apples\"] }";

		MyJsonObject obj = gson.fromJson(json, MyJsonObject.class);

		System.out.println(obj.getFoo());

		for(String bar : obj.getBar()) {
			System.out.println(bar);
		}

		obj = new MyJsonObject(2, new String[] { "20", "oranges" });
		json = gson.toJson(obj);

		System.out.println(json);
	}

}

class MyJsonObject {

	private int foo;
	private String[] bar;

	public MyJsonObject(int foo, String[] bar) {
		this.foo = foo;
		this.bar = bar;
	}

	public int getFoo() {
		return foo;
	}

	public String[] getBar() {
		return bar;
	}

}


var data = JSON.parse('{ "foo": 1, "bar": [10, "apples"] }');

var sample = { "blue": [1,2], "ocean": "water" };
var json_string = JSON.stringify(sample);


List solveKnapsack(items, maxWeight) {
  int MIN_VALUE=-100;
  int N = items.length; // number of items
  int W = maxWeight; // maximum weight of knapsack

  List profit = new List(N+1);
  List weight = new List(N+1);

  // generate random instance, items 1..N
  for(int n = 1; n<=N; n++) {
    profit[n] = items[n-1][2];
    weight[n] = items[n-1][1];

  }

  // opt[n][w] = max profit of packing items 1..n with weight limit w
  // sol[n][w] = does opt solution to pack items 1..n with weight limit w include item n?
  List<List<int>> opt = new List<List<int>>(N+1);
  for (int i=0; i<N+1; i++) {
    opt[i] = new List<int>(W+1);
    for(int j=0; j<W+1; j++) {
      opt[i][j] = MIN_VALUE;
    }
  }

  List<List<bool>> sol = new List<List<bool>>(N+1);
  for (int i=0; i<N+1; i++) {
    sol[i] = new List<bool>(W+1);
    for(int j=0; j<W+1; j++) {
      sol[i][j] = false;
    }
  }

  for(int n=1; n<=N; n++) {
    for (int w=1; w <= W; w++) {
      // don't take item n
      int option1 = opt[n-1][w];

      // take item n
      int option2 = MIN_VALUE;
      if (weight[n] <= w) {
        option2 = profit[n] + opt[n-1][w - weight[n]];
      }

      // select better of two options
      opt[n][w] = Math.max(option1, option2);
      sol[n][w] = (option2 > option1);
    }
  }

  // determine which items to take
  List<List> packItems = new List<List>();
  List<bool> take = new List(N+1);
  for (int n = N, w = W; n > 0; n--) {
    if (sol[n][w]) {
      take[n] = true;
      w = w - weight[n];
      packItems.add(items[n-1]);
    } else {
      take[n] = false;
    }
  }

  return packItems;

}

main() {
  List knapsackItems = [];
  knapsackItems.add(["map", 9, 150]);
  knapsackItems.add(["compass", 13, 35]);
  knapsackItems.add(["water", 153, 200]);
  knapsackItems.add(["sandwich", 50, 160]);
  knapsackItems.add(["glucose", 15, 60]);
  knapsackItems.add(["tin", 68, 45]);
  knapsackItems.add(["banana", 27, 60]);
  knapsackItems.add(["apple", 39, 40]);
  knapsackItems.add(["cheese", 23, 30]);
  knapsackItems.add(["beer", 52, 10]);
  knapsackItems.add(["suntan cream", 11, 70]);
  knapsackItems.add(["camera", 32, 30]);
  knapsackItems.add(["t-shirt", 24, 15]);
  knapsackItems.add(["trousers", 48, 10]);
  knapsackItems.add(["umbrella", 73, 40]);
  knapsackItems.add(["waterproof trousers", 42, 70]);
  knapsackItems.add(["waterproof overclothes", 43, 75]);
  knapsackItems.add(["note-case", 22, 80]);
  knapsackItems.add(["sunglasses", 7, 20]);
  knapsackItems.add(["towel", 18, 12]);
  knapsackItems.add(["socks", 4, 50]);
  knapsackItems.add(["book", 30, 10]);
  int maxWeight = 400;
  Stopwatch sw = new Stopwatch.start();
  List p = solveKnapsack(knapsackItems, maxWeight);
  sw.stop();
  int totalWeight = 0;
  int totalValue = 0;
  print(["item","profit","weight"]);
  p.forEach((var i) { print("${i}"); totalWeight+=i[1]; totalValue+=i[2]; });
  print("Total Value = ${totalValue}");
  print("Total Weight = ${totalWeight}");
  print("Elapsed Time = ${sw.elapsedInMs()}ms");

}


name$[] = [ "map" "compass" "water" "sandwich" "glucose" "tin" "banana" "apple" "cheese" "beer" "suntan cream" "camera" "t-shirt" "trousers" "umbrella" "waterproof trousers" "waterproof overclothes" "note-case" "sunglasses" "towel" "socks" "book" ]
weight[] = [ 9 13 153 50 15 68 27 39 23 52 11 32 24 48 73 42 43 22 7 18 4 30 ]
value[] = [ 150 35 200 160 60 45 60 40 30 10 70 30 15 10 40 70 75 80 20 12 50 10 ]
max_w = 400
#
func solve i w . items[] wres vres .
  if i < 0
    wres = 0
    vres = 0
    items[] = [ ]
  elif weight[i] > w
    call solve i - 1 w items[] wres vres
  else
    call solve i - 1 w items[] wres vres
    call solve i - 1 w - weight[i] items1[] w1 v1
    v1 += value[i]
    if v1 > vres
      swap items[] items1[]
      items[] &= i
      wres = w1 + weight[i]
      vres = v1
    .
  .
.
call solve len weight[] - 1 max_w items[] w v
print "weight: " & w
print "value: " & v
print "items:"
for i range len items[]
  print "  " & name$[items[i]]
.


sum <- function(var, lo, hi, term)
  eval(substitute({
    .temp <- 0;
    for (var in lo:hi) {
      .temp <- .temp + term
    }
    .temp
  }, as.list(match.call()[-1])),
  enclos=parent.frame())

sum(i, 1, 100, 1/i) #prints 5.187378

##and because of enclos=parent.frame(), the term can involve variables in the caller's scope:
x <- -1
sum(i, 1, 100, i^x) #5.187378


#lang algol60
begin
   integer i;
   real procedure sum (i, lo, hi, term);
      value lo, hi;
      integer i, lo, hi;
      real term;
      comment term is passed by-name, and so is i;
   begin
      real temp;
      temp := 0;
      for i := lo step 1 until hi do
         temp := temp + term;
      sum := temp
   end;
   comment note the correspondence between the mathematical notation and the call to sum;
   printnln (sum (i, 1, 100, 1/i))
end


sub sum($i is rw, $lo, $hi, &term) {
    my $temp = 0;
    loop ($i = $lo; $i <= $hi; $i++) {
        $temp += term;
    }
    return $temp;
}

my $i;
say sum $i, 1, 100, { 1 / $i };


public num Jenssen(int lo, int hi, num (int i) term){
	temp = 0;
	while (lo <= hi){
		temp += term(lo);
		lo += 1;}
	return temp;
}


/*REXX program demonstrates  Jensen's device  (via call subroutine,  and args by name). */
parse arg d .                                    /*obtain optional argument from the CL.*/
if d=='' | d==","  then d= 100                   /*Not specified?  Then use the default.*/
numeric digits d                                 /*use  D  decimal digits (9 is default)*/
say 'using '    d    " decimal digits:"          /*display what's being used for digits.*/
say
say  sum( i,  1,  100,  "1/i" )                  /*invoke  SUM  (100th harmonic number).*/
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
sum: procedure;   parse arg j,start,finish,exp;               $= 0

     interpret  'do'   j   "="   start   'to'   finish   ";   $=$+"   exp   ';   end'

 /*comment      ────   ═   ───   ═════   ────   ══════   ──────────   ═══   ─────────   */
 /*comment       lit  var  lit    var     lit     var      literal    var    literal    */

     return $


prompt$ jsish
Jsish interactive: see 'help [cmd]'
# var data = JSON.parse('{ "foo": 1, "bar": [10, "apples"] }');
variable
# data
{ bar:[ 10, "apples" ], foo:1 }

# var sample = { blue: [1,2], ocean: "water" };
variable
# sample
{ blue:[ 1, 2 ], ocean:"water" }

# puts(JSON.stringify(sample))
{ "blue":[ 1, 2 ], "ocean":"water" }


# Pkg.add("JSON") ... an external library http://docs.julialang.org/en/latest/packages/packagelist/
using JSON

sample = Dict()
sample["blue"] = [1, 2]
sample["ocean"] = "water"

@show sample jsonstring = json(sample)
@show jsonobj = JSON.parse(jsonstring)

@assert jsonstring == "{\"ocean\":\"water\",\"blue\":[1,2]}"
@assert jsonobj == Dict("ocean" => "water", "blue" => [1, 2])
@assert typeof(jsonobj) == Dict{String, Any}