include "cowgol.coh";

# To change the maximum prime, change the size of this array
# Everything else is automatically filled in at compile time
var sieve: uint8[5000];

# Make sure all elements of the sieve are set to zero
MemZero(&sieve as [uint8], @bytesof sieve);

# Generate the sieve
var prime: @indexof sieve := 2;
while prime < @sizeof sieve loop
    if sieve[prime] == 0 then
        var comp: @indexof sieve := prime * prime;
        while comp < @sizeof sieve loop
            sieve[comp] := 1;
            comp := comp + prime;
        end loop;
    end if;
    prime := prime + 1;
end loop;

# Print all primes
var cand: @indexof sieve := 2;
while cand < @sizeof sieve loop
    if sieve[cand] == 0 then
        print_i16(cand as uint16);
        print_nl();
    end if;
    cand := cand + 1;
end loop;


// version 1.0.6 (search_list.kt)

fun main(args: Array<String>) {
    val haystack = listOf("Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie", "Bush", "Boz", "Zag")
    println(haystack)
    var needle = "Zag"
    var index  = haystack.indexOf(needle)
    val index2 = haystack.lastIndexOf(needle)
    println("\n'$needle' first occurs at index $index of the list")
    println("'$needle' last  occurs at index $index2 of the list\n")
    needle = "Donald"
    index  = haystack.indexOf(needle)
    if (index == -1) throw Exception("$needle does not occur in the list")
}


: haystack(*)  ['rosetta 'code 'search 'a 'list 'lang5 'code] find-index ;
: find-index
    2dup eq length iota swap select swap drop
    length if swap drop
    else drop " is not in haystack" 2 compress "" join
    then ;
: ==>search  apply ;

['hello 'code] 'haystack ==>search .


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

int sedol_weights[] = {1, 3, 1, 7, 3, 9};
const char *reject = "AEIOUaeiou";

int sedol_checksum(const char *sedol6)
{
  int len = strlen(sedol6);
  int sum = 0, i;

  if ( len == 7 ) {
    fprintf(stderr, "SEDOL code already checksummed? (%s)\n", sedol6);
    return sedol6[6] & 0x7f;
  }
  if ( (len > 7) || (len < 6) || ( strcspn(sedol6, reject) != 6 )) {
    fprintf(stderr, "not a SEDOL code? (%s)\n", sedol6);
    return -1;
  }
  for(i=0; i < 6; i++) {
    if ( isdigit(sedol6[i]) ) {
      sum += (sedol6[i]-'0')*sedol_weights[i];
    } else if ( isalpha(sedol6[i]) ) {
      sum += ((toupper(sedol6[i])-'A') + 10)*sedol_weights[i];
    } else {
      fprintf(stderr, "SEDOL with not alphanumeric digit\n");
      return -1;
    }
  }
  return (10 - (sum%10))%10 + '0';
}

#define MAXLINELEN 10
int main()
{
  char line[MAXLINELEN];
  int sr, len;
  while( fgets(line, MAXLINELEN, stdin) != NULL ) {
    len = strlen(line);
    if ( line[len-1] == '\n' ) line[len-1]='\0';
    sr = sedol_checksum(line);
    if ( sr > 0 )
      printf("%s%c\n", line, sr);
  }
  return 0;
}


# compile with `--release --no-debug` for speed...

require "bit_array"

alias Prime = UInt64

class SoE
  include Iterator(Prime)
  @bits : BitArray; @bitndx : Int32 = 2

  def initialize(range : Prime)
    if range < 2
      @bits = BitArray.new 0
    else
      @bits = BitArray.new((range + 1).to_i32)
    end
    ba = @bits; ndx = 2
    while true
      wi = ndx * ndx
      break if wi >= ba.size
      if ba[ndx]
        ndx += 1; next
      end
      while wi < ba.size
        ba[wi] = true; wi += ndx
      end
      ndx += 1
    end
  end

  def next
    while @bitndx < @bits.size
      if @bits[@bitndx]
        @bitndx += 1; next
      end
      rslt = @bitndx.to_u64; @bitndx += 1; return rslt
    end
    stop
  end
end

print "Primes up to a hundred:  "
SoE.new(100).each { |p| print " ", p }; puts
print "Number of primes to a million:  "
puts SoE.new(1_000_000).each.size
print "Number of primes to a billion:  "
start_time = Time.monotonic
print SoE.new(1_000_000_000).each.size
elpsd = (Time.monotonic - start_time).total_milliseconds
puts " in #{elpsd} milliseconds."


local(haystack) = array('Zig', 'Zag', 'Wally', 'Ronald', 'Bush', 'Krusty', 'Charlie', 'Bush', 'Bozo')

#haystack->findindex('Bush')->first // 5
#haystack->findindex('Bush')->last // 8

protect => {^
    handle_error => {^ error_msg ^}
        fail_if(not #haystack->findindex('Washington')->first,'Washington is not in haystack.')
^}


haystack$="apple orange pear cherry melon peach banana needle blueberry mango strawberry needle "
haystack$=haystack$+"pineapple grape kiwi blackberry plum raspberry needle cranberry apricot"

idx=1
do until word$(haystack$,idx)=""
idx=idx+1
loop
total=idx-1

needle$="needle"
'index of first occurrence
for i = 1 to total
    if word$(haystack$,i)=needle$ then exit for
next
print needle$;" first found at index ";i

'index of last occurrence
for j = total to 1
    if word$(haystack$,j)=needle$ then exit for
next
print needle$;" last found at index ";j
if i<>j then
    print "Multiple instances of ";needle$
    else
    print "Only one instance of ";needle$;" in list."
end if

'raise exception
needle$="cauliflower"
for k=1 to total
    if word$(haystack$,k)=needle$ then exit for
next
if k>total then
    print needle$;" not found in list."
else
    print needle$;" found at index ";k
end if


static int[] sedol_weights = { 1, 3, 1, 7, 3, 9 };
static int sedolChecksum(string sedol)
{
    int len = sedol.Length;
    int sum = 0;

    if (len == 7) //SEDOL code already checksummed?
        return (int)sedol[6];

    if ((len > 7) || (len < 6) || System.Text.RegularExpressions.Regex.IsMatch(sedol, "[AEIOUaeiou]+")) //invalid SEDOL
        return -1;

    for (int i = 0; i < 6; i++)
    {
        if (Char.IsDigit(sedol[i]))
            sum += (((int)sedol[i] - 48) * sedol_weights[i]);

        else if (Char.IsLetter(sedol[i]))
            sum += (((int)Char.ToUpper(sedol[i]) - 55) * sedol_weights[i]);

        else
            return -1;

    }

    return (10 - (sum % 10)) % 10;
}


#include <numeric>
#include <cctype>
#include <iostream>
#include <string>

template<typename result_sink_t>
auto sedol_checksum(std::string const& sedol, result_sink_t result_sink)
{
    if(sedol.size() != 6)
        return result_sink(0, "length of sedol string != 6");

    const char * valid_chars = "BCDFGHJKLMNPQRSTVWXYZ0123456789";
    if(sedol.find_first_not_of(valid_chars) != std::string::npos)
        return result_sink(0, "sedol string contains disallowed characters");

    const int weights[] = {1,3,1,7,3,9};
    auto weighted_sum = std::inner_product(sedol.begin(), sedol.end(), weights, 0
                                           , [](int acc, int prod){ return acc + prod; }
                                           , [](char c, int weight){ return (std::isalpha(c) ? c -'A' + 10 : c - '0') * weight; }
                                             );
    return result_sink((10 - (weighted_sum % 10)) % 10, nullptr);
}

int main()
{
    using namespace std;
    string inputs[] = {
       "710889", "B0YBKJ", "406566", "B0YBLH", "228276", "B0YBKL",
       "557910", "B0YBKR", "585284", "B0YBKT", "B00030"
   };
   for(auto const & sedol : inputs)
   {
        sedol_checksum(sedol, [&](auto sum, char const * errorMessage)
        {
            if(errorMessage)
                cout << "error for sedol: " << sedol << " message: " <<  errorMessage << "\n";
            else
                cout << sedol << sum << "\n";
        });
   }
   return 0;
}


import std.stdio, std.algorithm, std.range, std.functional;

uint[] sieve(in uint limit) nothrow @safe {
    if (limit < 2)
        return [];
    auto composite = new bool[limit];

    foreach (immutable uint n; 2 .. cast(uint)(limit ^^ 0.5) + 1)
        if (!composite[n])
            for (uint k = n * n; k < limit; k += n)
                composite[k] = true;

    //return iota(2, limit).filter!(not!composite).array;
    return iota(2, limit).filter!(i => !composite[i]).array;
}

void main() {
    50.sieve.writeln;
}


haystack = ["apples", "oranges", "bananas", "oranges"]
needle = "oranges"

pos = haystack.getPos(needle)
if pos then
  put "needle found at index "&pos
else
  put "needle not found in haystack"
end if

-- "needle found at index 2"


+ haystack : ARRAY[STRING];
haystack := "Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo".split;
"Washington Bush".split.foreach { needle : STRING;
  haystack.has(needle).if {
    haystack.first_index_of(needle).print;
    ' '.print;
    needle.print;
    '\n'.print;
  } else {
    needle.print;
    " is not in haystack\n".print;
  };
};


to indexof :item :list
  if empty? :list [(throw "NOTFOUND 0)]
  if equal? :item first :list [output 1]
  output 1 + indexof :item butfirst :list
end

to showindex :item :list
  make "i catch "NOTFOUND [indexof :item :list]
  ifelse :i = 0 [(print :item [ not found in ] :list)] [(print :item [ found at position ] :i [ in ] :list)]
end

showindex "dog [My dog has fleas]   ; dog found at position 2 in My dog has fleas
showindex "cat [My dog has fleas]   ; cat not found in My dog has fleas


Class Utils.Check [ Abstract ]
{

ClassMethod SEDOL(x As %String) As %Boolean
{
	// https://en.wikipedia.org/wiki/SEDOL
	IF x'?1(7N,1U5UN1N) QUIT 0
	IF x'=$TRANSLATE(x,"AEIOU") QUIT 0
	SET cd=$EXTRACT(x,*), x=$EXTRACT(x,1,*-1)
	SET wgt="1317391", t=0
	FOR i=1:1:$LENGTH(x) {
		SET n=$EXTRACT(x,i)
		IF n'=+n SET n=$ASCII(n)-55
		SET t=t+(n*$EXTRACT(wgt,i))
	}
	QUIT cd=((10-(t#10))#10)
}

}


(defn sedols [xs]
  (letfn [(sedol [ys] (let [weights [1 3 1 7 3 9]
                            convtonum (map #(Character/getNumericValue %) ys)
                            check (-> (reduce + (map * weights convtonum)) (rem 10) (->> (- 10)) (rem 10))]
                        (str ys check)))]
    (map #(sedol %) xs)))


       >>SOURCE FREE
IDENTIFICATION DIVISION.
PROGRAM-ID. sedol.

ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
    SELECT sedol-file ASSIGN "sedol.txt"
        ORGANIZATION LINE SEQUENTIAL
        FILE STATUS sedol-file-status.

DATA DIVISION.
FILE SECTION.
FD  sedol-file.
01  sedol                               PIC X(6).

WORKING-STORAGE SECTION.
01  sedol-file-status                   PIC XX.
    88  sedol-file-ok                   VALUE "00".

01  digit-num                           PIC 9 COMP.

01  digit-weights-area                  VALUE "1317391".
    03  digit-weights                   PIC 9 OCCURS 7 TIMES.

01  weighted-sum-parts-area.
    03  weighted-sum-parts              PIC 9(3) COMP OCCURS 6 TIMES.

01  weighted-sum                        PIC 9(3) COMP.

01  check-digit                         PIC 9.

PROCEDURE DIVISION.
    OPEN INPUT sedol-file
    PERFORM UNTIL NOT sedol-file-ok
        READ sedol-file
            AT END
                EXIT PERFORM
        END-READ

        MOVE FUNCTION UPPER-CASE(sedol) TO sedol

        PERFORM VARYING digit-num FROM 1 BY 1 UNTIL digit-num > 6
            EVALUATE TRUE
                WHEN sedol (digit-num:1) IS ALPHABETIC-UPPER
                    IF sedol (digit-num:1) = "A" OR "E" OR "I" OR "O" OR "U"
                        DISPLAY "Invalid SEDOL: " sedol
                        EXIT PERFORM CYCLE
                    END-IF

                    COMPUTE weighted-sum-parts (digit-num) =
                        (FUNCTION ORD(sedol (digit-num:1)) - FUNCTION ORD("A")
                        + 10) * digit-weights (digit-num)

                WHEN sedol (digit-num:1) IS NUMERIC
                    MULTIPLY FUNCTION NUMVAL(sedol (digit-num:1))
                        BY digit-weights (digit-num)
                        GIVING weighted-sum-parts (digit-num)

                WHEN OTHER
                    DISPLAY "Invalid SEDOL: " sedol
                    EXIT PERFORM CYCLE
            END-EVALUATE
        END-PERFORM

        INITIALIZE weighted-sum
        PERFORM VARYING digit-num FROM 1 BY 1 UNTIL digit-num > 6
            ADD weighted-sum-parts (digit-num) TO weighted-sum
        END-PERFORM

        COMPUTE check-digit =
            FUNCTION MOD(10 - FUNCTION MOD(weighted-sum, 10), 10)

        DISPLAY sedol check-digit
    END-PERFORM

    CLOSE sedol-file
    .
END PROGRAM sedol.


// helper function to pretty print an Iterable
String iterableToString(Iterable seq) {
  String str = "[";
  Iterator i = seq.iterator;
  if (i.moveNext()) str += i.current.toString();
  while(i.moveNext()) {
    str += ", " + i.current.toString();
  }
  return str + "]";
}

main() {
  int limit = 1000;
  int strt = new DateTime.now().millisecondsSinceEpoch;
  Set<int> sieve = new Set<int>();

  for(int i = 2; i <= limit; i++) {
    sieve.add(i);
  }
  for(int i = 2; i * i <= limit; i++) {
   if(sieve.contains(i)) {
     for(int j = i * i; j <= limit; j += i) {
       sieve.remove(j);
     }
   }
  }
  var sortedValues = new List<int>.from(sieve);
  int elpsd = new DateTime.now().millisecondsSinceEpoch - strt;
  print("Found " + sieve.length.toString() + " primes up to " + limit.toString() +
      " in " + elpsd.toString() + " milliseconds.");
  print(iterableToString(sortedValues)); // expect sieve.length to be 168 up to 1000...
//  Expect.equals(168, sieve.length);
}


list = {"mouse", "hat", "cup", "deodorant", "television", "soap", "methamphetamine", "severed cat heads"} --contents of my desk

item = io.read()

for i,v in ipairs(list)
  if v == item then print(i) end
end


Module Checkit {
      Flush ' empty stack
      Inventory Queue Haystack=  "foo", "bar", "baz", "quux", "quuux", "quuuux", "bazola", "ztesch", "foo", "bar", "thud", "grunt"
      Append  Haystack, "foo", "bar", "bletch", "foo", "bar", "fum", "fred", "jim", "sheila", "barney", "flarp", "zxc"
      Append  Haystack,  "spqr", "wombat", "shme", "foo", "bar", "baz", "bongo", "spam", "eggs", "snork", "foo", "bar"
      Append  Haystack,  "zot", "blarg", "wibble", "toto", "titi", "tata", "tutu", "pippo", "pluto", "paperino", "aap"
      Append  Haystack,  "noot", "mies", "oogle", "foogle", "boogle", "zork", "gork", "bork"
      \\ Inventories are objects and we have access to properties using COM model
      With HayStack, "index" as index
      Inventory Queue HayStackRev
      N=Each(HayStack, -1, 1)
      While N {
            Append HayStackRev, Eval$(N, N^)
      }
      With HayStackRev, "index" as indexRev
      Print Len(HayStack)
      Print Len(HayStackRev)
      local needle$
      \\ Print all elements using columns
      Print haystack
      Repeat {
                Input "Word to search for? (Leave blank to exit) ", needle$
                If needle$ <> "" Then {
                          If Exist(haystackrev,lcase$(needle$) ) Then {
                              Print "Found "; CHR$(34); needle$; CHR$(34); " at index "; STR$(len(haystackrev)-indexrev,"")

                              If Exist(haystack,lcase$(needle$) ) Then  {
                                    if len(haystackrev)-1<>indexrev+index then {
                                                Print "Found "; CHR$(34); needle$; CHR$(34); " at index "; STR$(Len(haystack)-index,"")
                                    }
                              }
                        } Else  Print CHR$(34); needle$; CHR$(34); " not found"
            } Else Exit
      } Always
}
CheckIt


haystack := ["Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo"]:
occurences := ListTools:-SearchAll(needle,haystack):
try
	#first occurence
	printf("The first occurence is at index %d\n", occurences[1]);
	#last occurence, note that StringTools:-SearchAll()retuns a list of all occurences positions
	printf("The last occurence is at index %d\n", occurences[-1]);
catch :
	print("Erros: Needle not found in the haystack"):
end try:


(defun append-sedol-check-digit (sedol &key (start 0) (end (+ start 6)))
  (assert (<= 0 start end (length sedol)))
  (assert (= (- end start) 6))
  (loop
       :with checksum = 0
       :for weight :in '(1 3 1 7 3 9)
       :for index :upfrom start
       :do (incf checksum (* weight (digit-char-p (char sedol index) 36)))
       :finally (let* ((posn (- 10 (mod checksum 10)))
		       (head (subseq sedol start end))
		       (tail (digit-char posn)))
		  (return (concatenate 'string head (list tail))))))


import std.stdio, std.algorithm, std.string, std.numeric, std.ascii;

char checksum(in char[] sedol) pure @safe /*@nogc*/
in {
    assert(sedol.length == 6);
    foreach (immutable c; sedol)
        assert(c.isDigit || (c.isUpper && !"AEIOU".canFind(c)));
} out (result) {
    assert(result.isDigit);
} body {
    static immutable c2v = (in dchar c) => c.isDigit ? c - '0' : (c - 'A' + 10);
    immutable int d = sedol.map!c2v.dotProduct([1, 3, 1, 7, 3, 9]);
    return digits[10 - (d % 10)];
}

void main() {
    foreach (const sedol; "710889 B0YBKJ 406566 B0YBLH 228276
                          B0YBKL 557910 B0YBKR 585284 B0YBKT".split)
        writeln(sedol, sedol.checksum);
}


program erathostenes;

{$APPTYPE CONSOLE}

type
  TSieve = class
  private
    fPrimes: TArray<boolean>;
    procedure InitArray;
    procedure Sieve;
    function getNextPrime(aStart: integer): integer;
    function getPrimeArray: TArray<integer>;
  public
    function getPrimes(aMax: integer): TArray<integer>;
  end;

  { TSieve }

function TSieve.getNextPrime(aStart: integer): integer;
begin
  result := aStart;
  while not fPrimes[result] do
    inc(result);
end;

function TSieve.getPrimeArray: TArray<integer>;
var
  i, n: integer;
begin
  n := 0;
  setlength(result, length(fPrimes)); // init array with maximum elements
  for i := 2 to high(fPrimes) do
  begin
    if fPrimes[i] then
    begin
      result[n] := i;
      inc(n);
    end;
  end;
  setlength(result, n); // reduce array to actual elements
end;

function TSieve.getPrimes(aMax: integer): TArray<integer>;
begin
  setlength(fPrimes, aMax);
  InitArray;
  Sieve;
  result := getPrimeArray;
end;

procedure TSieve.InitArray;
begin
  for i := 2 to high(fPrimes) do
    fPrimes[i] := true;
end;

procedure TSieve.Sieve;
var
  i, n, max: integer;
begin
  max := length(fPrimes);
  i := 2;
  while i < sqrt(max) do
  begin
    n := sqr(i);
    while n < max do
    begin
      fPrimes[n] := false;
      inc(n, i);
    end;
    i := getNextPrime(i + 1);
  end;
end;

var
  i: integer;
  Sieve: TSieve;

begin
  Sieve := TSieve.Create;
  for i in Sieve.getPrimes(100) do
    write(i, ' ');
  Sieve.Free;
  readln;
end.


haystack = {"Zig","Zag","Wally","Ronald","Bush","Zig","Zag","Krusty","Charlie","Bush","Bozo"};
needle = "Zag";
first = Position[haystack,needle,1][[1,1]]
last = Position[haystack,needle,1][[-1,1]]
all = Position[haystack,needle,1][[All,1]]


haystack: ["Zig","Zag","Wally","Ronald","Bush","Zig","Zag","Krusty","Charlie","Bush","Bozo"];
needle:  "Zag";

findneedle(needle, haystack, [opt]):=block([idx],
  idx: sublist_indices(haystack, lambda([w], w=needle)),
  if emptyp(idx) then throw('notfound),
  if emptyp(opt) then return(idx),
  opt: first(opt),
  if opt='f then first(idx) else if opt='l then last(idx) else throw('unknownmode));


program Sedol;

{$APPTYPE CONSOLE}

uses
  SysUtils;

const
  SEDOL_CHR_COUNT = 6;
  DIGITS = ['0'..'9'];
  LETTERS = ['A'..'Z'];
  VOWELS = ['A', 'E', 'I', 'O', 'U'];
  ACCEPTABLE_CHRS = DIGITS + LETTERS - VOWELS;
  WEIGHTS : ARRAY [1..SEDOL_CHR_COUNT] of integer = (1, 3, 1, 7, 3, 9);
  LETTER_OFFSET = 9;

function AddSedolCheckDigit(Sedol : string) : string;
var
  iChr : integer;
  Checksum : integer;
  CheckDigit : char;
begin
  if Sedol <> uppercase(Sedol) then
    raise ERangeError.CreateFmt('%s contains lower case characters',[Sedol]);
  if length(Sedol) <> SEDOL_CHR_COUNT then
    raise ERangeError.CreateFmt('"%s" length is invalid. Should be 6 characters',[Sedol]);

  Checksum := 0;
  for iChr := 1 to SEDOL_CHR_COUNT do
  begin

    if Sedol[iChr] in Vowels then
      raise ERangeError.CreateFmt('%s contains a vowel (%s) at chr %d',[Sedol, Sedol[iChr], iChr]);
    if not (Sedol[iChr] in ACCEPTABLE_CHRS) then
      raise ERangeError.CreateFmt('%s contains an invalid chr (%s) at position %d',[Sedol, Sedol[iChr], iChr]);

    if Sedol[iChr] in DIGITS then
      Checksum := Checksum + (ord(Sedol[iChr]) - ord('0')) * WEIGHTS[iChr]
    else
      Checksum := Checksum + (ord(Sedol[iChr]) - ord('A') + 1 + LETTER_OFFSET) * WEIGHTS[iChr];

  end;

  Checksum := (Checksum mod 10);
  if Checksum <> 0 then
    Checksum := 10 - Checksum;
  CheckDigit := chr(CheckSum + ord('0'));

  Result := Sedol + CheckDigit;
end;

procedure Test(First6 : string);
begin
  writeln(First6, ' becomes ', AddSedolCheckDigit(First6));
end;

begin
  try
    Test('710889');
    Test('B0YBKJ');
    Test('406566');
    Test('B0YBLH');
    Test('228276');
    Test('B0YBKL');
    Test('557910');
    Test('B0YBKR');
    Test('585284');
    Test('B0YBKT');
    Test('B00030');
  except
    on E : Exception do
      writeln(E.Message);
  end;
  readln;
end.


/* Sieve of Eratosthenes - fill a given boolean array */
proc nonrec sieve([*] bool prime) void:
    word p, c, max;
    max := dim(prime,1)-1;
    prime[0] := false;
    prime[1] := false;
    for p from 2 upto max do prime[p] := true od;
    for p from 2 upto max>>1 do
        if prime[p] then
            for c from p*2 by p upto max do
                prime[c] := false
            od
        fi
    od
corp

/* Print primes up to 1000 using the sieve */
proc nonrec main() void:
    word MAX = 1000;
    unsigned MAX i;
    byte c;
    [MAX+1] bool prime;
    sieve(prime);

    c := 0;
    for i from 0 upto MAX do
        if prime[i] then
            write(i:4);
            c := c + 1;
            if c=10 then c:=0; writeln() fi
        fi
    od
corp


haystack=#("Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo")

for needle in #("Washington","Bush") do
(
    index = findItem haystack needle

    if index == 0 then
    (
        format "% is not in haystack\n" needle
    )
    else
    (
        format "% %\n" index needle
    )
)


$haystack = list()
append $haystack "Zig" "Zag" "Wally" "Ronald" "Bush" "Krusty" "Charlie"
append $haystack "Bush" "Bozo"

$needles = list()
append $needles "Washington"
append $needles "Bush"

for ($i = 0) ($i < len($needles)) ($i = $i + 1)
	$needle = $needles[$i]
	try
		// use array lookup syntax to get the index of the needle
		println $haystack[$needle] + " " + $needle
	catch
		println $needle + " is not in haystack"
	end
end for


/* NetRexx */
options replace format comments java crossref symbols nobinary

driver(arg) -- call the test wrapper
return

-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method searchListOfWords(haystack, needle, forwards = (1 == 1), respectCase = (1 == 1)) public static signals Exception

  if \respectCase then do
    needle   = needle.upper()
    haystack = haystack.upper()
    end
  if forwards then wp = haystack.wordpos(needle)
  else             wp = haystack.words() - haystack.reverse().wordpos(needle.reverse()) + 1
  if wp = 0 then signal Exception('*** Error! "'needle'" not found in list ***')

  return wp

-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method searchIndexedList(haystack, needle, forwards = (1 == 1), respectCase = (1 == 1)) public static signals Exception
  if forwards then do
    strtIx = 1
    endIx  = haystack[0]
    incrIx = 1
    end
  else do
    strtIx = haystack[0]
    endIx  = 1
    incrIx = -1
    end

    wp = 0
    loop ix = strtIx to endIx by incrIx
      if respectCase then
        if needle == haystack[ix] then wp = ix
        else nop
      else
        if needle.upper() == haystack[ix].upper() then wp = ix
        else nop
      if wp > 0 then leave ix
      end ix
    if wp = 0 then signal Exception('*** Error! "'needle'" not found in indexed list ***')

  return wp

-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- Test wrapper
method driver(arg) public static
  -- some manifests
  TRUE_        = (1 == 1); FALSE_      = \TRUE_
  FORWARDS_    = TRUE_;    BACKWARDS_  = FALSE_
  CASERESPECT_ = TRUE_;    CASEIGNORE_ = \CASERESPECT_

  -- test data
  needles = ['barley', 'quinoa']

  -- a simple list of words.  Lists of words are indexable in NetRexx via the word(N) function
  hayrick = 'Barley maize barley sorghum millet wheat rice rye barley Barley oats flax'

  -- a Rexx indexed string made up from the words in hayrick
  cornstook = ''
  loop w_ = 1 to hayrick.words() -- populate the indexed string
    cornstook[0]  = w_
    cornstook[w_] = hayrick.word(w_)
    end w_

  loop needle over needles
    do -- process the list of words
      say 'Searching for "'needle'" in the list "'hayrick'"'
      idxF = searchListOfWords(hayrick, needle)
      idxL = searchListOfWords(hayrick, needle, BACKWARDS_)
      say '  The first occurence of "'needle'" is at index' idxF 'in the list'
      say '  The last occurence of "'needle'" is at index' idxL 'in the list'
      idxF = searchListOfWords(hayrick, needle, FORWARDS_, CASEIGNORE_)
      idxL = searchListOfWords(hayrick, needle, BACKWARDS_, CASEIGNORE_)
      say '  The first caseless occurence of "'needle'" is at index' idxF 'in the list'
      say '  The last caseless occurence of "'needle'" is at index' idxL 'in the list'
      say
    catch ex = Exception
      say '  'ex.getMessage()
      say
    end

    do -- process the indexed list
      corn = ''
      loop ci = 1 to cornstook[0]
        corn = corn cornstook[ci]
        end ci
      say 'Searching for "'needle'" in the indexed list "'corn.space()'"'
      idxF = searchIndexedList(cornstook, needle)
      idxL = searchIndexedList(cornstook, needle, BACKWARDS_)
      say '  The first occurence of "'needle'" is at index' idxF 'in the indexed list'
      say '  The last occurence of "'needle'" is at index' idxL 'in the indexed list'
      idxF = searchIndexedList(cornstook, needle, FORWARDS_, CASEIGNORE_)
      idxL = searchIndexedList(cornstook, needle, BACKWARDS_, CASEIGNORE_)
      say '  The first caseless occurence of "'needle'" is at index' idxF 'in the indexed list'
      say '  The last caseless occurence of "'needle'" is at index' idxL 'in the indexed list'
      say
    catch ex = Exception
      say '  'ex.getMessage()
      say
    end
    end needle

  return


def weights := [1,3,1,7,3,9]
def Digit := ('0'..'9')
def Letter := ('B'..'D'|'F'..'H'|'J'..'N'|'P'..'T'|'V'..'Z')
def sedolCharValue(c) {
  switch (c) {
    match digit :Digit { return digit - '0' }
    match letter :Letter {
      return letter - 'A'
    }
  }
}

def checksum(sedol :String) {
  require(sedol.size() == 6)
  var sum := 0
  for i => c in sedol {
    sum += weights[i] * sedolCharValue(c)
  }
  return E.toString((10 - sum %% 10) %% 10)
}

def addChecksum(sedol :String) {
  return sedol + checksum(sedol)
}

for sedol in "710889
              B0YBKJ
              406566
              B0YBLH
              228276
              B0YBKL
              557910
              B0YBKR
              585284
              B0YBKT".trim().split("\n") {
  println(addChecksum(sedol.trim()))
}


defmodule SEDOL do
  @sedol_char  "0123456789BCDFGHJKLMNPQRSTVWXYZ" |> String.codepoints
  @sedolweight  [1,3,1,7,3,9]

  defp char2value(c) do
    unless c in @sedol_char, do: raise ArgumentError, "No vowels"
    String.to_integer(c,36)
  end

  def checksum(sedol) do
    if String.length(sedol) != length(@sedolweight), do: raise ArgumentError, "Invalid length"
    sum = Enum.zip(String.codepoints(sedol), @sedolweight)
          |> Enum.map(fn {ch, weight} -> char2value(ch) * weight end)
          |> Enum.sum
    to_string(rem(10 - rem(sum, 10), 10))
  end
end

data = ~w{
          710889
          B0YBKJ
          406566
          B0YBLH
          228276
          B0YBKL
          557910
          B0YBKR
          585284
          B0YBKT
          B00030
          C0000
          1234567
          00000A
         }

Enum.each(data, fn sedol ->
  :io.fwrite "~-8s ", [sedol]
  try do
    IO.puts sedol <> SEDOL.checksum(sedol)
  rescue
    e in ArgumentError -> IO.inspect e
  end
end)


function Primes(limit : Integer) : array of Integer;
var
   n, k : Integer;
   sieve := new Boolean[limit+1];
begin
   for n := 2 to Round(Sqrt(limit)) do begin
      if not sieve[n] then begin
         for k := n*n to limit step n do
            sieve[k] := True;
      end;
   end;

   for k:=2 to limit do
      if not sieve[k] then
         Result.Add(k);
end;

var r := Primes(50);
var i : Integer;
for i:=0 to r.High do
   PrintLn(r[i]);


let haystack = ["Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo"]

for needle in ["Bush", "Washington"]:
  let f = haystack.find(needle)
  if f >= 0:
    echo f, " ", needle
  else:
    raise newException(ValueError, needle & " not in haystack")


use Collection;

class Test {
  function : Main(args : String[]) ~ Nil {
    haystack := ["Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo"];
    values := CompareVector->New();
    each(i : haystack) {
      values->AddBack(haystack[i]->As(Compare));
    };

    needles := ["Washington", "Bush"];
    each(i : needles) {
      values->Has(needles[i]->As(Compare))->PrintLine();
    };
  }
}


SEDOLCHECKSUM
=LAMBDA(s,
    IF(6 = LEN(s),
        LET(
            cs, MID(s, SEQUENCE(1, 6, 1, 1), 1),
            isVowel, LAMBDA(c,
                ELEM(c)({"A","E","I","O","U"})
            ),
            sedolValue, LAMBDA(c,
                LET(
                    ic, CODE(c),
                    IF(65 > ic,
                        ic - 48,
                        (ic + 10) - 65
                    )
                )
            ),
            IF(OR(isVowel(cs)),
                " -> Invalid vowel in SEDOL string",
                MOD(
                    10 - MOD(
                        SUM(
                            MUL({1,3,1,7,3,9})(
                                sedolValue(cs)
                            )
                        ), 10
                    ), 10
                )
            )
        ),
        "Expected a 6-character SEDOL"
    )
)


open System
let Inputs = ["710889"; "B0YBKJ"; "406566"; "B0YBLH"; "228276"; "B0YBKL"
              "557910"; "B0YBKR"; "585284"; "B0YBKT"; "B00030"]

let Vowels = set ['A'; 'E'; 'I'; 'O'; 'U']
let Weights = [1; 3; 1; 7; 3; 9; 1]

let inline isVowel c = Vowels.Contains (Char.ToUpper c)

let char2value c =
    if Char.IsDigit c then int c - 0x30
    else (['A'..'Z'] |> List.findIndex ((=) (Char.ToUpper c))) + 10

let sedolCheckDigit (input: string) =
    if input.Length <> 6 || input |> Seq.exists isVowel then
        failwithf "Input must be six characters long and not contain vowels: %s" input

    let sum = Seq.map2 (fun ch weight -> (char2value ch) * weight) input Weights |> Seq.sum
    (10 - sum%10)%10

let addCheckDigit inputs =
    inputs |> List.map (fun s -> s + (sedolCheckDigit s).ToString())

let processDigits() =
    try
        addCheckDigit Inputs |> List.iter (printfn "%s")
    with
        ex -> printfn "ERROR: %s" ex.Message


define method primes(n)
  let limit = floor(n ^ 0.5) + 1;
  let sieve = make(limited(<simple-vector>, of: <boolean>), size: n + 1, fill: #t);
  let last-prime = 2;

  while (last-prime < limit)
    for (x from last-prime ^ 2 to n by last-prime)
      sieve[x] := #f;
    end for;
    block (found-prime)
      for (n from last-prime + 1 below limit)
        if (sieve[n] = #f)
          last-prime := n;
          found-prime()
        end;
      end;
      last-prime := limit;
    end block;
  end while;

  for (x from 2 to n)
    if (sieve[x]) format-out("Prime: %d\n", x); end;
  end;
end;


NSArray *haystack = @[@"Zig",@"Zag",@"Wally",@"Ronald",@"Bush",@"Krusty",@"Charlie",@"Bush",@"Bozo"];
for (id needle in @[@"Washington",@"Bush"]) {
    int index = [haystack indexOfObject:needle];
    if (index == NSNotFound)
        NSLog(@"%@ is not in haystack", needle);
    else
        NSLog(@"%i %@", index, needle);
}


# let find_index pred lst =
    let rec loop n = function
       []    -> raise Not_found
     | x::xs -> if pred x then n
                          else loop (n+1) xs
    in
    loop 0 lst;;
val find_index : ('a -> bool) -> 'a list -> int = <fun>

# let haystack =
    ["Zig";"Zag";"Wally";"Ronald";"Bush";"Krusty";"Charlie";"Bush";"Bozo"];;
val haystack : string list =
  ["Zig"; "Zag"; "Wally"; "Ronald"; "Bush"; "Krusty"; "Charlie"; "Bush";
   "Bozo"]
# List.iter (fun needle ->
               try
                 Printf.printf "%i %s\n" (find_index ((=) needle) haystack) needle
               with Not_found ->
                 Printf.printf "%s is not in haystack\n" needle)
            ["Washington"; "Bush"];;
Washington is not in haystack
4 Bush
- : unit = ()


USING: combinators combinators.short-circuit formatting io kernel
math math.parser regexp sequences unicode ;
IN: rosetta-code.sedols

<PRIVATE

CONSTANT: input {
    "710889" "B0YBKJ" "406566" "B0YBLH" "228276" "B0YBKL"
    "557910" "B0YBKR" "585284" "B0YBKT" "B00030" "AEIOUA"
    "123"    ""       "B_7K90"
}

CONSTANT: weights B{ 1 3 1 7 3 9 1 }

: sedol-error ( seq -- err-str )
    {
        { [ dup empty? ] [ drop "no data" ] }
        { [ dup length 6 = not ] [ drop "invalid length" ] }
        [ drop "invalid char(s)" ]
    } cond "*error* " prepend ;

: sedol-valid? ( seq -- ? )
    { [ length 6 = ] [ R/ [0-9BCDFGHJ-NP-TV-Z]+/ matches? ] } 1&& ;

: sedol-value ( m -- n ) dup digit? [ digit> ] [ 55 - ] if ;

: sedol-checksum ( seq -- n )
    [ sedol-value ] { } map-as weights [ * ] 2map sum ;

: (sedol-check-digit) ( seq -- str )
    sedol-checksum 10 mod 10 swap - 10 mod number>string ;

PRIVATE>

: sedol-check-digit ( seq -- str )
    dup sedol-valid? [ (sedol-check-digit) ] [ sedol-error ] if ;

: sedol-demo ( -- )
    "SEDOL   Check digit\n======  ===========" print
    input [ dup sedol-check-digit "%-6s  %s\n" printf ] each ;

MAIN: sedol-demo


create weight 1 , 3 , 1 , 7 , 3 , 9 ,

: char>num ( '0-9A-Z' -- 0..35 )
  dup [char] 9 > 7 and - [char] 0 - ;

: check+ ( sedol -- sedol' )
  6 <> abort" wrong SEDOL length"
  0 ( sum )
  6 0 do
    over I + [email protected] char>num
    weight I cells + @ *
    +
  loop
  10 mod   10 swap -  10 mod  [char] 0 +
  over 6 + c! 7 ;

: sedol"   [char] " parse check+ type ;

sedol" 710889" 7108899 ok
sedol" B0YBKJ" B0YBKJ7 ok
sedol" 406566" 4065663 ok
sedol" B0YBLH" B0YBLH2 ok
sedol" 228276" 2282765 ok
sedol" B0YBKL" B0YBKL9 ok
sedol" 557910" 5579107 ok
sedol" B0YBKR" B0YBKR5 ok
sedol" 585284" 5852842 ok
sedol" B0YBKT" B0YBKT7 ok


MODULE SEDOL_CHECK
  IMPLICIT NONE
  CONTAINS

  FUNCTION Checkdigit(c)
    CHARACTER :: Checkdigit
    CHARACTER(6), INTENT(IN) :: c
    CHARACTER(36) :: alpha = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    INTEGER, DIMENSION(6) :: weights = (/ 1, 3, 1, 7, 3, 9 /), temp
    INTEGER :: i, n

    DO i = 1, 6
      temp(i) = INDEX(alpha, c(i:i)) - 1
    END DO
    temp = temp * weights
    n = MOD(10 - (MOD(SUM(temp), 10)), 10)
    Checkdigit = ACHAR(n + 48)
  END FUNCTION Checkdigit

END MODULE SEDOL_CHECK

PROGRAM SEDOLTEST
  USE SEDOL_CHECK
  IMPLICIT NONE

  CHARACTER(31) :: valid = "0123456789BCDFGHJKLMNPQRSTVWXYZ"
  CHARACTER(6) :: codes(10) = (/ "710889", "B0YBKJ", "406566", "B0YBLH", "228276" ,  &
                                 "B0YBKL", "557910", "B0YBKR", "585284", "B0YBKT" /)
  CHARACTER(7) :: sedol
  INTEGER :: i, invalid

  DO i = 1, 10
    invalid = VERIFY(codes(i), valid)
    IF (invalid == 0) THEN
      sedol = codes(i)
      sedol(7:7) = Checkdigit(codes(i))
    ELSE
      sedol = "INVALID"
    END IF
    WRITE(*, "(2A9)") codes(i), sedol
  END DO

END PROGRAM SEDOLTEST


def rangeFromBelowBy(start, limit, step) {
  return def stepper {
    to iterate(f) {
      var i := start
      while (i < limit) {
        f(null, i)
        i += step
      }
    }
  }
}


: needleIndex(needle, haystack)
   haystack indexOf(needle) dup ifNull: [ drop ExRuntime throw("Not found", needle) ] ;

[ "Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie", "Bush", "Boz" ] const: Haystack

needleIndex("Bush", Haystack) println
Haystack lastIndexOf("Bush") println
needleIndex("Washington", Haystack) println


-- ordered collections always return the first hit
a = .array~of(1,2,3,4,4,5)
say a~index(4)
a2 = .array~new(5,5)  -- multidimensional
a2[3,3] = 4
-- the returned index is an array of values
say a2~index(4)~makestring('line', ',')
-- Note, list indexes are assigned when an item is added and
-- are not tied to relative position
l = .list~of(1,2,3,4,4,5)
say l~index(4)
q = .queue~of(1,2,3,4,4,5)
say q~index(4)
-- directories are unordered, so it is
-- undertermined which one is returned
d = .directory~new
d["foo"] = 4
d["bar"] = 4
say d~index(4)


' version 05-07-2015
' compile with: fbc -s console

Function check_sedol(input_nr As String) As Integer
    input_nr = Trim(input_nr)
    Dim As Integer i, j, x, nr_begin, sum
    Dim As String ch, legal = "AEIOU0123456789BCDFGHJKLMNPQRSTVWXYZ"
    Dim As Integer weight(0 To ...) = { 1, 3, 1, 7, 3, 9, 1}

    x = Len(input_nr)
    If x < 6 Or x > 7 Then
        Return -99 ' to long or to short
    End If

    For i = 0 To 5
        ch = Chr(input_nr[i])
        j = InStr(legal,ch)
        If j < 6 Then
            Return -90+j ' not a legal char. or a vowel
        End If
        j = ch[0] - Asc("0")
        If j > 9 Then j = j + (Asc("0") + 10- Asc("A"))
        If i = 0 AndAlso j < 10 Then nr_begin = 1
        If nr_begin = 1 AndAlso i > 0 Then
            If j > 9 Then Return -97 ' first is number then all be numbers
        End If
        sum = sum + j * weight(i)
    Next
    sum= ((10 - (sum Mod 10)) Mod 10)
    If x = 7 Then
        j=input_nr[6] - Asc("0") ' checksum digit is only number
        If j = sum Then
            Return 100+sum ' correct
        Else
            Return -98   ' wrong
        End If
    End If

    Return sum ' checksum digit

End Function

Sub sedol(in As String)

    Dim As Integer checksum = check_sedol(in)
    Print(in);

    Select Case checksum
        Case -99
            Print " Illegal SEDOL: wrong length"
        Case -98
            Print " Illegal SEDOL: checksum digits do not match"
        Case -97
            Print " Illegal SEDOL: starts with number, may only contain numbers"
        Case -90
            Print " Illegal SEDOL: illegal character"
        Case -89 To -85
            Print " Illegal SEDOL: No vowels allowed"
        Case Is > 99
            Print " Valid SEDOL: checksums match"
        Case Else
            Print " checksum calculated : ";in;Str(checksum)
    End Select

End Sub
' ------=< MAIN >=------

Dim As Integer k,checksum
Dim As String in(1 To ...) = {"710889", "B0YBKJ", "406566", "B0YBLH",_
                              "228276", "B0YBKL", "557910", "B0YBKR",_
                                        "585284", "B0YBKT", "B00030"}

Print "Calculated checksum"
For k = 1 To UBound(in) : sedol(in(k)) : Next

Print : Print "Check checksum"
Dim As String in1(1 To ...) = {"7108899", "B0YBKJ7", "4065663", "B0YBLH2",_
                                "2282765", "B0YBKL9","5579107", "B0YBKR5",_
                                          "5852842", "B0YBKT7", "B000300"}

For k = 1 To UBound(in1) : sedol(in1(k)) : Next

Print : Print "Error test"
Dim As String errors(1 To ...) = {"12", "1234567890", "1B0000", "123 45",_
                                                     "A00000", "B000301"}

For k = 1 To UBound(errors) : sedol(errors(k)) : Next

' empty keyboard buffer
While Inkey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End


len prims[] 100
max = sqrt len prims[]
tst = 2
while tst <= max
  if prims[tst] = 0
    i = tst * tst
    while i < len prims[]
      prims[i] = 1
      i += tst
    .
  .
  tst += 1
.
i = 2
while i < len prims[]
  if prims[i] = 0
    print i
  .
  i += 1
.


declare
  %% Lazy list of indices of Y in Xs.
  fun {Indices Y Xs}
     for
        X in Xs
        I in 1;I+1
        yield:Yield
     do
        if Y == X then {Yield I} end
     end
  end

  fun {Index Y Xs}
     case {Indices Y Xs} of X|_ then X
     else raise index(elementNotFound Y) end
     end
  end

  Haystack = ["Zig" "Zag" "Wally" "Ronald" "Bush" "Krusty" "Charlie" "Bush" "Bozo"]
in
  {Show {Index "Bush" Haystack}}
  {Show {List.last {Indices "Bush" Haystack}}}

  {Show {Index "Washington" Haystack}} %% throws


find(v,n)={
  my(i=setsearch(v,n));
  if(i,
    while(i>1, if(v[i-1]==n,i--))
  ,
    error("Could not find")
  );
  i
};


Public Sub Main()
Dim byWeight As Byte[] = [1, 3, 1, 7, 3, 9, 1]
Dim byCount, byCompute As Byte
Dim siTotal As Short
Dim sWork As New String[]
Dim sToProcess As String[] = ["710889", "B0YBKJ", "406566", "B0YBLH", "228276", "B0YBKL",
                              "557910", "B0YBKR", "585284", "B0YBKT", "B00030"]

For byCompute = 0 To sToProcess.Max
  For byCount = 1 To 6
    If IsLetter(Mid(sToProcess[byCompute], byCount, 1)) Then
      sWork.Add(Str(Asc(Mid(sToProcess[byCompute], byCount, 1)) - 55) * byWeight[byCount - 1])
    Else
      sWork.Add(Val(Mid(sToProcess[byCompute], byCount, 1)) * byWeight[byCount - 1])
    End If
  Next

  For byCount = 0 To 5
    siTotal += Val(sWork[byCount])
  Next

  siTotal = (10 - (siTotal Mod 10)) Mod 10

  Print sToProcess[byCompute] & " = " & sToProcess[byCompute] & siTotal
  sWork.Clear()
  siTotal = 0
Next

End


package main

import (
    "fmt"
    "strings"
    "strconv"
)

const input = `710889
B0YBKJ
406566
B0YBLH
228276
B0YBKL
557910
B0YBKR
585284
B0YBKT
B00030

B
B0003
B000300
A00030
E00030
I00030
O00030
U00030
β00030
β0003`

var weight = [...]int{1,3,1,7,3,9}

func csd(code string) string {
    switch len(code) {
    case 6:
    case 0:
        return "No data"
    default:
        return "Invalid length"
    }
    sum := 0
    for i, c := range code {
        n, err := strconv.ParseInt(string(c), 36, 0)
        if err != nil || c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U' {
            return "Invalid character"
        }
        sum += int(n)*weight[i]
    }
    return strconv.Itoa(9-(sum-1)%10)
}

func main() {
    for _, s := range strings.Split(input, "\n") {
        d := csd(s)
        if len(d) > 1 {
            fmt.Printf(":%s: %s\n", s, d)
        } else {
            fmt.Println(s + d)
        }
    }
}


public class FindPrime
{
   Array<int> primeList { [ 2 ], minAllocSize = 64 };
   int index;

   index = 3;

   bool HasPrimeFactor(int x)
   {
      int max = (int)floor(sqrt((double)x));

      for(i : primeList)
      {
         if(i > max) break;
         if(x % i == 0) return true;
      }
      return false;
   }

   public int GetPrime(int x)
   {
      if(x > primeList.count - 1)
      {
         for (; primeList.count != x; index += 2)
            if(!HasPrimeFactor(index))
            {
               if(primeList.count >= primeList.minAllocSize) primeList.minAllocSize *= 2;
               primeList.Add(index);
            }
      }
      return primeList[x-1];
   }
}

class PrimeApp : Application
{
   FindPrime fp { };
   void Main()
   {
      int num = argc > 1 ? atoi(argv[1]) : 1;
      PrintLn(fp.GetPrime(num));
   }
}


use List::Util qw(first);

my @haystack = qw(Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo);

foreach my $needle (qw(Washington Bush)) {
  my $index = first { $haystack[$_] eq $needle } (0 .. $#haystack); # note that "eq" was used because we are comparing strings
                                                                    # you would use "==" for numbers
  if (defined $index) {
    print "$index $needle\n";
  } else {
    print "$needle is not in haystack\n";
  }
}


def checksum(text) {
    assert text.size() == 6 && !text.toUpperCase().find(/[AEIOU]+/) : "Invalid SEDOL text: $text"

    def sum = 0
    (0..5).each { index ->
        sum +=  Character.digit(text.charAt(index), 36) * [1, 3, 1, 7, 3, 9][index]
    }
    text + (10 - (sum % 10)) % 10
}
String.metaClass.sedol = { this.&checksum(delegate) }


import Data.Char (isAsciiUpper, isDigit, ord)

-------------------------- SEDOLS ------------------------

checkSum :: String -> String
checkSum x =
  case traverse sedolValue x of
    Right xs -> (show . checkSumFromSedolValues) xs
    Left annotated -> annotated

checkSumFromSedolValues :: [Int] -> Int
checkSumFromSedolValues xs =
  rem
    ( 10
        - rem
          ( sum $
              zipWith
                (*)
                [1, 3, 1, 7, 3, 9]
                xs
          )
          10
    )
    10

sedolValue :: Char -> Either String Int
sedolValue c
  | c `elem` "AEIOU" = Left " ← Unexpected vowel."
  | isDigit c = Right (ord c - ord '0')
  | isAsciiUpper c = Right (ord c - ord 'A' + 10)

--------------------------- TEST -------------------------
main :: IO ()
main =
  mapM_
    (putStrLn . ((<>) <*> checkSum))
    [ "710889",
      "B0YBKJ",
      "406566",
      "B0YBLH",
      "228276",
      "B0YBKL",
      "557910",
      "B0YBKR",
      "585284",
      "B0YBKT",
      "BOYBKT", -- Ill formed test case - illegal vowel.
      "B00030"
    ]


(require 'types) ;; bit-vector

;; converts sieve->list for integers in [nmin .. nmax[
(define (s-range sieve nmin nmax (base 0))
	(for/list ([ i (in-range nmin nmax)]) #:when (bit-vector-ref sieve i) (+ i base)))

;; next prime in sieve > p, or #f
(define (s-next-prime sieve p ) ;;
		(bit-vector-scan-1 sieve (1+ p)))

;; returns a bit-vector - sieve- all numbers in [0..n[
(define (eratosthenes n)
  (define primes (make-bit-vector-1 n ))
  (bit-vector-set! primes 0 #f)
  (bit-vector-set! primes 1 #f)
  (for ([p (1+ (sqrt n))])
  		 #:when (bit-vector-ref primes  p)
         (for ([j (in-range (* p p) n p)])
    (bit-vector-set! primes j #f)))
   primes)

(define s-primes (eratosthenes 10_000_000))

(s-range s-primes 0 100)
   → (2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97)
(s-range s-primes 1_000_000 1_000_100)
   → (1000003 1000033 1000037 1000039 1000081 1000099)
(s-next-prime s-primes 9_000_000)
   → 9000011


constant s = {"Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie", "Bush", "Boz", "Zag"}

integer r = find("Zag",s)       ?r  -- 2    (first)
r = find("Zag",s,r+1)           ?r  -- 10   (next)
r = find("Zag",s,r+1)           ?r  -- 0    (no more)
r = rfind("Zag",s)              ?r  -- 10   (last)
r = find("Zog",s)               ?r  -- 0    (none)


"mouse" "hat" "cup" "deodorant" "television"
"soap" "methamphetamine" "severed cat heads" "cup"
pstack
stklen tolist reverse
0 tolist var t

"Enter string to search: " input var s nl
true
while
    head s == if
        len t swap 0 put var t
    endif
    tail nip len
endwhile
drop

t len not if
    "String not found in list" print
else
    reverse
    "First index for " print s print " : " print 1 get print
    len 1 > if
        nl "Last index for " print s print " : " print len get print
    endif
endif
drop


procedure main()
every write(sedol("710889"|"B0YBKJ"|"406566"|"B0YBLH"|"228276"|
           "B0YBKL"|"557910"|"B0YBKR"|"585284"|"B0YBKT"|"B00030"))
end

procedure sedol(x)   #: return the completed sedol with check digit
static w,c
initial {
   every (i := -1, c := table())[!(&digits||&ucase)] := i +:= 1 # map chars
   every c[!"AEIOU"] := &null                 # delete vowels
   w := [1,3,1,7,3,9]                         # weights
   }

if *(x := map(x,&lcase,&ucase)) = *w then {   # match lengths
   every (t :=0, i := 1 to *x) do
      t +:= \c[x[i]]*w[i] | fail              # accumulate weighted chars
   return x  || (10 - (t%10))  % 10           # complete
   }
end


 [Sieve of Eratosthenes]
 [EDSAC program. Initial Orders 2]

[Memory usage:
   56..87   library subroutine P6, for printing
   88..222  main program
  224..293  mask table: 35 long masks; each has 34 1's and a single 0
  294..1023 array of bits for integers 2, 3, 4, ...,
            where bit is changed from 1 to 0 when integer is crossed out.
  The address of the mask table must be even, and clear of the main program.
  To change it, just change the value after "T47K" below.
  The address of the bit array will then be changed automatically.]

[Subroutine M3, prints header, terminated by blank row of tape.
 It's an "interlude", which runs and then gets overwritten.]
      [email protected]@E8FEZPF
      @&*SIEVE!OF!ERATOSTHENES!#2020
      @&*BASED!ON!CODE!BY!EIITI!WADA!#2001
      ..PZ

[Subroutine P6, prints strictly positive integer.
 32 locations; working locations 1, 4, 5.]
        T  56 K
  [email protected]@[email protected]@[email protected]@TFTF
  [email protected]@[email protected]@J995FJF!F

  [Store address of mask table in (say) location 47
  (chosen because its code letter M is first letter of "Mask").
  Address must be even and clear of main program.]
        T  47 K
        P 224 F  [<-------- address of mask table]

[Main program]
        T  88 K  [Define load address for main program.
                 Must be even, because of long values at start.]
        G     K [set @ (theta) for relative addressing]

[Long constants]
        T#Z PF TZ [clears sandwich digit between 0 and 1]
    [0] PD PF     [long value 1; also low word = short 1]
        T2#Z PF T2Z [clears sandwich digit between 2 and 3]
    [2] PF K4096F [long value 1000...000 binary;
                   also high word = teleprinter null]

 [Short constants
  The address in the following C order is the (exclusive) end of the bit table.
  Must be even: max = 1024, min = M + 72 where M is address of mask table set up above.
  Usually 1024, but may be reduced, e.g. to make the program run faster.]
    [4] C1024 D [or e.g. C 326 D to make it much faster]
    [5] U     F ['U' = 'T' - 'C']
    [6] K     F ['K' = 'S' - 'C']
    [7] H    #M [H order for start of mask table]
    [8] H  70#M [used to test for end of mask table]
    [9] P   2 F [constant4, or 2 in address field]
   [10] P  70 F [constant 140, or 70 in address field]
   [11] @     F [carriage return]
   [12] &     F [line feed]

 [Short variables]
   [13] P   1 F [p = number under test
                Let p = 35*q + r, where 0 <= r < 35]
   [14] P     F [4*q]
   [15] P   4 F [4*r]

 [Initial values of orders; required only for optional code below.]
   [16] C  70#M [initial value of a variable C order]
   [17] T    #M [initial value of a variable T order]
   [18] T  70#M [initial value of a variable T order]

   [19]
   [Enter with acc = 0]

  [Optional code to do some initializing at run time.
   This code allows the program to run again without being loaded again.]
         A  7 @ [initial values of variable orders]
         T 65 @
         A 16 @
         T 66 @
         A 17 @
         T 44 @
         A 18 @
         T 52 @

  [Initialize variables]
         A    @ [load 1 (short)]
         L    D [shift left 1]
         U 13 @ [p := 2]
         L  1 F [shift left 2]
         T 15 @ [4*r :=  8]
         T 14 @ [4*q :=  0]
  [End of optional code]

 [Make table of 35 masks 111...110,  111...101, ...,  011...111
  Treat the mask 011...111 separately to avoid accumulator overflow.
  Assume acc = 0 here.]
        S    #@ [acc all 1's]
        S  2 #@ [acc := 0111...111]
   [35] T 68 #M [store at high end of mask table]
        S    #@ [acc := -1]
        L     D [make mask 111...1110]
        G 43  @ [jump to store it
 [Loop shifting the mask right and storing the result in the mask table.
  Uses first entry of bit array as temporary store.]
   [39] T     F [clear acc]
        A 70 #M [load previous mask]
        L     D [shift left]
        A    #@ [add 1]
   [43] U 70 #M [update current mask]
   [44] T    #M [store it in table (order changed at run time)]
        A 44  @ [load preceding T order]
        A  9  @ [inc address by 2]
        U 44  @ [store back]
        S 35  @ [reached high entry yet?]
        G 39  @ [loop back if not]
 [Mask table is now complete]

 [Initialize bit array: no numbers crossed out, so all bits are 1]
   [50] T     F [clear acc]
        S     #@ [subtract long 1, make top 35 bits all 1's]
   [52] T 70 #M [store as long value, both words all 1's  (order changed at run time)]
        A  52 @ [load preceding order]
        A   9 @ [add 2 to address field]
        U  52 @ [and store back]
        S   5 @ [convert to C order with same address (*)]
        S   4 @ [test for end of bit array]
        G  50 @ [loop until stored all 1's in bit table]
 [(*) Done so that end of bit table can be stored at one place only
      in list of constants, i.e. 'C m D' only, not 'T m D' as well.]

 [Start of main loop.]
 [Testing whether number has been crossed out]
   [59] T     F [acc := 0]
        A  66 @ [deriving S order from C order]
        A   6 @
        T  64 @
        S    #@ [acc := -1]
   [64] S     F [acc := 1's complement of bit-table entry (order changed at run time)]
   [65] H    #M [mult reg := start of mask array (order changed at run time)]
   [66] C  70#M [acc := -1 iff p (current number) is crossed out (order changed at run time)]
 [The next order is to avoid accumulator overflow if acc = max positive number]
        E  70 @ [if acc >= 0, jump to process new prime]
       A     #@ [if acc < 0, add 1 to test for -1]
       E 106  @ [if acc now >= 0 number is crossed out, jump to test next]
 [Here if new prime found.
  Send it to the teleprinter]
   [70] O  11 @ [print CR]
        O  12 @ [print LF]
        T     F [clear acc]
        A  13 @ [load prime]
        T     F [store in C(0) for print routine]
        A  75 @ [for subroutine return]
        G 56  F [print prime]

 [Cross out its multiples by setting corresponding bits to 0]
        A  65 @ [load H order above]
        T 102 @ [plant in crossing-out loop]
        A  66 @ [load C order above]
        T1 03 @ [plant in crossing-out loop]

 [Start of crossing-out loop. Here acc must = 0]
   [81] A 102 @ [load H order below]
        A  15 @ [inc address field by 2*r, where p = 35q + r]
        U 102 @ [update H order]
        S   8 @ [compare with 'H 70 #M']
        G  93 @ [skip if not gone beyond end of mask table]
        T     F [wrap mask address and inc address in bit tsble]
        A 102 @ [load H order below]
        S  10 @ [reduce mask address by 70]
        T 102 @ [update H order]
        A 103 @ [load C order below]
        A   9 @ [add 2 to address]
        T 103 @ [update C order]
   [93] T     F [clear acc]
        A 103 @ [load C order below]
        A  14 @ [inc address field by 2*q, where p = 35q + r]
        U 103 @ [update C order]
        S   4 @ [test for end of bit array]
        E 106 @ [if finished crossing out, loop to test next number]
        A  4  @ [restore C order]
        A  5  @ [make T order with same address]
        T 104 @ [store below]

 [Execute the crossing-out orders created above]
  [102] X     F [mult reg := mask (order created at run time)]
  [103] X     F [acc := logical and with bit-table entry (order created at run time)]
  [104] X     F [update entry (order created at run time)]
        E  81 @ [loop back with acc = 0]

  [106] T     F [clear acc]
        A  13 @ [load p = number under test]
        A     @ [add 1 (single)]
        T  13 @ [update]
        A  15 @ [load 4*r, where p = 35q + r]
        A   9 @ [add 4]
        U  15 @ [store back (r inc'd by 1)]
        S  10 @ [is 4*r now >= 140?]
        G 119 @ [no, skip]
        T  15 @ [yes, reduce 4*r by 140]
        A  14 @ [load 4*q]
        A   9 @ [add 4]
        T  14 @ [store back (q inc'd by 1)]
  [119] T     F [clear acc]
        A  65 @ [load 'H ... D' order, which refers to a mask]
        A   9 @ [inc mask address by 2]
        U  65 @ [update order]
        S   8 @ [over end of mask table?]
        G  59 @ [no, skip wrapround code]
        A   7 @ [yes, add constant to wrap round]
        T  65 @ [update H order]
        A  66 @
        A   9 @ [inc address by 2]
        U  66 @ [and store back]
        S   4 @ [test for end, as defined by C order at start]
        G  59 @ [loop back if not at end]

[Finished whole thing]
  [132] O   3 @ [output null to flush teleprinter buffer]
        Z     F [stop]
        E  19 Z [address to start execution]
        P     F [acc = 0 at start]


$haystack = array("Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo");

foreach (array("Washington","Bush") as $needle) {
  $i = array_search($needle, $haystack);
  if ($i === FALSE) // note: 0 is also considered false in PHP, so you need to specifically check for FALSE
    echo "$needle is not in haystack\n";
  else
    echo "$i $needle\n";
}


import util.

go =>
  Haystack=["Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Bush", "Charlie", "Bush", "Boz", "Zag"],

  println("First 'Bush'"=search_list(Haystack,"Bush")),
  println("Last 'Bush'"=search_list_last(Haystack,"Bush")),

  println("All 'Bush'"=search_list_all(Haystack,"Bush")),

  catch(WaldoIx=search_list(Haystack,"Waldo"),E,println(E)),
  println("Waldo"=WaldoIx),

  nl.

% Wrapping find_first_of/2 and find_last_of/2 with exceptions
search_list(Haystack,Needle) = Ix =>
  Ix = find_first_of(Haystack,Needle),
  if Ix < 0 then
    throw $error(search_list(Needle),not_found)
  end.

search_list_last(Haystack,Needle) = Ix =>
  Ix = find_last_of(Haystack,Needle),
  if Ix < 0 then
    throw $error(search_list_last(Needle),not_found)
  end.

% Find all indices
search_list_all(Haystack,Needle) = Ixs =>
  Ixs = [Ix : {W,Ix} in zip(Haystack,1..Haystack.len), W == Needle],
  if Ixs == [] then
    throw $error(search_list_all(Needle),not_found)
  end.


(de lastIndex (Item Lst)
   (- (length Lst) (index Item (reverse Lst)) -1) )

(de findNeedle (Fun Sym Lst)
   (prinl Sym " " (or (Fun Sym Lst) "not found")) )

(let Lst '(Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo)
   (findNeedle index 'Washington Lst)
   (findNeedle index 'Bush Lst)
   (findNeedle lastIndex 'Bush Lst) )


import java.util.Scanner;

public class SEDOL{
	public static void main(String[] args){
		Scanner sc = new Scanner(System.in);
		while(sc.hasNext()){
			String sedol = sc.next();
			System.out.println(sedol + getSedolCheckDigit(sedol));
		}
	}

	private static final int[] mult = {1, 3, 1, 7, 3, 9};

	public static int getSedolCheckDigit(String str){
	    if(!validateSedol(str)){
	    	System.err.println("SEDOL strings must contain six characters with no vowels.");
	    	return -1;
	    }
	    str = str.toUpperCase();
	    int total = 0;
	    for(int i = 0;i < 6; i++){
	        char s = str.charAt(i);
	        total += Character.digit(s, 36) * mult[i];
	    }
	    return (10 - (total % 10)) % 10;
	}

	public static boolean validateSedol(String str){
		return (str.length() == 6) && !str.toUpperCase().matches(".*?[AEIOU].*?");
	}
}


function sedol(input) {
    return input + sedol_check_digit(input);
}

var weight = [1, 3, 1, 7, 3, 9, 1];
function sedol_check_digit(char6) {
    if (char6.search(/^[0-9BCDFGHJKLMNPQRSTVWXYZ]{6}$/) == -1)
        throw "Invalid SEDOL number '" + char6 + "'";
    var sum = 0;
    for (var i = 0; i < char6.length; i++)
        sum += weight[i] * parseInt(char6.charAt(i), 36);
    var check = (10 - sum%10) % 10;
    return check.toString();
}

var input = [
    '710889', 'B0YBKJ', '406566', 'B0YBLH', '228276',
    'B0YBKL', '557910', 'B0YBKR', '585284', 'B0YBKT',
    "BOATER" , "12345", "123456", "1234567"
];

var expected = [
    '7108899', 'B0YBKJ7', '4065663', 'B0YBLH2', '2282765',
    'B0YBKL9', '5579107', 'B0YBKR5', '5852842', 'B0YBKT7',
    null, null, '1234563', null
];

for (var i in input) {
    try {
        var sedolized = sedol(input[i]);
        if (sedolized == expected[i])
            print(sedolized);
        else
            print("error: calculated sedol for input " + input[i] +
                  " is " + sedolized + ", but it should be " + expected[i]
            );
    }
    catch (e) {
        print("error: " + e);
    }
}


class
    APPLICATION

create
    make

feature
       make
            -- Run application.
        do
            across primes_through (100) as ic loop print (ic.item.out + " ") end
        end

    primes_through (a_limit: INTEGER): LINKED_LIST [INTEGER]
            -- Prime numbers through `a_limit'
        require
            valid_upper_limit: a_limit >= 2
        local
            l_tab: ARRAY [BOOLEAN]
        do
            create Result.make
            create l_tab.make_filled (True, 2, a_limit)
            across
                l_tab as ic
            loop
                if ic.item then
                    Result.extend (ic.target_index)
                    across ((ic.target_index * ic.target_index) |..| l_tab.upper).new_cursor.with_step (ic.target_index) as id
                    loop
                        l_tab [id.item] := False
                    end
                end
            end
        end
end


search: procedure () returns (fixed binary);
   declare haystack (0:9) character (200) varying static initial
      ('apple', 'banana', 'celery', 'dumpling', 'egg', 'flour',
       'grape', 'pomegranate', 'raisin', 'sugar' );
   declare needle character (200) varying;
   declare i fixed binary;
   declare missing_needle condition;

   on condition(missing_needle) begin;
      put skip list ('your string ''' || needle ||
         ''' does not exist in the haystack.');
   end;

   put ('Please type a string');
   get edit (needle) (L);
   do i = lbound(haystack,1) to hbound(haystack,1);
      if needle = haystack(i) then return (i);
   end;
   signal condition(missing_needle);
   return (lbound(haystack,1)-1);
end search;


To run:
Start up.
Make an example haystack.
Find "b" in the example haystack giving a count.
Destroy the example haystack.
Write "The index of ""b"" is " then the count on the console.
Wait for the escape key.
Shut down.

A needle is a string.

Some hay is some strings.

A bale is a thing with some hay.

A haystack is some bales.

To add some hay to a haystack:
Allocate memory for a bale.
Put the hay into the bale's hay.
Append the bale to the haystack.

To make an example haystack:
Add "a" to the example haystack.
Add "a" to the example haystack.
Add "b" to the example haystack.
Add "c" to the example haystack.
Add "d" to the example haystack.

\ As Plain English doesn't have exceptions, return -1 if the needle is not found.
To find a needle in a haystack giving a count:
Get a bale from the haystack.
Loop.
If the bale is nil, put -1 into the count; exit.
If the bale's hay is the needle, exit.
Put the bale's next into the bale.
Bump the count.
Repeat.


def ascii_upcase:
  explode | map( if 97 <= . and . <= 122 then . - 32  else . end) | implode;

def sedol_checksum:
  def encode(a): 10 + (a|explode[0]) - ("A"|explode[0]);
  . as $sed
  | [1,3,1,7,3,9] as $sw
  | reduce range(0;6) as $i
      (0;
       $sed[$i:$i+1] as $c
       | if ( "0123456789" | index($c) )
         then . + ($c|tonumber) * $sw[$i]
         else . + encode($c) * $sw[$i]
         end )
  | (10 - (. % 10)) % 10 ;

# error on error, else pass input to output
def check_valid_sedol:
  def has_vowel:
    ("AEIOU"|explode) as $vowels
    | reduce explode[] as $c
        (false; if . then . else $vowels|index($c) end);

  if has_vowel then error( "\(.) is not a valid SEDOL code" )
  else .
  end
  | if length > 7 or length < 6 then
      error( "\(.) is too long or too short to be valid SEDOL")
    else .
    end;

def sedolize:
  ascii_upcase as $in
  | $in
  | check_valid_sedol
  | .[0:6] as $sedol
  | ($sedol | sedol_checksum | tostring) as $sedolcheck
  | ($sedol + $sedolcheck) as $ans
  | if length == 7 and $ans != $in then
         $ans + " (original \($in) has wrong checksum digit"
    else $ans
    end ;
sedolize


using Base.Test

function appendchecksum(chars::AbstractString)
    if !all(isalnum, chars) throw(ArgumentError("invalid SEDOL number '$chars'")) end
    weights = [1, 3, 1, 7, 3, 9, 1]

    s = 0
    for (w, c) in zip(weights, chars)
        s += w * parse(Int, c, 36)
    end
    return string(chars, (10 - s % 10) % 10)
end

tests = ["710889", "B0YBKJ", "406566", "B0YBLH", "228276", "B0YBKL", "557910", "B0YBKR", "585284", "B0YBKT", "B00030"]
csums = ["7108899", "B0YBKJ7", "4065663", "B0YBLH2", "2282765", "B0YBKL9", "5579107", "B0YBKR5", "5852842", "B0YBKT7", "B000300"]

@testset "Checksums" begin
    for (t, c) in zip(tests, csums)
        @test appendchecksum(t) == c
    end
end


// version 1.1.0

val weights = listOf(1, 3, 1, 7, 3, 9, 1)

fun sedol7(sedol6: String): String {
    if (sedol6.length != 6) throw IllegalArgumentException("Length of argument string must be 6")
    var sum = 0
    for (i in 0..5) {
        val c = sedol6[i]
        val v = when (c) {
            in '0'..'9' -> c.toInt() - 48
            in 'A'..'Z' -> c.toInt() - 55
            else        -> throw IllegalArgumentException("Argument string contains an invalid character")
        }
        sum += v * weights[i]
    }
    val check = (10 - (sum % 10)) % 10
    return sedol6 + (check + 48).toChar()
}

fun main(args: Array<String>) {
    val sedol6s = listOf("710889", "B0YBKJ", "406566", "B0YBLH", "228276", "B0YBKL",
                         "557910", "B0YBKR", "585284", "B0YBKT", "B00030")
    for (sedol6 in sedol6s) println("$sedol6 -> ${sedol7(sedol6)}")
}


defmodule Prime do
  def eratosthenes(limit \\ 1000) do
    sieve = [false, false | Enum.to_list(2..limit)] |> List.to_tuple
    check_list = [2 | Stream.iterate(3, &(&1+2)) |> Enum.take(round(:math.sqrt(limit)/2))]
    Enum.reduce(check_list, sieve, fn i,tuple ->
      if elem(tuple,i) do
        clear_num = Stream.iterate(i*i, &(&1+i)) |> Enum.take_while(fn x -> x <= limit end)
        clear(tuple, clear_num)
      else
        tuple
      end
    end)
  end

  defp clear(sieve, list) do
    Enum.reduce(list, sieve, fn i, acc -> put_elem(acc, i, false) end)
  end
end

limit = 199
sieve = Prime.eratosthenes(limit)
Enum.each(0..limit, fn n ->
  if x=elem(sieve, n), do: :io.format("~3w", [x]), else: :io.format("  .")
  if rem(n+1, 20)==0, do: IO.puts ""
end)


FUNCTION PBMAIN () AS LONG
    DIM haystack(54) AS STRING
    ARRAY ASSIGN haystack() = "foo", "bar", "baz", "quux", "quuux", "quuuux", _
                 "bazola", "ztesch", "foo", "bar", "thud", "grunt", "foo", _
                 "bar", "bletch", "foo", "bar", "fum", "fred", "jim", _
                 "sheila", "barney", "flarp", "zxc", "spqr", ";wombat", "shme", _
                 "foo", "bar", "baz", "bongo", "spam", "eggs", "snork", "foo", _
                 "bar", "zot", "blarg", "wibble", "toto", "titi", "tata", _
                 "tutu", "pippo", "pluto", "paperino", "aap", "noot", "mies", _
                 "oogle", "foogle", "boogle", "zork", "gork", "bork"
    DIM needle AS STRING, found AS LONG, lastFound AS LONG
    DO
        needle = INPUTBOX$("Word to search for? (Leave blank to exit)")
        IF needle <> "" THEN
            ' collate ucase -> case insensitive
            ARRAY SCAN haystack(), COLLATE UCASE, = needle, TO found
            IF found > 0 THEN
                lastFound = found
                MSGBOX "Found """ & needle & """ at index " & TRIM$(STR$(found - 1))
                IF found < UBOUND(haystack) THEN
                    DO
                        ARRAY SCAN haystack(lastFound), COLLATE UCASE, = needle, TO found
                        IF found > 0 THEN
                            MSGBOX "Another occurence of """ & needle & """ at index " & _
                                   TRIM$(STR$(found + lastFound - 1))
                            lastFound = found + lastFound
                        ELSE
                            MSGBOX "No more occurences of """ & needle & """ found"
                            EXIT DO 'will exit inner DO, not outer
                        END IF
                    LOOP
                END IF
            ELSE
                MSGBOX "No occurences of """ & needle & """ found"
            END IF
        ELSE
            EXIT DO
        END IF
    LOOP
END FUNCTION


function index($haystack,$needle) {
    $index = $haystack.IndexOf($needle)
    if($index -eq -1) {
        Write-Warning "$needle is absent"
    } else {
        $index
    }

}
$haystack = @("word", "phrase", "preface", "title", "house", "line", "chapter", "page", "book", "house")
index $haystack "house"
index $haystack "paragraph"


search_a_list(N1, N2) :-
	L = ["Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie", "Bush", "Boz", "Zag"],

	write('List is :'), maplist(my_write, L), nl, nl,

	(   nth1(Ind1, L, N1) ->
	    format('~s is in position ~w~n', [N1, Ind1])
	;   format('~s is not present~n', [N1])),
	(   nth1(Ind2, L, N2) ->
	    format('~s is in position ~w~n', [N2, Ind2])
	;   format('~s is not present~n', [N2])),
	(   reverse_nth1(Ind3, L, N1) ->
	    format('~s last position is ~w~n', [N1, Ind3])
	;   format('~s is not present~n', [N1])).

reverse_nth1(Ind, L, N) :-
	reverse(L, RL),
	length(L, Len),
	nth1(Ind1, RL, N),
	Ind is Len - Ind1 + 1.

my_write(Name) :-
	writef(' %s', [Name]).


val .csd = f(.code) {
    given len(.code) {
        case 0:
            return "nada, zip, zilch"
        case != 6:
            return "invalid length"
    }

    if matching(re/[^B-DF-HJ-NP-TV-Z0-9]/, .code) {
        return "invalid character(s)"
    }

    val .weight = [1,3,1,7,3,9]

    val .nums = s2n .code
    val .sum = for[=0] .i of .nums {
        _for += .nums[.i] x .weight[.i]
    }

    toString 9 - (.sum - 1) rem 10
}

val .h = h{
    # invalid...
    "": 0,
    "123": 0,
    "A00030": 0,
    "E00030": 0,
    "I00030": 0,
    "O00030": 0,
    "U00030": 0,
    "β00030": 0,

    # valid...
    "710889": 9,
    "B0YBKJ": 7,
    "406566": 3,
    "B0YBLH": 2,
    "228276": 5,
    "B0YBKL": 9,
    "557910": 7,
    "B0YBKR": 5,
    "585284": 2,
    "B0YBKT": 7,
    "B00030": 0,
}

for .input in sort(keys .h) {
    val .d = .csd(.input)
    if len(.d) > 1 {
        writeln .input, ": ", .d
    } else {
        val .expect = toString .h[.input]
        write .input, .d
        writeln if .expect == .d {""} else {
            $" (SEDOL test failed; expected check digit \.expect;)"}
    }
}


'adapted from BASIC solution
    mult(1) = 1: mult(2) = 3: mult(3) = 1
    mult(4) = 7: mult(5) = 3: mult(6) = 9

DO
        INPUT a$
        PRINT a$ + STR$(getSedolCheckDigit(a$))
LOOP WHILE a$ <> ""

FUNCTION getSedolCheckDigit (str$)
    IF LEN(str$) <> 6 THEN
        PRINT "Six chars only please"
        EXIT FUNCTION
    END IF
    str$ = upper$(str$)
    total = 0
    FOR i = 1 TO 6
        s$ = MID$(str$, i, 1)
        IF (s$ = "A") OR (s$ = "E") OR (s$ = "I") OR (s$ = "O") OR (s$ = "U") THEN
                PRINT "No vowels"
                EXIT FUNCTION
        END IF
        IF (ASC(s$) >= 48) AND (ASC(s$) <= 57) THEN
                total = total + VAL(s$) * mult(i)
        ELSE
                total = total + (ASC(s$) - 55) * mult(i)
        END IF

    NEXT i
    getSedolCheckDigit = (10 - (total MOD 10)) MOD 10
END FUNCTION


module Main exposing (main)

import Browser exposing (element)
import Task exposing (Task, succeed, perform, andThen)
import Html exposing (Html, div, text)
import Time exposing (now, posixToMillis)

type CIS a = CIS a (() -> CIS a)

uptoCIS2List : comparable -> CIS comparable -> List comparable
uptoCIS2List n cis =
  let loop (CIS hd tl) lst =
        if hd > n then List.reverse lst
        else loop (tl()) (hd :: lst)
  in loop cis []

countCISTo : comparable -> CIS comparable -> Int
countCISTo n cis =
  let loop (CIS hd tl) cnt =
        if hd > n then cnt else loop (tl()) (cnt + 1)
  in loop cis 0

primesTreeFolding : () -> CIS Int
primesTreeFolding() =
  let
    merge (CIS x xtl as xs) (CIS y ytl as ys) =
      case compare x y of
        LT -> CIS x <| \ () -> merge (xtl()) ys
        EQ -> CIS x <| \ () -> merge (xtl()) (ytl())
        GT -> CIS y <| \ () -> merge xs (ytl())
    pmult bp =
      let adv = bp + bp
          pmlt p = CIS p <| \ () -> pmlt (p + adv)
      in pmlt (bp * bp)
    allmlts (CIS bp bptl) =
      CIS (pmult bp) <| \ () -> allmlts (bptl())
    pairs (CIS frst tls) =
      let (CIS scnd tlss) = tls()
      in CIS (merge frst scnd) <| \ () -> pairs (tlss())
    cmpsts (CIS (CIS hd tl) tls) =
      CIS hd <| \ () -> merge (tl()) <| cmpsts <| pairs (tls())
    testprm n (CIS hd tl as cs) =
      if n < hd then CIS n <| \ () -> testprm (n + 2) cs
      else testprm (n + 2) (tl())
    oddprms() =
      CIS 3 <| \ () -> testprm 5 <| cmpsts <| allmlts <| oddprms()
  in CIS 2 <| \ () -> oddprms()

type alias Model = ( Int, String, String )

type Msg = Start Int | Done ( Int, Int )

cLIMIT : Int
cLIMIT = 1000000

timemillis : () -> Task Never Int
timemillis() = now |> andThen (\ t -> succeed (posixToMillis t))

test : Int -> Cmd Msg
test lmt =
  let cnt = countCISTo lmt (primesTreeFolding()) -- (soeDict())
  in timemillis() |> andThen (\ t -> succeed ( t, cnt )) |> perform Done

myupdate : Msg -> Model -> (Model, Cmd Msg)
myupdate msg mdl =
  let (strttm, oldstr, _) = mdl in
  case msg of
    Start tm -> ( ( tm, oldstr, "Running..." ), test cLIMIT )
    Done (stptm, answr) ->
      ( ( stptm, oldstr, "Found " ++ String.fromInt answr ++
           " primes to " ++ String.fromInt cLIMIT ++
           " in " ++ String.fromInt (stptm - strttm) ++ " milliseconds." )
      , Cmd.none )

myview : Model -> Html msg
myview mdl =
  let (_, str1, str2) = mdl
  in div [] [ div [] [text str1], div [] [text str2] ]

main : Program () Model Msg
main =
  element { init = \ _ -> ( ( 0
                            , "The primes up to 100 are:  " ++
                                (primesTreeFolding() |> uptoCIS2List 100
                                  |> List.map String.fromInt
                                  |> String.join ", ") ++ "."
                            , "" ), perform Start (timemillis()) )
          , update = myupdate
          , subscriptions = \ _ -> Sub.none
          , view = myview }


If OpenConsole()  ; Open a simple console to interact with user
  NewList Straws.s()
  Define Straw$, target$="TBA"
  Define found

  Restore haystack ; Read in all the straws of the haystack.
  Repeat
    Read.s Straw$
    If Straw$<>""
      AddElement(Straws())
      Straws()=UCase(Straw$)
      Continue
    Else
      Break
    EndIf
  ForEver

  While target$<>""
    Print(#CRLF$+"Enter word to search for (leave blank to quit) :"): target$=Input()
    ResetList(Straws()): found=#False
    While NextElement(Straws())
      If UCase(target$)=Straws()
        found=#True
        PrintN(target$+" found as index #"+Str(ListIndex(Straws())))
      EndIf
    Wend
    If Not found
      PrintN("Not found.")
    EndIf
  Wend
EndIf

DataSection
  haystack:
  Data.s "Zig","Zag","Zig","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo",""
EndDataSection


haystack=["Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo"]

for needle in ("Washington","Bush"):
  try:
    print haystack.index(needle), needle
  except ValueError, value_error:
    print needle,"is not in haystack"


divert(-1)
changequote(`[',`]')
define([_bar],include(sedol.inp))
define([eachlineA],
   [ifelse(eval($2>0),1,
      [$3(substr([$1],0,$2))[]eachline(substr([$1],incr($2)),[$3])])])
define([eachline],[eachlineA([$1],index($1,[
]),[$2])])
define([_idx],
   [index([0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ],substr($1,$2,1))])
define([_wsum],
   [eval(_idx($1,0)+_idx($1,1)*3+_idx($1,2)+_idx($1,3)*7+_idx($1,4)*3+_idx($1,5)*9)])
define([checksum],
   [$1[]eval((10-_wsum($1)%10)%10)
])
divert
eachline(_bar,[checksum])


SEDOL
 NEW A,B
SEDOL1
 READ !,"Enter the first 6 digits of a SEDOL: ",A
 SET B=$$SEDOLCHK(A)
 WRITE !,$SELECT($LENGTH(B)=1:"Full SEDOL is "_A_B,1:B)
 GOTO SEDOL1
 QUIT
SEDOLCHK(STOCK)
 NEW WT,VAL,I,CHK,C,FLAG
 SET WT="1317391",VAL=0,FLAG=0
 FOR I=1:1:6 SET C=$$TOUPPER($EXTRACT(STOCK,I)),VAL=VAL+($$SEDVAL(C)*$EXTRACT(WT,I)) SET:"AEIOUaeiou"[C FLAG=1
 SET:$LENGTH(STOCK)'=6 FLAG=1
 KILL WT,I,CHK,C
 QUIT $SELECT(FLAG:"INVALID",'FLAG:(10-(VAL#10))#10)
SEDVAL(X)
 QUIT $SELECT($ISVALIDNUM(X):X,1:$ASCII(X)-$ASCII("@")+9)
TOUPPER(X)
 NEW UP,LO
 SET UP="ABCDEFGHIJKLMNOPQRSTUVWXYZ",LO="abcdefghijklmnopqrstuvwxyz"
 QUIT $TRANSLATE(X,LO,UP)


proc c2v(c: char): int =
  assert c notin "AEIOU"
  if c < 'A': ord(c) - ord('0') else: ord(c) - ord('7')

const weight = [1, 3, 1, 7, 3, 9]

proc checksum(sedol: string): char =
  var val = 0
  for i, ch in sedol:
    val += c2v(ch) * weight[i]
  result = chr((10 - val mod 10) mod 10 + ord('0'))

for sedol in ["710889", "B0YBKJ", "406566", "B0YBLH",
              "228276", "B0YBKL", "557910", "B0YBKR",
              "585284", "B0YBKT", "B00030"]:
  echo sedol, " → ", sedol & checksum(sedol)


(defun sieve-set (limit)
  (let ((xs (make-vector (1+ limit) 0)))
    (cl-loop for i from 2 to limit
             when (zerop (aref xs i))
             collect i
             and do (cl-loop for m from (* i i) to limit by i
                             do (aset xs m 1)))))


find.needle <- function(haystack, needle="needle", return.last.index.too=FALSE)
{
   indices <- which(haystack %in% needle)
   if(length(indices)==0) stop("no needles in the haystack")
   if(return.last.index.too) range(indices) else min(indices)
}


(define (index xs y)
  (for/first ([(x i) (in-indexed xs)]
              #:when (equal? x y))
    i))


my @haystack = <Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo>;

for <Washington Bush> -> $needle {
    say "$needle -- { @haystack.first($needle, :k) // 'not in haystack' }";
}


let char2value c =
  assert (not (String.contains "AEIOU" c));
  match c with
  | '0'..'9' -> int_of_char c - int_of_char '0'
  | 'A'..'Z' -> int_of_char c - int_of_char 'A' + 10
  | _ -> assert false

let sedolweight = [1;3;1;7;3;9]

let explode s =
  s |> String.to_seq |> List.of_seq

let checksum sedol =
  let tmp = List.fold_left2 (fun sum ch weight -> sum + char2value ch * weight)
              0 (explode sedol) sedolweight in
  string_of_int ((10 - (tmp mod 10)) mod 10) ;;

List.iter (fun sedol -> print_endline (sedol ^ checksum sedol))
  [ "710889";
    "B0YBKJ";
    "406566";
    "B0YBLH";
    "228276";
    "B0YBKL";
    "557910";
    "B0YBKR";
    "585284";
    "B0YBKT" ]


func: sedol(s)
   [ 1, 3, 1, 7, 3, 9 ] s
   zipWith(#[ dup isDigit ifTrue: [ '0' - ] else: [ 'A' - 10 + ] * ]) sum
   10 mod 10 swap - 10 mod
   StringBuffer new s << swap '0' + <<c ;


-module( sieve_of_eratosthenes ).

-export( [primes_upto/1] ).

primes_upto( N ) ->
	Ns = lists:seq( 2, N ),
	Dict = dict:from_list( [{X, potential_prime} || X <- Ns] ),
	{Upto_sqrt_ns, _T} = lists:split( erlang:round(math:sqrt(N)), Ns ),
	{N, Prime_dict} = lists:foldl( fun find_prime/2, {N, Dict}, Upto_sqrt_ns ),
	lists:sort( dict:fetch_keys(Prime_dict) ).

find_prime( N, {Max, Dict} ) -> find_prime( dict:find(N, Dict), N, {Max, Dict} ).

find_prime( error, _N, Acc ) -> Acc;
find_prime( {ok, _Value}, N, {Max, Dict} ) when Max > N*N ->
    {Max, lists:foldl( fun dict:erase/2, Dict, lists:seq(N*N, Max, N))};
find_prime( {ok, _Value}, _, R) -> R.


rebol [
	Title: "List Indexing"
	URL: http://rosettacode.org/wiki/Index_in_a_list
]

locate: func [
	"Find the index of a string (needle) in string collection (haystack)."
	haystack [series!] "List of values to search."
	needle [string!] "String to find in value list."
	/largest "Return the largest index if more than one needle."
	/local i
][
	i: either largest [
		find/reverse tail haystack needle][find haystack needle]
	either i [return index? i][
		throw reform [needle "is not in haystack."]
	]
]

; Note that REBOL uses 1-base lists instead of 0-based like most
; computer languages. Therefore, the index provided will be one
; higher than other results on this page.

haystack: parse "Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo" none

print "Search for first occurance:"
foreach needle ["Washington" "Bush"] [
	print catch [
		reform [needle "=>" locate haystack needle]
	]
]

print [crlf "Search for last occurance:"]
foreach needle ["Washington" "Bush"] [
	print catch [
		reform [needle "=>" locate/largest haystack needle]
	]
]


/*REXX program searches a collection of strings   (an array of periodic table elements).*/
hay.=                                            /*initialize the haystack collection.  */
hay.1  = 'sodium'
hay.2  = 'phosphorous'
hay.3  = 'californium'
hay.4  = 'copernicium'
hay.5  = 'gold'
hay.6  = 'thallium'
hay.7  = 'carbon'
hay.8  = 'silver'
hay.9  = 'curium'
hay.10 = 'copper'
hay.11 = 'helium'
hay.12 = 'sulfur'

needle = 'gold'                                  /*we'll be looking for the gold.       */
upper needle                                     /*in case some people capitalize stuff.*/
found=0                                          /*assume the needle isn't found yet.   */

          do j=1  while hay.j\==''               /*keep looking in the haystack.        */
          _=hay.j;     upper _                   /*make it uppercase to be safe.        */
          if _=needle  then do;  found=1         /*we've found the needle in haystack.  */
                                 leave           /*   ··· and stop looking, of course.  */
                            end
          end   /*j*/

if found  then return j                          /*return the haystack  index  number.  */
          else say  needle  "wasn't found in the haystack!"
return 0                                         /*indicates the needle  wasn't  found. */


program Sedols(output);

function index(c: char): integer;
  const
    alpha = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  var
    i: integer;
  begin
    index := 0;
    for i := low(alpha) to high(alpha) do
      if c = alpha[i] then
        index := i;
  end;

function checkdigit(c: string): char;
  const
    weight: array [1..6] of integer = (1, 3, 1, 7, 3, 9);
  var
    i, sum: integer;
  begin
    sum := 0;
    for i := 1 to 6 do
      sum := sum + (index(c[i]) - 1) * weight[i];
    checkdigit := char((10 - (sum mod 10)) mod 10 + 48);
  end;

const
  codes: array [1..11] of string =
    ('710889', 'B0YBKJ', '406566', 'B0YBLH',
     '228276', 'B0YBKL', '557910', 'B0YBKR',
     '585284', 'B0YBKT', 'B00030');

var
  seforl: string;
  i: integer;

begin
  for i := low(codes) to high(codes) do
  begin
    seforl := codes[i];
    setlength(seforl, 7);
    seforl[7] := checkdigit(codes[i]);
    writeln(codes[i], ' -> ', seforl);
  end;
end.


PROGRAM SIEVE_ORG
  ! --------------------------------------------------
  ! Eratosthenes Sieve Prime Number Program in BASIC
  ! (da 3 a SIZE*2)   from Byte September 1981
  !---------------------------------------------------
  CONST SIZE%=8190

  DIM FLAGS%[SIZE%]

BEGIN
  PRINT("Only 1 iteration")
  COUNT%=0
  FOR I%=0 TO SIZE% DO
     IF FLAGS%[I%]=TRUE THEN
         !$NULL
       ELSE
         PRIME%=I%+I%+3
         K%=I%+PRIME%
         WHILE NOT (K%>SIZE%) DO
            FLAGS%[K%]=TRUE
            K%=K%+PRIME%
         END WHILE
         PRINT(PRIME%;)
         COUNT%=COUNT%+1
     END IF
  END FOR
  PRINT
  PRINT(COUNT%;" PRIMES")
END PROGRAM


haystack = ["alpha","bravo","charlie","delta","echo","foxtrot","golf",
"hotel","india","juliet","kilo","lima","mike","needle",
"november","oscar","papa","quebec","romeo","sierra","tango",
"needle","uniform","victor","whisky","x-ray","yankee","zulu"]

needle = "needle"
maxindex = len(haystack)

for index = 1 to maxindex
    if needle = haystack[index] exit ok
next
if index <= maxindex
   see "first found at index " + index + nl ok
for last = maxindex to 0 step -1
    if needle = haystack[last] exit ok
next
if !=index see " last found at index " + last + nl
else see "not found" + nl ok


haystack = %w(Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo)

%w(Bush Washington).each do |needle|
  if (i = haystack.index(needle))
    puts "#{i} #{needle}"
  else
    raise "#{needle} is not in haystack\n"
  end
end


haystack$ = ("Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo Bush ")
needle$   = "Zag Wally Bush Chicken"

while word$(needle$,i+1," ") <> ""
  i  = i + 1
  thisNeedle$ = word$(needle$,i," ") + " "
  j  = instr(haystack$,thisNeedle$)
  k1 = 0
  k  = instr(haystack$,thisNeedle$,j+1)
  while k <> 0
    k1 = k
    k  = instr(haystack$,thisNeedle$,k+1)
  wend
  if j <> 0 then
    print thisNeedle$;" located at:";j;
    if k1 <> 0 then print " Last position located at:";k1;
    print
   else
    print thisNeedle$;" is not in the list"
  end if
wend


use List::Util qw(sum);
use POSIX qw(strtol);

sub zip(&\@\@) {
  my $f = shift;
  my @a = @{shift()};
  my @b = @{shift()};
  my @result;
  push(@result, $f->(shift @a, shift @b)) while @a && @b;
  return @result;
}

my @weights = (1, 3, 1, 7, 3, 9);
sub sedol($) {
  my $s = shift;
  $s =~ /[AEIOU]/ and die "No vowels";
  my @vs = map {(strtol $_, 36)[0]} split //, $s;
  my $checksum = sum (zip {$_[0] * $_[1]} @vs, @weights);
  my $check_digit = (10 - $checksum % 10) % 10;
  return $s . $check_digit;
}

while (<>) {
    chomp;
    print sedol($_), "\n";
}


constant limit = 1000
sequence flags,primes
flags = repeat(1, limit)
for i = 2 to sqrt(limit) do
    if flags[i] then
        for k = i*i to limit by i do
            flags[k] = 0
        end for
    end if
end for

primes = {}
for i = 2 to limit do
    if flags[i] = 1 then
        primes &= i
    end if
end for
? primes


fn main() {
    let haystack=vec!["Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie",
                        "Bush", "Boz", "Zag"];

    println!("First occurence of 'Bush' at {:?}",haystack.iter().position(|s| *s=="Bush"));
    println!("Last occurence of 'Bush' at {:?}",haystack.iter().rposition(|s| *s=="Bush"));
    println!("First occurence of 'Rob' at {:?}",haystack.iter().position(|s| *s=="Rob"));
}


variable haystack = ["Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo","Ronald"];

define find(needle)
{
    variable i = where(haystack == needle);
    if (length(i)) {
       % print(sprintf("%s: first=%d, last=%d", needle, i[0], i[-1]));
       return(i[0], i[-1]);
    }
    else
       throw ApplicationError, "an exception";
}

($1, $2) = find("Ronald");     % returns 3, 9
($1, $2) = find("McDonald");   % throws ApplicationError, labelled "an exception"


class MAIN is
   main is
      haystack :ARRAY{STR} := |"Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie", "Bush", "Bozo"|;
      needles :ARRAY{STR} := | "Washington", "Bush" |;
      loop needle ::= needles.elt!;
	 index ::= haystack.index_of(needle);
	 if index < 0 then
	    #OUT + needle + " is not in the haystack\n";
	 else
	    #OUT + index + " " + needle + "\n";
	 end;
      end;
   end;
end;


def findNeedles(needle: String, haystack: Seq[String]) = haystack.zipWithIndex.filter(_._1 == needle).map(_._2)
def firstNeedle(needle: String, haystack: Seq[String]) = findNeedles(needle, haystack).head
def lastNeedle(needle: String, haystack: Seq[String]) = findNeedles(needle, haystack).last


type string6(object s)
    return string(s) and length(s)=6
end type

type sedolch(integer ch)
    return ch>='0' and ch<='Z' and (ch<='9' or ch>='A') and not find(ch,"AEIOU")
end type

function sedol(string6 t)
sedolch c
integer s = 0
    for i=1 to 6 do
        c = t[i]
        s += iff(c>='A'?c-'A'+10:c-'0')*{1,3,1,7,3,9}[i]
    end for
    return t & mod(10-mod(s,10),10)+'0'
end function

constant tests = {"710889",
                  "B0YBKJ",
                  "406566",
                  "B0YBLH",
                  "228276",
                  "B0YBKL",
                  "557910",
                  "B0YBKR",
                  "585284",
                  "B0YBKT",
                  "B00030"}
for i=1 to length(tests) do
    ?sedol(tests[i])
end for


function char2value($c) {
  assert(stripos('AEIOU', $c) === FALSE);
  return intval($c, 36);
}

$sedolweight = array(1,3,1,7,3,9);

function checksum($sedol) {
    global $sedolweight;
    $tmp = array_sum(array_map(create_function('$ch, $weight', 'return char2value($ch) * $weight;'),
                               str_split($sedol), $sedolweight)
                    );
    return strval((10 - ($tmp % 10)) % 10);
}

foreach (array('710889',
               'B0YBKJ',
               '406566',
               'B0YBLH',
               '228276',
               'B0YBKL',
               '557910',
               'B0YBKR',
               '585284',
               'B0YBKT') as $sedol)
    echo $sedol, checksum($sedol), "\n";


let primes max =
    let mutable xs = [|2..max|]
    let limit = max |> float |> sqrt |> int
    for x in [|2..limit|] do
        xs <- xs |> Array.except [|x*x..x..max|]
    xs


(define haystack
  '("Zig" "Zag" "Wally" "Ronald" "Bush" "Krusty" "Charlie" "Bush" "Bozo"))

(define index-of
  (lambda (needle hackstack)
    (let ((tail (member needle haystack)))
      (if tail
          (- (length haystack) (length tail))
          (throw 'needle-missing)))))

(define last-index-of
  (lambda (needle hackstack)
    (let ((tail (member needle (reverse haystack))))
      (if tail
          (- (length tail) 1)
          (throw 'needle-missing)))))


put ("apple", "banana", "cranberry" ,"durian", "eggplant", "grape", "banana", "appl", "blackberry") into fruitList

put findInList(fruitList,"banana")  // 2
put findInList(fruitList,"banana", true)  // 7
put findInList(fruitList,"tomato")  // throws an exception

function findInList paramList, paramItem, findLast
	set temp to every offset of paramItem within paramList
	if (number of items in temp = 0)
		Throw InvalidSearch, "Item not found in list"
	end if
	if findLast
		return last item of temp
	else
		return first item of temp
	end if
end findInList


/* Compute SEDOLs; includes check for invalid characters. */
sedol: procedure options (main); /* 3 March 2012 */
   declare alphabet character (36) static initial
      ('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ');
   declare weight (6) fixed static initial (1, 3, 1, 7, 3, 9);
   declare s character (6);
   declare (i, v, k) fixed;

   do while ('1'b);
      get edit (s) (a(6));
      put skip edit (s) (a);
      /* Check for invalid characters: */
      if verify(s, '0123456789BCDFGHJKLMNPQRSTVWXYZ') > 0 then stop;
      v = 0;
      do i = 1 to 6;
         k = index(alphabet, substr(s, i, 1)) - 1;
         v = v + weight(i) * k;
      end;
      k = mod(v, 10);
      v = mod(10 - k, 10);
      put edit (s, v) (x(2), a, f(1)); put edit ('  ') (a);
   end;
end sedol;


USING: bit-arrays io kernel locals math math.functions
math.ranges prettyprint sequences ;
IN: rosetta-code.sieve-of-erato

<PRIVATE

: init-sieve ( n -- seq )   ! Include 0 and 1 for easy indexing.
    1 - <bit-array> dup set-bits ?{ f f } prepend ;

! Given the sieve and a prime starting index, create a range of
! values to mark composite. Start at the square of the prime.
: to-mark ( seq n -- range )
    [ length 1 - ] [ dup dup * ] bi* -rot <range> ;

! Mark multiples of prime n as composite.
: mark-nths ( seq n -- )
    dupd to-mark [ swap [ f ] 2dip set-nth ] with each ;

: next-prime ( index seq -- n ) [ t = ] find-from drop ;

PRIVATE>

:: sieve ( n -- seq )
    n sqrt 2 n init-sieve :> ( limit i! s )
    [ i limit < ]             ! sqrt optimization
    [ s i mark-nths i 1 + s next-prime i! ] while t s indices ;

: sieve-demo ( -- )
    "Primes up to 120 using sieve of Eratosthenes:" print
    120 sieve . ;

MAIN: sieve-demo


var haystack = %w(Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo);

%w(Bush Washington).each { |needle|
    var i = haystack.first_index{|item| item == needle};
    if (i >= 0) {
        say "#{i} #{needle}";
    } else {
        die "#{needle} is not in haystack";
    }
}


define: #haystack -> ('Zig,Zag,Wally,Ronald,Bush,Krusty,Charlie,Bush,Bozo' splitWith: $,).
{'Washington'. 'Bush'} do: [| :needle |
  (haystack indexOf: needle)
    ifNil: [inform: word ; ' is not in the haystack']
    ifNotNilDo: [| :firstIndex lastIndex |
      inform: word ; ' is in the haystack at index ' ; firstIndex printString.
      lastIndex: (haystack lastIndexOf: word).
      lastIndex isNotNil /\ (lastIndex > firstIndex) ifTrue:
        [inform: 'last occurrence of ' ; word ; ' is at index ' ; lastIndex]]].


| haystack |
haystack := 'Zig,Zag,Wally,Ronald,Bush,Krusty,Charlie,Bush,Bozo' subStrings: $,.
{ 'Washington' . 'Bush' } do: [:word |
  |t|

  ((t := haystack indexOf: word) = 0)
          ifTrue: [ ('%1 is not in the haystack' % { word }) displayNl ]
          ifFalse: [
               |l|
               ('%1 is at index %2' % { word . t }) displayNl.
               l := ( (haystack size) - (haystack reverse indexOf: word) + 1 ).
               ( t = l ) ifFalse: [
                   ('last occurence of %1 is at index %2' %  { word . l }) displayNl ]
               ]
].


sedolnum = (c) :
   if ("0" ord <= c ord and c ord <= "9" ord): c number integer.
   else: 10 + c ord - "A" ord.
.

sedol = (str) :
   weight = (1, 3, 1, 7, 3, 9)
   sum = 0
   6 times (i) :
      sum = sum + sedolnum(str(i)) * weight(i)
   .
   (str, (10 - (sum % 10)) % 10) join
.


function Add-SEDOLCheckDigit
    {
    Param ( #  Validate input as six-digit SEDOL number
            [ValidatePattern( "^[0123456789bcdfghjklmnpqrstvwxyz]{6}$" )]
            [parameter ( Mandatory = $True ) ]
            [string]
            $SixDigitSEDOL )

    #  Convert to array of single character strings, using type char as an intermediary
    $SEDOL = [string[]][char[]]$SixDigitSEDOL

    #  Define place weights
    $Weight = @( 1, 3, 1, 7, 3, 9 )

    #  Define character values (implicit in 0-based location within string)
    $Characters = "0123456789abcdefghijklmnopqrstuvwxyz"

    $CheckSum = 0

    #  For each digit, multiply the character value by the weight and add to check sum
    0..5 | ForEach { $CheckSum += $Characters.IndexOf( $SEDOL[$_].ToLower() ) * $Weight[$_] }

    #  Derive the check digit from the partial check sum
    $CheckDigit = ( 10 - $CheckSum % 10 ) % 10

    #  Return concatenated result
    return ( $SixDigitSEDOL + $CheckDigit )
    }

#  Test
$List = @(
    "710889"
    "B0YBKJ"
    "406566"
    "B0YBLH"
    "228276"
    "B0YBKL"
    "557910"
    "B0YBKR"
    "585284"
    "B0YBKT"
    "B00030"
    )

ForEach ( $PartialSEDOL in $List )
    {
    Add-SEDOLCheckDigit -SixDigitSEDOL $PartialSEDOL
    }


BEGIN # find Ruth-Aaron pairs - pairs of consecutive integers where the sum #
      # of the prime factors or divisors are equal                          #
    INT max number = 99 000 000; # max number we will consider #
    # construct a sieve of primes up to max number #
    [ 1 : max number ]BOOL prime;
    prime[ 1 ] := FALSE;
    prime[ 2 ] := TRUE;
    FOR i FROM 3 BY 2 TO UPB prime DO prime[ i ] := TRUE  OD;
    FOR i FROM 4 BY 2 TO UPB prime DO prime[ i ] := FALSE OD;
    FOR i FROM 3 BY 2 TO ENTIER sqrt( UPB prime ) DO
        IF prime[ i ] THEN
            FOR s FROM i * i BY i + i TO UPB prime DO prime[ s ] := FALSE OD
        FI
    OD;
    # construct the sums of prime divisors up to max number #
    [ 1 : max number ]INT ps; FOR n TO max number DO ps[ n ] := 0 OD;
    FOR n TO max number DO
        IF prime[ n ] THEN
            FOR j FROM n BY n TO max number DO ps[ j ] PLUSAB n OD
        FI
    OD;
    INT max count = 30;
    # first max count Ruth-Aaron (divisors) numbers #
    [ 1 : max count ]INT dra;
    INT count    := 0;
    INT prev sum := 0;
    FOR n FROM 2 WHILE count < max count DO
        INT this sum = ps[ n ];
        IF prev sum = this sum THEN
            # found another Ruth-Aaron number #
            count PLUSAB 1;
            IF count <= max count THEN dra[ count ] := n - 1 FI
        FI;
        prev sum := this sum
    OD;
    # first triple #
    INT dra3      := 0;
    INT pprev sum := ps[ 1 ];
    prev sum      := ps[ 2 ];
    FOR n FROM 3 WHILE dra3 = 0 DO
        INT this sum = ps[ n ];
        IF prev sum = this sum THEN
            IF pprev sum = this sum THEN
                # found a Ruth-Aaron triple #
                dra3 := n - 2
            FI
        FI;
        pprev sum := prev sum;
        prev sum  := this sum
    OD;
    # replace ps with the prime factor count #
    INT root max number = ENTIER sqrt( max number );
    FOR n FROM 2 TO root max number DO
        IF prime[ n ] THEN
            INT p := n * n;
            WHILE p < root max number DO
                FOR j FROM p BY p TO max number DO ps[ j ] PLUSAB n OD;
                p TIMESAB n
            OD
        FI
    OD;
    # first max count Ruth-Aaron (factors) numbers #
    [ 1 : max count ]INT fra;
    prev sum := ps[ 1 ];
    count    := 0;
    FOR n FROM 2 WHILE count < 30 DO
        INT this sum = ps[ n ];
        IF prev sum = this sum THEN
            # found another Ruth-Aaron number #
            count PLUSAB 1;
            fra[ count ] := n - 1
        FI;
        prev sum := this sum
    OD;
    # first triple #
    prev sum := 0;
    count    := 0;
    INT fra3 := 0;
    FOR n FROM 2 WHILE fra3 = 0 DO
        INT this sum = ps[ n ];
        IF prev sum = this sum AND pprev sum = this sum THEN
            # found a Ruth-Aaron triple #
            fra3 := n - 2
        FI;
        pprev sum := prev sum;
        prev sum  := this sum
    OD;
    # show the numbers #
    print( ( "The first ", whole( max count, 0 ), " Ruth-Aaron numbers (factors):", newline ) );
    FOR n TO max count DO
        print( ( whole( fra[ n ], - 6 ) ) );
        IF n MOD 10 = 0 THEN print( ( newline ) ) FI
    OD;
    # divisors #
    print( ( "The first ", whole( max count, 0 ), " Ruth-Aaron numbers (divisors):", newline ) );
    FOR n TO max count DO
        print( ( whole( dra[ n ], - 6 ) ) );
        IF n MOD 10 = 0 THEN print( ( newline ) ) FI
    OD;
    # triples #
    print( ( newline, "First Ruth-Aaron triple (factors):  ", whole( fra3, 0 ) ) );
    print( ( newline, "First Ruth-Aaron triple (divisors): ", whole( dra3, 0 ) ) )
END


fun find_index (pred, lst) = let
  fun loop (n, [])    = NONE
    | loop (n, x::xs) = if pred x then SOME n
                                  else loop (n+1, xs)
in
  loop (0, lst)
end;

val haystack = ["Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo"];

app (fn needle =>
       case find_index (fn x => x = needle, haystack) of
            SOME i => print (Int.toString i ^ " " ^ needle ^ "\n")
          | NONE   => print (needle ^ " is not in haystack\n"))
    ["Washington", "Bush"];


let haystack = ["Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo"]
for needle in ["Washington","Bush"] {
  if let index = haystack.indexOf(needle) {
    print("\(index) \(needle)")
  } else {
    print("\(needle) is not in haystack")
  }
}


set haystack {Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo}
foreach needle {Bush Washington} {
    if {[set idx [lsearch -exact $haystack $needle]] == -1} {
        error "$needle does not appear in the haystack"
    } else {
        puts "$needle appears at index $idx in the haystack"
    }
}


Procedure.s SEDOLs(rawstring$)
  Protected i, j, sum, c, m
  For i=1 To Len(rawstring$)
    c=Asc(Mid(rawstring$,i,1))
    Select c
      Case Asc("0") To Asc("9")
        j=Val(Mid(rawstring$,i,1))
      Default
        j=c-Asc("A")
    EndSelect
    Select i
      Case 1, 3, 7:  m=1
      Case 2, 5:     m=3
      Case 4:        m=7
      Default:       m=9
    EndSelect
    sum+j*m
  Next
  sum=(10-(sum%10))%10
  ProcedureReturn rawstring$+Str(sum)
EndProcedure

Define result$, i
Restore Tests
For i=0 To 10
  Read.s  SEDOL$
  result$+SEDOLs(SEDOL$)
  If i%2
    result$+#CRLF$
  ElseIf i<10
    result$+", "
  EndIf
Next
MessageRequester("SEDOLs","Result"+#CRLF$+result$)

DataSection
  Tests:
  Data.s  "710889","B0YBKJ","406566","B0YBLH","228276"
  Data.s  "B0YBKL","557910","B0YBKR","585284","B0YBKT","B00030"
EndDataSection