import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Predicate;

/**
 * Represent a City and it's population.
 * City-Objects do have a natural ordering, they are ordered by their poulation (descending)
 */
class City implements Comparable<City> {
    private final String name;
    private final double population;

    City(String name, double population) {
        this.name = name;
        this.population = population;
    }

    public String getName() {
        return this.name;
    }

    public double getPopulation() {
        return this.population;
    }

    @Override
    public int compareTo(City o) {
        //compare for descending order. for ascending order, swap o and this
        return Double.compare(o.population, this.population);
    }
}

public class SearchListOfRecords {

    public static void main(String[] args) {

        //Array-of-City-Objects-Literal
        City[] datasetArray = {new City("Lagos", 21.),
                new City("Cairo", 15.2),
                new City("Kinshasa-Brazzaville", 11.3),
                new City("Greater Johannesburg", 7.55),
                new City("Mogadishu", 5.85),
                new City("Khartoum-Omdurman", 4.98),
                new City("Dar Es Salaam", 4.7),
                new City("Alexandria", 4.58),
                new City("Abidjan", 4.4),
                new City("Casablanca", 3.98)};

        //Since this is about "collections smarter that arrays", the Array is converted to a List
        List<City> dataset = Arrays.asList(datasetArray);

        //the City-Objects know that they are supposed to be compared by population
        Collections.sort(dataset);

        //Find the first City that matches the given predicate and print it's index in the dataset
        //the Predicate here is given in the form a Java 8 Lambda that returns true if the given name
        //Note that the Predicate is not limited to searching for names. It can operate on anything one can done with
        // and compared about City-Objects
        System.out.println(findIndexByPredicate(dataset, city -> city.getName().equals("Dar Es Salaam")));

        //Find the first City whose population matches the given Predicate (here: population <= 5.) and print it's name
        //here the value is returned an printed by the caller
        System.out.println(findFirstCityByPredicate(dataset, city -> city.getPopulation() <= 5.));

        //Find the first City that matches the given predicate (here: name starts with "A") and
        //apply the given consumer (here: print the city's population)
        //here the caller specifies what to do with the object. This is the most generic solution and could also be used to solve Task 2
        applyConsumerByPredicate(dataset, city -> city.getName().startsWith("A"), city -> System.out.println(city.getPopulation()));

    }

    /**
     * Finds a City by Predicate.
     * The predicate can be anything that can be done or compared about a City-Object.
     *

     * Since the task was to "find the index" it is not possible to use Java 8's stream facilities to solve this.
     * The Predicate is used very explicitly here - this is unusual.
     *
     * @param dataset the data to operate on, assumed to be sorted
     * @param p       the Predicate that wraps the search term.
     * @return the index of the City in the dataset
     */
    public static int findIndexByPredicate(List<City> dataset, Predicate<City> p) {
        for (int i = 0; i < dataset.size(); i++) {
            if (p.test(dataset.get(i)))
                return i;
        }
        return -1;
    }

    /**
     * Finds and returns the name of the first City where the population matches the Population-Predicate.
     * This solutions makes use of Java 8's stream facilities.
     *
     * @param dataset   the data to operate on, assumed to be sorted
     * @param predicate a predicate that specifies the city searched. Can be "any predicate that can be applied to a City"
     * @return the name of the first City in the dataset whose population matches the predicate
     */
    private static String findFirstCityByPredicate(List<City> dataset, Predicate<City> predicate) {
        //turn the List into a Java 8 stream, so it can used in stream-operations
        //filter() by the specified predicate (to the right of this operation, only elements matching the predicate are left in the stream)
        //find the first element (which is "the first city..." from the task)
        //get() the actualy object (this is necessary because it is wrapped in a Java 8 Optional<T>
        //getName() the name and return it.
        return dataset.stream().filter(predicate).findFirst().get().getName();
    }

    /**
     * In specified dataset, find the first City whose name matches the specified predicate, and apply the specified consumer
     *

     * Since this can be solved pretty much like the "find a city by population", this has been varied. The caller specifies what to do with the result.
     * So this method does not return anything, but requiers a "consumer" that processes the result.
     *
     * @param dataset      the data to operate on, assumed to be sorted
     * @param predicate    a predicate that specifies the city searched. Can be "any predicate that can be applied to a City"
     * @param doWithResult a Consumer that specified what to do with the results
     */
    private static void applyConsumerByPredicate(List<City> dataset, Predicate<City> predicate, Consumer<City> doWithResult) {
        //turn the List in to a Java 8 stream in stream-operations
        //filter() by the specified predicate (to the right of this operation, only elements matching the predicate are left in the stream)
        //find the first element (which is "the first city..." from the task)
        // if there is an element found, feed it to the Consumer
        dataset.stream().filter(predicate).findFirst().ifPresent(doWithResult);
    }
}


V haystack = [‘Zig’, ‘Zag’, ‘Wally’, ‘Ronald’, ‘Bush’, ‘Krusty’, ‘Charlie’, ‘Bush’, ‘Bozo’]

L(needle) (‘Washington’, ‘Bush’)
   X.try
      print(haystack.index(needle)‘ ’needle)
   X.catch ValueError
      print(needle‘ is not in haystack’)


sieve2←{
  b←⍵⍴1
  b[⍳2⌊⍵]←0
  2≥⍵:b
  p←{⍵/⍳⍴⍵}∇⌈⍵*0.5
  m←1+⌊(⍵-1+p×p)÷p
  b ⊣ p {b[⍺×⍺+⍳⍵]←0}¨ m
}

primes2←{⍵/⍳⍴⍵}∘sieve2


(function () {
    'use strict';

    // find :: (a -> Bool) -> [a] -> Maybe a
    function find(f, xs) {
        for (var i = 0, lng = xs.length; i < lng; i++) {
            if (f(xs[i])) return xs[i];
        }
        return undefined;
    }

    // findIndex :: (a -> Bool) -> [a] -> Maybe Int
    function findIndex(f, xs) {
        for (var i = 0, lng = xs.length; i < lng; i++) {
            if (f(xs[i])) return i;
        }
        return undefined;
    }

    var lst = [
      { "name": "Lagos",                "population": 21.0  },
      { "name": "Cairo",                "population": 15.2  },
      { "name": "Kinshasa-Brazzaville", "population": 11.3  },
      { "name": "Greater Johannesburg", "population":  7.55 },
      { "name": "Mogadishu",            "population":  5.85 },
      { "name": "Khartoum-Omdurman",    "population":  4.98 },
      { "name": "Dar Es Salaam",        "population":  4.7  },
      { "name": "Alexandria",           "population":  4.58 },
      { "name": "Abidjan",              "population":  4.4  },
      { "name": "Casablanca",           "population":  3.98 }
    ];

    return {
        darEsSalaamIndex: findIndex(function (x) {
            return x.name === 'Dar Es Salaam';
        }, lst),

        firstBelow5M: find(function (x) {
                return x.population < 5;
            }, lst)
            .name,

        firstApop: find(function (x) {
                return x.name.charAt(0) === 'A';
            }, lst)
            .population
    };

})();


(defun index-of-r (e xs i)
   (cond ((endp xs) nil)
         ((equal e (first xs)) i)
         (t (index-of-r e (rest xs) (1+ i)))))

(defun index-of (e xs)
   (index-of-r e xs 0))


DEFINE PTR="CARD"

INT FUNC Search(PTR ARRAY texts INT count CHAR ARRAY text)
  INT i

  FOR i=0 TO count-1
  DO
    IF SCompare(texts(i),text)=0 THEN
      RETURN (i)
    FI
  OD
RETURN (-1)

PROC Test(PTR ARRAY texts INT count CHAR ARRAY text)
  INT index

  index=Search(texts,count,text)
  IF index=-1 THEN
    PrintF("""%S"" is not in haystack.%E",text)
  ELSE
    PrintF("""%S"" is on index %I in haystack.%E",text,index)
  FI
RETURN

PROC Main()
  PTR ARRAY texts(7)

  texts(0)="Monday"
  texts(1)="Tuesday"
  texts(2)="Wednesday"
  texts(3)="Thursday"
  texts(4)="Friday"
  texts(5)="Saturday"
  texts(6)="Sunday"

  Test(texts,7,"Monday")
  Test(texts,7,"Sunday")
  Test(texts,7,"Thursday")
  Test(texts,7,"Weekend")
RETURN


on sieveOfEratosthenes(limit)
    script o
        property numberList : {missing value}
    end script

    repeat with n from 2 to limit
        set end of o's numberList to n
    end repeat
    repeat with n from 2 to (limit ^ 0.5 div 1)
        if (item n of o's numberList is n) then
            repeat with multiple from (n * n) to limit by n
                set item multiple of o's numberList to missing value
            end repeat
        end if
    end repeat

    return o's numberList's numbers
end sieveOfEratosthenes

sieveOfEratosthenes(1000)


using DataFrames

dataset = DataFrame(name=["Lagos", "Cairo", "Kinshasa-Brazzaville", "Greater Johannesburg", "Mogadishu",
                          "Khartoum-Omdurman", "Dar Es Salaam", "Alexandria", "Abidjan", "Casablanca"],
                    population=[21.0, 15.2, 11.3, 7.55, 5.85, 4.98, 4.7, 4.58, 4.4, 3.98])

print("Find the (one-based) index of the first city in the list whose name is \"Dar Es Salaam\": ")
println(findfirst(dataset[:name], "Dar Es Salaam"))
print("Find the name of the first city in this list whose population is less than 5 million: ")
println(dataset[first(find(dataset[:population] .< 5)), :name])
print("Find the population of the first city in this list whose name starts with the letter \"A\": ")
println(dataset[first(find(startswith.(dataset[:name], 'A'))), :population])


// version 1.1.2

class City(val name: String, val pop: Double)

val cities = listOf(
    City("Lagos", 21.0),
    City("Cairo", 15.2),
    City("Kinshasa-Brazzaville", 11.3),
    City("Greater Johannesburg", 7.55),
    City("Mogadishu", 5.85),
    City("Khartoum-Omdurman", 4.98),
    City("Dar Es Salaam", 4.7),
    City("Alexandria", 4.58),
    City("Abidjan", 4.4),
    City("Casablanca", 3.98)
)

fun main(args: Array<String>) {
    val index = cities.indexOfFirst { it.name == "Dar Es Salaam" }
    println("Index of first city whose name is 'Dar Es Salaam'          = $index")
    val name = cities.first { it.pop < 5.0 }.name
    println("Name of first city whose population is less than 5 million = $name")
    val pop = cities.first { it.name[0] == 'A' }.pop
    println("Population of first city whose name starts with 'A'        = $pop")
}


var list:Vector.<String> = Vector.<String>(["Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie", "Bush", "Boz", "Zag"]);
function lowIndex(listToSearch:Vector.<String>, searchString:String):int
{
	var index:int = listToSearch.indexOf(searchString);
	if(index == -1)
		throw new Error("String not found: " + searchString);
	return index;
}

function highIndex(listToSearch:Vector.<String>, searchString:String):int
{
	var index:int = listToSearch.lastIndexOf(searchString);
	if(index == -1)
		throw new Error("String not found: " + searchString);
	return index;
}


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

procedure Test_List_Index is
   Not_In : exception;

   type List is array (Positive range <>) of Unbounded_String;

   function Index (Haystack : List; Needle : String) return Positive is
   begin
      for Index in Haystack'Range loop
         if Haystack (Index) = Needle then
            return Index;
         end if;
      end loop;
      raise Not_In;
   end Index;

      -- Functions to create lists
   function "+" (X, Y : String) return List is
   begin
      return (1 => To_Unbounded_String (X), 2 => To_Unbounded_String (Y));
   end "+";

   function "+" (X : List; Y : String) return List is
   begin
      return X & (1 => To_Unbounded_String (Y));
   end "+";

   Haystack : List := "Zig"+"Zag"+"Wally"+"Ronald"+"Bush"+"Krusty"+"Charlie"+"Bush"+"Bozo";

   procedure Check (Needle : String) is
   begin
      Put (Needle);
      Put_Line ("at" & Positive'Image (Index (Haystack, Needle)));
   exception
      when Not_In => Put_Line (" is not in");
   end Check;
begin
   Check ("Washington");
   Check ("Bush");
end Test_List_Index;


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

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

.equ MAXI,      101

/*********************************/
/* Initialized data              */
/*********************************/
.data
sMessResult:        .asciz "Prime  : @ \n"
szCarriageReturn:   .asciz "\n"

/*********************************/
/* UnInitialized data            */
/*********************************/
.bss
sZoneConv:                  .skip 24
TablePrime:                 .skip   4 * MAXI
/*********************************/
/*  code section                 */
/*********************************/
.text
.global main
main:                               @ entry of program
    ldr r4,iAdrTablePrime           @ address prime table
    mov r0,#2                       @ prime 2
    bl displayPrime
    mov r1,#2
    mov r2,#1
1:                                  @ loop for multiple of 2
    str r2,[r4,r1,lsl #2]           @ mark  multiple of 2
    add r1,#2
    cmp r1,#MAXI                    @ end ?
    ble 1b                          @ no loop
    mov r1,#3                       @ begin indice
    mov r3,#1
2:
    ldr r2,[r4,r1,lsl #2]           @ load table élément
    cmp r2,#1                       @ is prime ?
    beq 4f
    mov r0,r1                       @ yes -> display
    bl displayPrime
    mov r2,r1
3:                                  @ and loop to mark multiples of this prime
    str r3,[r4,r2,lsl #2]
    add r2,r1                       @ add the prime
    cmp r2,#MAXI              @ end ?
    ble 3b                          @ no -> loop
4:
    add r1,#2                       @ other prime in table
    cmp r1,#MAXI              @ end table ?
    ble 2b                          @ no -> loop

100:                                @ standard end of the program
    mov r0, #0                      @ return code
    mov r7, #EXIT                   @ request to exit program
    svc #0                          @ perform the system call
iAdrszCarriageReturn:    .int szCarriageReturn
iAdrsMessResult:         .int sMessResult
iAdrTablePrime:          .int TablePrime

/******************************************************************/
/*      Display prime table elements                                */
/******************************************************************/
/* r0 contains the prime */
displayPrime:
    push {r1,lr}                    @ save registers
    ldr r1,iAdrsZoneConv
    bl conversion10                 @ call décimal conversion
    ldr r0,iAdrsMessResult
    ldr r1,iAdrsZoneConv            @ insert conversion in message
    bl strInsertAtCharInc
    bl affichageMess                @ display message
100:
    pop {r1,lr}
    bx lr
iAdrsZoneConv:                   .int sZoneConv
/***************************************************/
/*      ROUTINES INCLUDE                           */
/***************************************************/
.include "../affichage.inc"


on findFirstRecord (data, condition)
  cnt = data.count
  repeat with i = 1 to cnt
    record = data[i]
    if value(condition) then return [#index:i-1, #record:record]
  end repeat
end


-- Dataset declaration
local cityPops = {
    {name = "Lagos", population = 21.0},
    {name = "Cairo", population = 15.2},
    {name = "Kinshasa-Brazzaville", population = 11.3},
    {name = "Greater Johannesburg", population = 7.55},
    {name = "Mogadishu", population = 5.85},
    {name = "Khartoum-Omdurman", population = 4.98},
    {name = "Dar Es Salaam", population = 4.7},
    {name = "Alexandria", population = 4.58},
    {name = "Abidjan", population = 4.4},
    {name = "Casablanca", population = 3.98}
}

-- Function to search a dataset using a custom match function
function recordSearch (dataset, matchFunction)
    local returnValue
    for index, element in pairs(dataset) do
        returnValue = matchFunction(index, element)
        if returnValue then return returnValue end
    end
    return nil
end

-- Main procedure
local testCases = {
    function (i, e) if e.name == "Dar Es Salaam" then return i - 1 end end,
    function (i, e) if e.population < 5 then return e.name end end,
    function (i, e) if e.name:sub(1, 1) == "A" then return e.population end end
}
for _, func in pairs(testCases) do print(recordSearch(cityPops, func)) end


void
search(list l, text s)
{
    integer i;

    i = 0;
    while (i < ~l) {
        if (l[i] == s) {
            break;
        }
        i += 1;
    }

    o_(s, " is ", i == ~l ? "not in the haystack" : "at " + itoa(i), "\n");
}

integer
main(void)
{
    list l;

    l = l_effect("Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty",
                 "Charlie", "Bush", "Boz", "Zag");
    __ucall(search, 1, 1, l, "Bush", "Washington", "Zag");

    return 0;
}


 FORMAT hay stack := $c("Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo")$;

 FILE needle exception; STRING ref needle;
 associate(needle exception, ref needle);

 PROC index = (FORMAT haystack, REF STRING needle)INT:(
   INT out;
   ref needle := needle;
   getf(needle exception,(haystack, out));
   out
 );

 test:(
   []STRING needles = ("Washington","Bush");
   FOR i TO UPB needles DO
     STRING needle := needles[i];
     on value error(needle exception, (REF FILE f)BOOL: value error);
       printf(($d" "gl$,index(hay stack, needle), needle));
       end on value error;
     value error:
       printf(($g" "gl$,needle, "is not in haystack"));
     end on value error: reset(needle exception)
   OD
 )


sieve: function [upto][
    composites: array.of: inc upto false
    loop 2..to :integer sqrt upto 'x [
        if not? composites\[x][
            loop range.step: x x^2 upto 'c [
                composites\[c]: true
            ]
        ]
    ]
    result: new []
    loop.with:'i composites 'c [
        unless c -> 'result ++ i
    ]
    return result -- [0,1]
]

print sieve 100


#!/bin/ksh

# Search a list of records

#	# Variables:
#
json='{ "name": "Lagos",                "population": 21.0  },
  { "name": "Cairo",                "population": 15.2  },
  { "name": "Kinshasa-Brazzaville", "population": 11.3  },
  { "name": "Greater Johannesburg", "population":  7.55 },
  { "name": "Mogadishu",            "population":  5.85 },
  { "name": "Khartoum-Omdurman",    "population":  4.98 },
  { "name": "Dar Es Salaam",        "population":  4.7  },
  { "name": "Alexandria",           "population":  4.58 },
  { "name": "Abidjan",              "population":  4.4  },
  { "name": "Casablanca",           "population":  3.98 }'

typeset -a African_Metro
integer i=0

typeset -T Metro_Africa_t=(
	typeset -h		'Metro name'		met_name=''
	typeset -E3 -h	'Metro population'	met_pop

	function init_metro {
		typeset name ; name="$1"
		typeset pop ; typeset -E3 pop=$2

		_.met_name=${name}
		_.met_pop=${pop}
	}

	function prt_name {
		print "${_.met_name}"
	}

	function prt_pop {
		print "${_.met_pop}"
	}
)

#	# Functions:
#

#	# Function _findcityindex(arr, name) - return array index of citry named "name"
#
function _findcityindex {
	typeset _arr ; nameref _arr="$1"
	typeset _name ; _name="$2"
	typeset _i ; integer _i

	for ((_i=0; _i<${#_arr[*]}; _i++)); do
		[[ ${_name} == $(_arr[_i].prt_name) ]] && echo ${_i} && return 0
	done

	echo "-1"
	return 1
}

#	# Function _findcitynamepop(arr, pop, xx) - find 1st city name pop $3 of $2
#
function _findcitynamepop {
	typeset _arr ; nameref _arr="$1"
	typeset _pop ; typeset -E3 _pop=$2
	typeset _comp ; _comp="$3"
	typeset _i ; integer _i

	for ((_i=0; _i<${#_arr[*]}; _i++)); do
		case ${_comp} in
		gt)
			[[ $(_arr[_i].prt_pop) -gt ${_pop} ]] && _arr[_i].prt_name && return 0 ;;
		lt)
			[[ $(_arr[_i].prt_pop) -lt ${_pop} ]] && _arr[_i].prt_name && return 0 ;;
		esac
	done

	echo "DNE"
	return 1
}

#	# Function _findcitypopname(arr, pat) - find pop of first city starting w/ pat
#
function _findcitypopname {
	typeset _arr ; nameref _arr="$1"
	typeset _pat ; _pat="$2"
	typeset _i ; integer _i

	for ((_i=0; _i<${#_arr[*]}; _i++)); do
		[[ $(_arr[_i].prt_name) == ${_pat}* ]] && _arr[_i].prt_pop && return 0
	done

	echo "-1"
	return 1
}

 ######
# main #
 ######

#	# An indexed array of Type variable (objects)
#
echo "${json}" | while read; do
	metro="${REPLY#*\"name\"\:\ }" ; metro="${metro%%\,*}" ;  metro="${metro//\"/}"
	population="${REPLY#*\"population\"\:\ }" ; population=${population%+(\ )\}*(\,)}

	Metro_Africa_t African_Metro[i]
	African_Metro[i++].init_metro "${metro}" ${population}
done

_findcityindex African_Metro "Dar Es Salaam"
_findcitynamepop African_Metro 5.0 lt
_findcitypopname African_Metro "A"


rec := [table(["name"="Lagos","population"=21.0]),
      table(["name"="Cairo","population"=15.2]),
      table(["name"="Kinshasa-Brazzaville","population"=11.3]),
      table(["name"="Greater Johannesburg","population"=7.55]),
      table(["name"="Mogadishu","population"=5.85]),
      table(["name"="Khartoum-Omdurman","population"=4.98]),
      table(["name"="Dar Es Salaam","population"=4.7  ]),
      table(["name"="Alexandria","population"=4.58]),
      table(["name"="Abidjan","population"=4.4]),
      table(["name"="Casablanca","population"=3.98])]:

searchRec := proc(rec, pred, operation)
	local i:
	for i to numelems(rec) do
		if pred(rec[i]) then
			return operation(rec[i],i):
		fi:
	od:
end proc:
searchRec(rec, x->x["name"] = "Dar Es Salaam", (x,i)->print(i-1)): # minus 1 since Maple is 1-indexed
searchRec(rec, x->x["population"]<5, (x,i)->print(x["name"])):
searchRec(rec, x->x["name"][1] = "A", (x,i)->print(x["population"])):


data = Dataset[{
  <|"name" -> "Lagos", "population" -> 21.|>,
  <|"name" -> "Cairo", "population" -> 15.2|>,
  <|"name" -> "Kinshasa-Brazzaville", "population" -> 11.3|>,
  <|"name" -> "Greater Johannesburg", "population" -> 7.55|>,
  <|"name" -> "Mogadishu", "population" -> 5.85|>,
  <|"name" -> "Khartoum-Omdurman", "population" -> 4.98|>,
  <|"name" -> "Dar Es Salaam", "population" -> 4.7|>,
  <|"name" -> "Alexandria", "population" -> 4.58|>,
  <|"name" -> "Abidjan", "population" -> 4.4|>,
  <|"name" -> "Casablanca", "population" -> 3.98|>
}]
data[Position["Dar Es Salaam"], "name"][1, 1] - 1
data[Select[#population < 5 &]][1, "name"]
data[Select[StringMatchQ[#name, "A*"] &]][1, "population"]


template findIt(data, pred: untyped): int =
  ## Return the index of the first element in "data" satisfying
  ## the predicate "pred" or -1 if no such element is found.
  var result = -1
  for i, it {.inject.} in data.pairs:
    if pred:
      result = i
      break
  result

when isMainModule:

  import strutils

  type City = tuple[name: string; population: float]

  const Cities: seq[City] = @[("Lagos", 21.0),
                              ("Cairo", 15.2),
                              ("Kinshasa-Brazzaville", 11.3),
                              ("Greater Johannesburg", 7.55),
                              ("Mogadishu", 5.85),
                              ("Khartoum-Omdurman", 4.98),
                              ("Dar Es Salaam", 4.7),
                              ("Alexandria", 4.58),
                              ("Abidjan", 4.4),
                              ("Casablanca", 3.98)]

  echo "Index of the first city whose name is “Dar Es Salaam”: ",
      Cities.findIt(it.name == "Dar Es Salaam")

  let idx1 = Cities.findIt(it.population < 5)
  echo "Name of the first city whose population is less than 5 million: ",
      if idx1 == -1: "<none>" else: Cities[idx1].name

  let idx2 = Cities.findIt(it.name.startsWith("A"))
  echo "Population of the first city whose name starts with the letter “A”: ",
      if idx2 == -1: "<none>" else: $Cities[idx2].population


#load "str.cma"

(* We are going to use literally a list of records as said in the title of the
 * task. *)
(* First: Definition of the record type. *)
type city = {
  name : string;
  population : float
}

(* Second: The actual list of records containing the data. *)
let cities = [
  { name = "Lagos";                population = 21.0  };
  { name = "Cairo";                population = 15.2  };
  { name = "Kinshasa-Brazzaville"; population = 11.3  };
  { name = "Greater Johannesburg"; population =  7.55 };
  { name = "Mogadishu";            population =  5.85 };
  { name = "Khartoum-Omdurman";    population =  4.98 };
  { name = "Dar Es Salaam";        population =  4.7  };
  { name = "Alexandria";           population =  4.58 };
  { name = "Abidjan";              population =  4.4  };
  { name = "Casablanca";           population =  3.98 }
]

(* I can't find in the standard library any function in module List that returns
 * an index. Well, never mind, I make my own... *)
let find_index pred =
  let rec doloop i = function
    | [] -> raise Not_found
    | x :: xs -> if pred x then i else doloop (i + 1) xs
  in
  doloop 0

(* List.find returns the first element that satisfies the predicate.
 * List.filter or List.find_all would return *all* the elements that satisfy the
 * predicate. *)
let get_first pred = List.find pred

(* Simulate the 'startswith' function found in other languages. *)
let startswith sub s =
  Str.string_match (Str.regexp sub) s 0

let () =
  (* We use a typical dot notation to access the record fields. *)
  find_index (fun c -> c.name = "Dar Es Salaam") cities
  |> print_int
  |> print_newline;

  (get_first (fun c -> c.population < 5.0) cities).name
  |> print_endline;

  (get_first (fun c -> startswith "A" c.name) cities).population
  |> print_float
  |> print_newline;


haystack: [Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo]

loop [Bush Washington] 'needle [
    i: index haystack needle

    if? empty? i    -> panic ~"|needle| is not in haystack"
    else            -> print [i needle]
]


haystack = Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo
needle = bush, washington
Loop, Parse, needle, `,
{
  If InStr(haystack, A_LoopField)
    MsgBox, % A_LoopField
  Else
    MsgBox % A_LoopField . " not in haystack"
}


MsgBox % "12345678901234567890`n" Sieve(20)

Sieve(n) { ; Sieve of Eratosthenes => string of 0|1 chars, 1 at position k: k is prime
   Static zero := 48, one := 49 ; Asc("0"), Asc("1")
   VarSetCapacity(S,n,one)
   NumPut(zero,S,0,"char")
   i := 2
   Loop % sqrt(n)-1 {
      If (NumGet(S,i-1,"char") = one)
         Loop % n//i
            If (A_Index > 1)
               NumPut(zero,S,A_Index*i-1,"char")
      i += 1+(i>2)
   }
   Return S
}


use feature 'say';
use List::Util qw(first);

my @cities = (
  { name => 'Lagos',                population => 21.0  },
  { name => 'Cairo',                population => 15.2  },
  { name => 'Kinshasa-Brazzaville', population => 11.3  },
  { name => 'Greater Johannesburg', population =>  7.55 },
  { name => 'Mogadishu',            population =>  5.85 },
  { name => 'Khartoum-Omdurman',    population =>  4.98 },
  { name => 'Dar Es Salaam',        population =>  4.7  },
  { name => 'Alexandria',           population =>  4.58 },
  { name => 'Abidjan',              population =>  4.4  },
  { name => 'Casablanca',           population =>  3.98 },
);

my $index1 = first { $cities[$_]{name} eq 'Dar Es Salaam' } 0..$#cities;
say $index1;

my $record2 = first { $_->{population} < 5 } @cities;
say $record2->{name};

my $record3 = first { $_->{name} =~ /^A/ } @cities;
say $record3->{population};


constant CITY_NAME = 1, POPULATION = 2
constant municipalities = {{"Lagos",21},
                           {"Cairo",15.2},
                           {"Kinshasa-Brazzaville",11.3},
                           {"Greater Johannesburg",7.55},
                           {"Mogadishu",5.85},
                           {"Khartoum-Omdurman",4.98},
                           {"Dar Es Salaam",4.7},
                           {"Alexandria",4.58},
                           {"Abidjan",4.4},
                           {"Casablanca",3.98}}

function searchfor(sequence s, integer rid, object user_data, bool return_index=false)
    for i=1 to length(s) do
        if rid(s[i],user_data) then
            return iff(return_index?i:s[i])
        end if
    end for
    return 0 -- not found
end function

function city_named(sequence si, string city_name)
    return si[CITY_NAME]==city_name
end function

?searchfor(municipalities,city_named,"Dar Es Salaam",true)

function smaller_than(sequence si, atom population)
    return si[POPULATION]<population
end function

?searchfor(municipalities,smaller_than,5)[CITY_NAME]

function starts_with(sequence si, integer ch)
    return si[CITY_NAME][1]=ch
end function

?searchfor(municipalities,starts_with,'A')[POPULATION]


#! /usr/bin/awk -f
BEGIN {
    # create the array, using the word as index...
    words="Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo";
    split(words, haystack_byorder, " ");
    j=0;
    for(idx in haystack_byorder) {
	haystack[haystack_byorder[idx]] = j;
	j++;
    }
    # now check for needle (we know it is there, so no "else")...
    if ( "Bush" in haystack ) {
	print "Bush is at " haystack["Bush"];
    }
    # check for unexisting needle
    if ( "Washington" in haystack ) {
	print "impossible";
    } else {
	print "Washington is not here";
    }
}


DATA foo, bar, baz, quux, quuux, quuuux, bazola, ztesch, foo, bar, thud, grunt
DATA foo, bar, bletch, foo, bar, fum, fred, jim, sheila, barney, flarp, zxc
DATA spqr, wombat, shme, foo, bar, baz, bongo, spam, eggs, snork, foo, bar
DATA zot, blarg, wibble, toto, titi, tata, tutu, pippo, pluto, paperino, aap
DATA noot, mies, oogle, foogle, boogle, zork, gork, bork

DIM haystack(54) AS STRING
DIM needle AS STRING, found AS INTEGER, L0 AS INTEGER

FOR L0 = 0 TO 54
    READ haystack(L0)
NEXT

DO
    INPUT "Word to search for? (Leave blank to exit) ", needle
    IF needle <> "" THEN
        FOR L0 = 0 TO UBOUND(haystack)
            IF UCASE$(haystack(L0)) = UCASE$(needle) THEN
                found = 1
                PRINT "Found "; CHR$(34); needle; CHR$(34); " at index "; LTRIM$(STR$(L0))
            END IF
        NEXT
        IF found < 1 THEN
            PRINT CHR$(34); needle; CHR$(34); " not found"
        END IF
    ELSE
        EXIT DO
    END IF
LOOP


#include <Array.au3>
$M = InputBox("Integer", "Enter biggest Integer")
Global $a[$M], $r[$M], $c = 1
For $i = 2 To $M -1
	If Not $a[$i] Then
		$r[$c] = $i
		$c += 1
		For $k = $i To $M -1 Step $i
			$a[$k] = True
		Next
	EndIf
Next
$r[0] = $c - 1
ReDim $r[$c]
_ArrayDisplay($r)


<?php

$data_array = [
  ['name' => 'Lagos', 'population' => 21.0],
  ['name' => 'Cairo', 'population' => 15.2],
  ['name' => 'Kinshasa-Brazzaville', 'population' => 11.3],
  ['name' => 'Greater Johannesburg', 'population' => 7.55],
  ['name' => 'Mogadishu', 'population' => 5.85],
  ['name' => 'Khartoum-Omdurman', 'population' => 4.98],
  ['name' => 'Dar Es Salaam', 'population' => 4.7],
  ['name' => 'Alexandria', 'population' => 4.58],
  ['name' => 'Abidjan', 'population' => 4.4],
  ['name' => 'Casablanca', 'population' => 3.98],
];
$found=0;
$search_name = 'Dar Es Salaam';
echo "Find the (zero-based) index of the first city in the list whose name is \"$search_name\" - 6";

$index = array_search($search_name, array_column($data_array, 'name'));
$population = $data_array[$index]['population'];
echo "\nAnswer 1: Index: [$index] Population for $search_name is $population Million\n";

$search_val = 5;
echo "\nFind the name of the first city in this list whose population is less than $search_val million - Khartoum-Omdurman";
foreach ($data_array as $index => $row) {
  if ($row['population'] < $search_val) {
    $name = $row['name'];
    echo "\nAnswer 2: Index [$index] Population for $row[name] is $row[population] Million\n";
    break;
  }
}

$search_term = 'A';
echo "\n\nFind the population of the first city in this list whose name starts with the letter \"$search_term\" - 4.58";
foreach ($data_array as $index => $row) {
  if (strpos($row['name'], $search_term) === 0) {
    echo "\nAnswer 3: Index: [$index] Population for $row[name] is $row[population] Million\n";
    break;
  }
}

echo "\nDone...";

Output:
Find the (zero-based) index of the first city in the list whose name is "Dar Es Salaam" - 6
Answer 1: Index: [6] Population for Dar Es Salaam is 4.7 Million

Find the name of the first city in this list whose population is less than 5 million - Khartoum-Omdurman
Answer 2: Index [5] Population for Khartoum-Omdurman is 4.98 Million

Find the population of the first city in this list whose name starts with the letter "A" - 4.58
Answer 3: Index: [7] Population for Alexandria is 4.58 Million

Done...


@echo off
setlocal enabledelayedexpansion

	%==Sample list==%
set "data=foo, bar, baz, quux, quuux, quuuux, bazola, ztesch, foo, bar, thud, grunt"
set "data=%data% foo, bar, bletch, foo, bar, fum, fred, jim, sheila, barney, flarp, zxc"
set "data=%data% spqr, wombat, shme, foo, bar, baz, bongo, spam, eggs, snork, foo, bar"
set "data=%data% zot, blarg, wibble, toto, titi, tata, tutu, pippo, pluto, paperino, aap"
set "data=%data% noot, mies, oogle, foogle, boogle, zork, gork, bork"

	%==Sample "needles" [whitespace is the delimiter]==%
set "needles=foo bar baz jim bong"

	%==Counting and Seperating each Data==%
set datalen=0
for %%. in (!data!) do (
	set /a datalen+=1
	set data!datalen!=%%.
)
	%==Do the search==%
for %%A in (!needles!) do (
	set "first="
	set "last="
	set "found=0"
	for /l %%B in (1,1,%datalen%) do (
		if "!data%%B!" == "%%A" (
			set /a found+=1
			if !found! equ 1 set first=%%B
			set last=%%B
		)
	)

	if !found! equ 0 echo."%%A": Not found.
	if !found! equ 1 echo."%%A": Found once in index [!first!].
	if !found! gtr 1 echo."%%A": Found !found! times. First instance:[!first!] Last instance:[!last!].

)
	%==We are done==%
echo.
pause


(scl 2)

(de *Data
   ("Lagos"                21.0)
   ("Cairo"                15.2)
   ("Kinshasa-Brazzaville" 11.3)
   ("Greater Johannesburg" 7.55)
   ("Mogadishu"            5.85)
   ("Khartoum-Omdurman"    4.98)
   ("Dar Es Salaam"        4.7)
   ("Alexandria"           4.58)
   ("Abidjan"              4.4)
   ("Casablanca"           3.98) )

(test 6
   (dec (index (assoc "Dar Es Salaam" *Data) *Data)) )

(test "Khartoum-Omdurman"
   (car (find '((L) (> 5.0 (cadr L))) *Data)) )

(test 4.58
   (cadr (find '((L) (pre? "A" (car L))) *Data)) )


$jsonData = @'
[
    { "Name": "Lagos",                "Population": 21.0  },
    { "Name": "Cairo",                "Population": 15.2  },
    { "Name": "Kinshasa-Brazzaville", "Population": 11.3  },
    { "Name": "Greater Johannesburg", "Population":  7.55 },
    { "Name": "Mogadishu",            "Population":  5.85 },
    { "Name": "Khartoum-Omdurman",    "Population":  4.98 },
    { "Name": "Dar Es Salaam",        "Population":  4.7  },
    { "Name": "Alexandria",           "Population":  4.58 },
    { "Name": "Abidjan",              "Population":  4.4  },
    { "Name": "Casablanca",           "Population":  3.98 }
]
'@

$cities = $jsonData | ConvertFrom-JSON


cities = [
    { "name": "Lagos",                "population": 21.0  },
    { "name": "Cairo",                "population": 15.2  },
    { "name": "Kinshasa-Brazzaville", "population": 11.3  },
    { "name": "Greater Johannesburg", "population":  7.55 },
    { "name": "Mogadishu",            "population":  5.85 },
    { "name": "Khartoum-Omdurman",    "population":  4.98 },
    { "name": "Dar Es Salaam",        "population":  4.7  },
    { "name": "Alexandria",           "population":  4.58 },
    { "name": "Abidjan",              "population":  4.4  },
    { "name": "Casablanca",           "population":  3.98 }
]

def first(query):
    return next(query, None)

print(
    first(index for index, city in enumerate(cities)
        if city['name'] == "Dar Es Salaam"),
    first(city['name'] for city in cities if city['population'] < 5),
    first(city['population'] for city in cities if city['name'][0] == 'A'),
    sep='\n')


      DIM haystack$(27)
      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% = DIM(haystack$(), 1)

      FOR index% = 0 TO maxindex%
        IF needle$ = haystack$(index%) EXIT FOR
      NEXT
      IF index% <= maxindex% THEN
        PRINT "First found at index "; index%
        FOR last% = maxindex% TO 0 STEP -1
          IF needle$ = haystack$(last%) EXIT FOR
        NEXT
        IF last%<>index% PRINT "Last found at index "; last%
      ELSE
        ERROR 100, "Not found"
      ENDIF


list ← ⟨"Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie", "Bush", "Boz", "Zag"⟩

IndexOf ← {
  ("Error: '" ∾𝕩∾ "' Not found in list") ! (≠𝕨)≠ind ← ⊑𝕨⊐⋈𝕩
  ind
}

•Show list ⊐ "Wally"‿"Hi" # intended
•Show list IndexOf "Wally"
list IndexOf "Hi"


(     return the largest index to a needle that has multiple
      occurrences in the haystack and print the needle
  : ?list
& (   !list:? haystack [?index ?
    & out$("The word 'haystack' occurs at 1-based index" !index)
  | out$"The word 'haystack' does not occur"
  )
& (   !list
    : ? %@?needle ? !needle ?
    : ( ? !needle [?index (?&~)
      |   ?
        &   out
          $ ( str
            $ ( "The word '"
                !needle
                "' occurs more than once. The last 1-based index is "
                !index
              )
            )
      )
  | out$"No word occurs more than once."
  )
);


DIM n AS Integer, k AS Integer, limit AS Integer

INPUT "Enter number to search to: "; limit
DIM flags(limit) AS Integer

FOR n = 2 TO SQR(limit)
    IF flags(n) = 0 THEN
        FOR k = n*n TO limit STEP n
            flags(k) = 1
        NEXT k
    END IF
NEXT n

' Display the primes
FOR n = 2 TO limit
    IF flags(n) = 0 THEN PRINT n; ", ";
NEXT n


#lang racket

(define (findf/pos proc lst)
  (let loop ([lst lst] [pos 0])
    (cond
      [(null? lst) #f]
      [(proc (car lst)) pos]
      [else (loop (cdr lst) (add1 pos))])))


my @cities =
  { name => 'Lagos',                population => 21.0  },
  { name => 'Cairo',                population => 15.2  },
  { name => 'Kinshasa-Brazzaville', population => 11.3  },
  { name => 'Greater Johannesburg', population =>  7.55 },
  { name => 'Mogadishu',            population =>  5.85 },
  { name => 'Khartoum-Omdurman',    population =>  4.98 },
  { name => 'Dar Es Salaam',        population =>  4.7  },
  { name => 'Alexandria',           population =>  4.58 },
  { name => 'Abidjan',              population =>  4.4  },
  { name => 'Casablanca',           population =>  3.98 },
;

say @cities.first(*<name> eq 'Dar Es Salaam', :k);
say @cities.first(*<population> < 5).<name>;
say @cities.first(*<name>.match: /^A/).<population>;


/*REXX program (when using criteria) locates values (indices)  from an associate array. */
$="Lagos=21,  Cairo=15.2,  Kinshasa-Brazzaville=11.3, Greater Johannesburg=7.55, Mogadishu=5.85,",
  "Khartoum-Omdurman=4.98, Dar Es Salaam=4.7,  Alexandria=4.58,   Abidjan=4.4,  Casablanca=3.98"
@.= '(city not found)';    city.= "(no city)"       /*city search results for not found.*/
                                                    /* [↓]  construct associate arrays. */
    do #=0  while $\='';  parse var $ c '=' p "," $;  c=space(c);  parse var c a 2;  @.c=#
    city.#=c;  pop.#=p;  pop.c=#;  if @.[email protected].  then @.a=c;  /*assign city, pop, indices.*/
    end   /*#*/                                     /* [↑]  city array starts at 0 index*/
                        /*▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ task 1:  show the  INDEX  of a city.*/
town= 'Dar Es Salaam'                               /*the name of a city for the search.*/
say 'The city of ' town " has an index of: " @.town /*show (zero─based) index of a city.*/
say                     /*▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ task 2:  show 1st city whose pop<5 M*/
many=5                                              /*size of a city's pop in millions. */
      do k=0  for #  until pop.k<many; end          /*find a city's pop from an index.  */
say '1st city that has a population less than '     many     " million is: "    city.k
say                     /*▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ task 3:  show 1st city with A* name.*/
c1= 'A'                                             /*1st character of a city for search*/
say '1st city that starts with the letter' c1 "is: " @.c1 /*stick a fork in it, all done*/


blsq ) {"Zig" "Zag" "Wally" "Bush" "Ronald" "Bush"}"Bush"Fi
3


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

const char *haystack[] = {
  "Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie",
  "Bush", "Boz", "Zag", NULL
};

int search_needle(const char *needle, const char **hs)
{
  int i = 0;
  while( hs[i] != NULL ) {
    if ( strcmp(hs[i], needle) == 0 ) return i;
    i++;
  }
  return -1;
}

int search_last_needle(const char *needle, const char **hs)
{
  int i, last=0;
  i = last = search_needle(needle, hs);
  if ( last < 0 ) return -1;
  while( hs[++i] != NULL ) {
    if ( strcmp(needle, hs[i]) == 0 ) {
      last = i;
    }
  }
  return last;
}

int main()
{
  printf("Bush is at %d\n", search_needle("Bush", haystack));
  if ( search_needle("Washington", haystack) == -1 )
    printf("Washington is not in the haystack\n");
  printf("First index for Zag: %d\n", search_needle("Zag", haystack));
  printf("Last index for Zag: %d\n", search_last_needle("Zag", haystack));
  return 0;
}


# Project : Search a list of records

cities = [[:name = "Lagos",:population = 21.0 ],
             [:name = "Cairo",:population =  15.2 ],
             [:name = "Kinshasa-Brazzaville",:population =  11.3 ],
             [:name = "Greater Johannesburg",:population =  7.55],
             [:name = "Mogadishu",:population =  5.85],
             [:name = "Khartoum-Omdurman",:population =  4.98],
             [:name = "Dar Es Salaam",:population =  4.7 ],
             [:name = "Alexandria",:population =  4.58],
             [:name = "Abidjan",:population =  4.4 ],
             [:name = "Casablanca",:population =  3.98]]

for n = 1 to len(cities)
     if cities[n][:name] = "Dar Es Salaam"
        see n-1 + nl
     ok
next

for n = 1 to len(cities)
     if cities[n][:population] < 5.00
        see cities[n][:name] + nl
        exit
     ok
next

for n = 1 to len(cities)
     if left(cities[n][:name],1) = "A"
        see cities[n][:population] + nl
        exit
     ok
next


cities = [
    {name: "Lagos", population: 21},
    {name: "Cairo", population: 15.2},
    {name: "Kinshasa-Brazzaville", population: 11.3},
    {name: "Greater Johannesburg", population: 7.55},
    {name: "Mogadishu", population: 5.85},
    {name: "Khartoum-Omdurman", population: 4.98},
    {name: "Dar Es Salaam", population: 4.7},
    {name: "Alexandria", population: 4.58},
    {name: "Abidjan", population: 4.4},
    {name: "Casablanca", population: 3.98},
]

puts cities.index{|city| city[:name] == "Dar Es Salaam"}      # => 6
puts cities.find {|city| city[:population] < 5.0}[:name]      # => Khartoum-Omdurman
puts cities.find {|city| city[:name][0] == "A"}[:population]  # => 4.58


struct City {
    name: &'static str,
    population: f64,
}

fn main() {
    let cities = [
        City {
            name: "Lagos",
            population: 21.0,
        },
        City {
            name: "Cairo",
            population: 15.2,
        },
        City {
            name: "Kinshasa-Brazzaville",
            population: 11.3,
        },
        City {
            name: "Greater Johannesburg",
            population: 7.55,
        },
        City {
            name: "Mogadishu",
            population: 5.85,
        },
        City {
            name: "Khartoum-Omdurman",
            population: 4.98,
        },
        City {
            name: "Dar Es Salaam",
            population: 4.7,
        },
        City {
            name: "Alexandria",
            population: 4.58,
        },
        City {
            name: "Abidjan",
            population: 4.4,
        },
        City {
            name: "Casablanca",
            population: 3.98,
        },
    ];

    println!(
        "{:?}",
        cities.iter().position(|city| city.name == "Dar Es Salaam")
    );
    println!(
        "{:?}",
        cities
            .iter()
            .find(|city| city.population < 5.0)
            .map(|city| city.name)
    );
    println!(
        "{:?}",
        cities
            .iter()
            .find(|city| city.name.starts_with('A'))
            .map(|city| city.population)
    );
}


using System;
using System.Collections.Generic;

class Program {
    static void Main(string[] args) {
        List<string> haystack = new List<string>() { "Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie", "Bush", "Bozo" };

        foreach (string needle in new string[] { "Washington", "Bush" }) {
            int index = haystack.IndexOf(needle);

            if (index < 0) Console.WriteLine("{0} is not in haystack",needle);
            else Console.WriteLine("{0} {1}",index,needle);
        }
    }
}


#include <string>
#include <algorithm>
#include <iterator>
#include <cstddef>
#include <exception>
#include <iostream>

// an exception to throw (actually, throwing an exception in this case is generally considered bad style, but it's part of the task)
class not_found: public std::exception
{
public:
  not_found(std::string const& s): text(s + " not found") {}
  char const* what() const throw() { return text.c_str(); }
  ~not_found() throw() {}
private:
  std::string text;
};

// needle search function, C-style interface version using standard library
std::size_t get_index(std::string* haystack, int haystack_size, std::string needle)
{
  std::size_t index = std::find(haystack, haystack+haystack_size, needle) - haystack;
  if (index == haystack_size)
    throw not_found(needle);
  else
    return index;
}

// needle search function, completely generic style, needs forward iterators
// (works with any container, but inefficient if not random-access-iterator)
template<typename FwdIter>
 typename std::iterator_traits<FwdIter>::difference_type fwd_get_index(FwdIter first, FwdIter last, std::string needle)
{
  FwdIter elem = std::find(first, last, needle);
  if (elem == last)
    throw not_found(needle);
  else
    return std::distance(first, elem);
}

// needle search function, implemented directly, needs only input iterator, works efficiently with all sequences
template<typename InIter>
 typename std::iterator_traits<InIter>::difference_type generic_get_index(InIter first, InIter last, std::string needle)
{
  typename std::iterator_traits<InIter>::difference_type index = 0;
  while (first != last && *first != needle)
  {
    ++index;
    ++first;
  }
  if (first == last)
    throw not_found(needle);
  else
    return index;
}

// ----------------------------------------------------------------------------------------------------------------------------------

// a sample haystack (content copied from Haskell example)
std::string haystack[] = { "Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie", "Bush", "Bozo" };

// some useful helper functions
template<typename T, std::size_t sz> T* begin(T (&array)[sz]) { return array; }
template<typename T, std::size_t sz> T* end(T (&array)[sz]) { return array + sz; }
template<typename T, std::size_t sz> std::size_t size(T (&array)[sz]) { return sz; }

// test function searching a given needle with each of the methods
void test(std::string const& needle)
{
  std::cout << "-- C style interface --\n";
  try
  {
    std::size_t index = get_index(haystack, size(haystack), needle);
    std::cout << needle << " found at index " << index << "\n";
  }
  catch(std::exception& exc) // better catch standard exceptions as well; me might e.g. run out of memory
  {
    std::cout << exc.what() << "\n";
  }

  std::cout << "-- generic interface, first version --\n";
  try
  {
    std::size_t index = fwd_get_index(begin(haystack), end(haystack), needle);
    std::cout << needle << " found at index " << index << "\n";
  }
  catch(std::exception& exc) // better catch standard exceptions as well; me might e.g. run out of memory
  {
    std::cout << exc.what() << "\n";
  }

  std::cout << "-- generic interface, second version --\n";
  try
  {
    std::size_t index = generic_get_index(begin(haystack), end(haystack), needle);
    std::cout << needle << " found at index " << index << "\n";
  }
  catch(std::exception& exc) // better catch standard exceptions as well; me might e.g. run out of memory
  {
    std::cout << exc.what() << "\n";
  }
}

int main()
{
  std::cout << "\n=== Word which only occurs once ===\n";
  test("Wally");
  std::cout << "\n=== Word occuring multiple times ===\n";
  test("Bush");
  std::cout << "\n=== Word not occuring at all ===\n";
  test("Goofy");
}


:: Sieve of Eratosthenes for Rosetta Code - PG
@echo off
setlocal ENABLEDELAYEDEXPANSION
setlocal ENABLEEXTENSIONS
rem echo on
set /p n=limit:
rem set n=100
for /L %%i in (1,1,%n%) do set crible.%%i=1
for /L %%i in (2,1,%n%) do (
  if !crible.%%i! EQU 1 (
    set /A w = %%i * 2
    for /L %%j in (!w!,%%i,%n%) do (
	  set crible.%%j=0
	)
  )
)
for /L %%i in (2,1,%n%) do (
  if !crible.%%i! EQU 1 echo %%i
)
pause


object SearchListOfRecords extends App {
  val cities = Vector(
    City("Lagos", 21.0e6),
    City("Cairo", 15.2e6),
    City("Kinshasa-Brazzaville", 11.3e6),
    City("Greater Johannesburg", 7.55e6),
    City("Mogadishu", 5.85e6),
    City("Khartoum-Omdurman", 4.98e6),
    City("Dar Es Salaam", 4.7e6),
    City("Alexandria", 4.58e6),
    City("Abidjan", 4.4e6),
    City("Casablanca", 3.98e6)
  )

  def index = cities.indexWhere((_: City).name == "Dar Es Salaam")

  def name = cities.find(_.pop < 5.0e6).map(_.name)

  def pop = cities.find(_.name(0) == 'A').map(_.pop)

  case class City(name: String, pop: Double)

  println(
    s"Index of first city whose name is 'Dar Es Salaam'          = $index\n" +
      s"Name of first city whose population is less than 5 million = ${name.get}\n" +
      f"Population of first city whose name starts with 'A'        = ${pop.get}%,.0f")

}


(import (scheme base)
        (scheme char)
        (scheme write)
        (srfi 1)    ; lists
        (srfi 132)) ; sorting

(define-record-type <places> ; compound data type is a record with two fields
                    (make-place name population)
                    place?
                    (name place-name)
                    (population place-population))

(define *items*
  (list-sort ; sort by decreasing population
    (lambda (r1 r2) (> (place-population r1)
                       (place-population r2)))
    (list (make-place "Lagos" 21.0)
          (make-place "Cairo" 15.2)
          (make-place "Kinshasa-Brazzaville" 11.3)
          (make-place "Greater Johannesburg" 7.55)
          (make-place "Mogadishu" 5.85)
          (make-place "Khartoum-Omdurman" 4.98)
          (make-place "Dar Es Salaam" 4.7)
          (make-place "Alexandria" 4.58)
          (make-place "Abidjan" 4.4)
          (make-place "Casablanca" 3.98))))

;; Find the (zero-based) index of the first city in the list
;; whose name is "Dar Es Salaam"
(display "Test 1: ")
(display (list-index (lambda (item)
                       (string=? "Dar Es Salaam" (place-name item)))
                     *items*))
(newline)

;; Find the name of the first city in this list
;; whose population is less than 5 million
(display "Test 2: ")
(display (place-name
           (find (lambda (item)
                   (< (place-population item) 5.0))
                 *items*)))
(newline)

;; Find the population of the first city in this list
;; whose name starts with the letter "A"
(display "Test 3: ")
(display (place-population
           (find (lambda (item)
                   (char=? (string-ref (place-name item) 0)
                           #\A))
                 *items*)))
(newline)


shared test void searchAListTask() {
    value haystack = [
            "Zig", "Zag", "Wally", "Ronald", "Bush",
            "Krusty", "Charlie", "Bush", "Bozo"];

    assert(exists firstIdx = haystack.firstOccurrence("Bush"));
    assert(exists lastIdx = haystack.lastOccurrence("Bush"));

    assertEquals(firstIdx, 4);
    assertEquals(lastIdx, 7);
}


(let [haystack ["Zig" "Zag" "Wally" "Ronald" "Bush" "Krusty" "Charlie" "Bush" "Bozo"]]
  (let [idx (.indexOf haystack "Zig")]
    (if (neg? idx)
      (throw (Error. "item not found."))
      idx)))


% Search an indexable, ordered collection.
% The collection needs to provide `indexes' and `fetch';
% the element type needs to provide `equal'.
search = proc [T, U: type] (haystack: T, needle: U)
         returns (int) signals (not_found)
         where T has indexes: itertype (T) yields (int),
                     fetch: proctype (T,int) returns (U) signals (bounds),
               U has equal: proctype (U,U) returns (bool)
    for i: int in T$indexes(haystack) do
        if needle = haystack[i] then return (i) end
    end
    signal not_found
end search

start_up = proc ()
    as = array[string]
    str_search = search[as,string]

    po: stream := stream$primary_output()
    haystack: as := as$
        ["Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo"]
    needles: as := as$
        ["Ronald","McDonald","Bush","Obama"]

    for needle: string in as$elements(needles) do
        stream$puts(po, needle || ": ")
        stream$putl(po, int$unparse(str_search(haystack,needle)))
        except when not_found:
            stream$putl(po, "not found")
        end
    end
end start_up


      limit% = 100000
      DIM sieve% limit%

      prime% = 2
      WHILE prime%^2 < limit%
        FOR I% = prime%*2 TO limit% STEP prime%
          sieve%?I% = 1
        NEXT
        REPEAT prime% += 1 : UNTIL sieve%?prime%=0
      ENDWHILE

      REM Display the primes:
      FOR I% = 1 TO limit%
        IF sieve%?I% = 0 PRINT I%;
      NEXT


struct City {
    String name,
    Number population,
}

var cities = [
    City("Lagos", 21),
    City("Cairo", 15.2),
    City("Kinshasa-Brazzaville", 11.3),
    City("Greater Johannesburg", 7.55),
    City("Mogadishu", 5.85),
    City("Khartoum-Omdurman", 4.98),
    City("Dar Es Salaam", 4.7),
    City("Alexandria", 4.58),
    City("Abidjan", 4.4),
    City("Casablanca", 3.98),
]

say cities.index{|city| city.name == "Dar Es Salaam"}
say cities.first{|city| city.population < 5.0}.name
say cities.first{|city| city.name.begins_with("A")}.population


CREATE TABLE african_capitals(name varchar2(100), population_in_millions NUMBER(3,2));


type city = { name : string, population : real }

val citys : city list = [
        { name = "Lagos",                population = 21.0  },
        { name = "Cairo",                population = 15.2  },
        { name = "Kinshasa-Brazzaville", population = 11.3  },
        { name = "Greater Johannesburg", population =  7.55 },
        { name = "Mogadishu",            population =  5.85 },
        { name = "Khartoum-Omdurman",    population =  4.98 },
        { name = "Dar Es Salaam",        population =  4.7  },
        { name = "Alexandria",           population =  4.58 },
        { name = "Abidjan",              population =  4.4  },
        { name = "Casablanca",           population =  3.98 } ]

val firstCityi   = #1 (valOf (List.findi (fn (_, city) => #name(city) = "Dar Es Salaam") citys))
val firstBelow5M = #name (valOf (List.find (fn city => #population(city) < 5.0) citys))
val firstPopA    = #population (valOf (List.find (fn city => String.substring (#name(city), 0, 1) = "A") citys))


*> This is written to COBOL85, which does not include exceptions.
       IDENTIFICATION DIVISION.
       PROGRAM-ID. Search-List.

       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01  haystack-area.
           78  Haystack-Size VALUE 10.
           03  haystack-data.
               05  FILLER     PIC X(7) VALUE "Zig".
               05  FILLER     PIC X(7) VALUE "Zag".
               05  FILLER     PIC X(7) VALUE "Wally".
               05  FILLER     PIC X(7) VALUE "Ronald".
               05  FILLER     PIC X(7) VALUE "Bush".
               05  FILLER     PIC X(7) VALUE "Krusty".
               05  FILLER     PIC X(7) VALUE "Charlie".
               05  FILLER     PIC X(7) VALUE "Bush".
               05  FILLER     PIC X(7) VALUE "Boz".
               05  FILLER     PIC X(7) VALUE "Zag".

           03  haystack-table REDEFINES haystack-data.
               05  haystack   PIC X(7) OCCURS Haystack-Size TIMES
                   INDEXED BY haystack-index.

       01  needle             PIC X(7).

       PROCEDURE DIVISION.
       main.
           MOVE "Bush" TO needle
           PERFORM find-needle

           MOVE "Goofy" TO needle
           PERFORM find-needle

*          *> Extra task
           MOVE "Bush" TO needle
           PERFORM find-last-of-needle

           GOBACK
           .

       find-needle.
           SEARCH haystack
               AT END
                   DISPLAY needle " not found."

               WHEN haystack (haystack-index) = needle
                   DISPLAY "Found " needle " at " haystack-index "."
           END-SEARCH
           .

       find-last-of-needle.
           PERFORM VARYING haystack-index FROM Haystack-Size BY -1
               UNTIL haystack-index = 0
               OR haystack (haystack-index) = needle
           END-PERFORM

           IF haystack-index = 0
               DISPLAY needle " not found."
           ELSE
               DISPLAY "Found last of " needle " at " haystack-index "."
           END-IF
           .


get "libhdr"

manifest $( LIMIT = 1000 $)

let sieve(prime,max) be
$(  let i = 2
    0!prime := false
    1!prime := false
    for i = 2 to max do i!prime := true
    while i*i <= max do
    $(  if i!prime do
        $(  let j = i*i
            while j <= max do
            $(  j!prime := false
                j := j + i
            $)
        $)
        i := i + 1
    $)
$)

let start() be
$(  let prime = vec LIMIT
    let col = 0
    sieve(prime, LIMIT)
    for i = 2 to LIMIT do
        if i!prime do
        $(  writef("%I4",i)
            col := col + 1
            if col rem 20 = 0 then wrch('*N')
        $)
    wrch('*N')
$)


struct Place {
  var name: String
  var population: Double
}

let places = [
  Place(name: "Lagos", population: 21.0),
  Place(name: "Cairo", population: 15.2),
  Place(name: "Kinshasa-Brazzaville", population: 11.3),
  Place(name: "Greater Johannesburg", population: 7.55),
  Place(name: "Mogadishu", population: 5.85),
  Place(name: "Khartoum-Omdurman", population: 4.98),
  Place(name: "Dar Es Salaam", population: 4.7),
  Place(name: "Alexandria", population: 4.58),
  Place(name: "Abidjan", population: 4.4),
  Place(name: "Casablanca", population: 3.98)
]


# records is a list of dicts.
set records {
  { name "Lagos"                population 21.0  }
  { name "Cairo"                population 15.2  }
  { name "Kinshasa-Brazzaville" population 11.3  }
  { name "Greater Johannesburg" population  7.55 }
  { name "Mogadishu"            population  5.85 }
  { name "Khartoum-Omdurman"    population  4.98 }
  { name "Dar Es Salaam"        population  4.7  }
  { name "Alexandria"           population  4.58 }
  { name "Abidjan"              population  4.4  }
  { name "Casablanca"           population  3.98 }
}

# Tcl's version of "higher order programming" is a bit unusual.  Instead of passing lambda
# functions, it is often easier to pass script fragments.  This command takes two such
# arguments: $test is an expression (as understood by [expr]), and $action is a script.
# thanks to [dict with], both $test and $action can refer to the fields of the current
# record by name - or to other variables used in the proc, like $index or $record.
proc search {records test action} {
    set index 0
    foreach record $records {
        dict with record {}
        if $test $action
        incr index
    }
    error "No match found!"
}

#  Find the (zero-based) index of the first city in the list whose name is "Dar Es Salaam"
puts [search $records {$name eq "Dar Es Salaam"} {return $index}]
#  Find the name of the first city in this list whose population is less than 5 million
puts [search $records {$population < 5.0} {return $name}]
#  Find the population of the first city in this list whose name starts with the letter "A"
puts [search $records {[string match A* $name]} {return $population}]


import "/dynamic" for Tuple

var Element = Tuple.create("Element", ["record", "index"])

var findFirst = Fn.new { |seq, pred|
    var i = 0
    for (e in seq) {
        if (pred.call(e)) return Element.new(e, i)
        i = i + 1
    }
    return Element.new(null, -1)
}

var City = Tuple.create("City", ["name", "pop"])

var cities = [
    City.new("Lagos", 21.0),
    City.new("Cairo", 15.2),
    City.new("Kinshasa-Brazzaville", 11.3),
    City.new("Greater Johannesburg", 7.55),
    City.new("Mogadishu", 5.85),
    City.new("Khartoum-Omdurman", 4.98),
    City.new("Dar Es Salaam", 4.7),
    City.new("Alexandria", 4.58),
    City.new("Abidjan", 4.4),
    City.new("Casablanca", 3.98)
]

var index = findFirst.call(cities) { |c| c.name == "Dar Es Salaam" }.index
System.print("Index of the first city whose name is 'Dar Es Salaam' is %(index).")
var city = findFirst.call(cities) { |c| c.pop < 5 }.record.name
System.print("First city whose population is less than 5 million is %(city).")
var pop = findFirst.call(cities) { |c| c.name[0] == "A" }.record.pop
System.print("The population of the first city whose name begins with 'A' is %(pop).")


(let ((haystack '(Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo)))
  (dolist (needle '(Washington Bush))
    (let ((index (position needle haystack)))
      (if index
          (progn (print index) (princ needle))
          (progn (print needle) (princ "is not in haystack"))))))


import std.algorithm, std.range, std.string;

auto firstIndex(R, T)(R hay, T needle) {
  auto i = countUntil(hay, needle);
  if (i == -1)
    throw new Exception("No needle found in haystack");
  return i;
}

auto lastIndex(R, T)(R hay, T needle) {
  return walkLength(hay) - firstIndex(retro(hay), needle) - 1;
}

void main() {
  auto h = split("Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo");
  assert(firstIndex(h, "Bush") == 4);
  assert(lastIndex(h, "Bush") == 7);
}


list:=T(SD("name","Lagos", 		  "population",21.0), // SD is a fixed dictionary
        SD("name","Cairo", 		  "population",15.2),
	SD("name","Kinshasa-Brazzaville", "population",11.3),
	SD("name","Greater Johannesburg", "population", 7.55),
	SD("name","Mogadishu", 		  "population", 5.85),
	SD("name","Khartoum-Omdurman", 	  "population", 4.98),
	SD("name","Dar Es Salaam", 	  "population", 4.7),
	SD("name","Alexandria", 	  "population", 4.58),
	SD("name","Abidjan", 		  "population", 4.4),
	SD("name","Casablanca", 	  "population", 3.98));

// Test case 1:
n:=list.filter1n(fcn(city){ city["name"]=="Dar Es Salaam" });  // one way
n:=list.filter1n(fcn(city){ city["name"].matches("dar es salaam") }); // or this way
n.println("==index of ",list[n].values);

// Test case 2:
city:=list.filter1(fcn(city){ city["population"]<5.0 });  // stop after first match
city["name"].println(" is the first city with population under 5 million.");

// Test case 3:
city:=list.filter1(fcn(city){ city["name"][0]=="A" });
println("The first \"A*\" city (%s) with population under 5 million: %f".fmt(city.values.xplode()));


program Needle;

{$APPTYPE CONSOLE}

uses
  SysUtils, Classes;

var
  list: TStringList;
  needle: string;
  ind: Integer;
begin
  list := TStringList.Create;
  try
    list.Append('triangle');
    list.Append('fork');
    list.Append('limit');
    list.Append('baby');
    list.Append('needle');

    list.Sort;

    needle := 'needle';
    ind := list.IndexOf(needle);
    if ind < 0 then
      raise Exception.Create('Needle not found')
    else begin
      Writeln(ind);
      Writeln(list[ind]);
    end;

    Readln;
  finally
    list.Free;
  end;
end.


var haystack : array of String = ["Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo"];

function Find(what : String) : Integer;
begin
   Result := haystack.IndexOf(what);
   if Result < 0 then
      raise Exception.Create('not found');
end;

PrintLn(Find("Ronald")); // 3
PrintLn(Find('McDonald')); // exception


Primes ← {
  𝕩≤2 ? ↕0 ;             # No primes below 2
  p ← 𝕊⌈√n←𝕩             # Initial primes by recursion
  b ← 2≤↕n               # Initial sieve: no 0 or 1
  E ← {↕∘⌈⌾((𝕩×𝕩+⊢)⁼)n}  # Multiples of 𝕩 under n, starting at 𝕩×𝕩
  / b E⊸{0¨⌾(𝕨⊸⊏)𝕩}´ p   # Cross them out
}


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

/** meet the 'raise an exception' requirement */
def find(needle) {
    switch (haystack.indexOf1(needle)) {
        match ==(-1) { throw("an exception") }
        match index { return index }
    }
}

println(find("Ronald")) # prints 3
println(find("McDonald")) # will throw


import system'routines;
import extensions;

public program()
{
    var haystack := new string[]{"Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie", "Bush", "Bozo"};

    new string[]{"Washington", "Bush"}.forEach:(needle)
    {
        var index := haystack.indexOfElement:needle;

        if (index == -1)
        {
            console.printLine(needle," is not in haystack")
        }
        else
        {
            console.printLine(needle, " - ", index)
        }
    }
}


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

Enum.each(~w(Bush Washington), fn needle ->
  index = Enum.find_index(haystack, fn x -> x==needle end)
  if index, do: (IO.puts "#{index} #{needle}"),
            else: raise "#{needle} is not in haystack\n"
end)


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

main() ->
    Haystack = ["Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo"],
    Needles = ["Washington","Bush"],
    lists:foreach(fun ?MODULE:print/1, [{N,pos(N, Haystack)} || N <- Needles]).

pos(Needle, Haystack) -> pos(Needle, Haystack, 1).
pos(_, [], _) -> undefined;
pos(Needle, [Needle|_], Pos) -> Pos;
pos(Needle, [_|Haystack], Pos) -> pos(Needle, Haystack, Pos+1).

print({Needle, undefined}) -> io:format("~s is not in haystack.~n",[Needle]);
print({Needle, Pos}) -> io:format("~s at position ~p.~n",[Needle,Pos]).


#include <stdlib.h>
#include <math.h>

char*
eratosthenes(int n, int *c)
{
	char* sieve;
	int i, j, m;

	if(n < 2)
		return NULL;

	*c = n-1;     /* primes count */
	m = (int) sqrt((double) n);

	/* calloc initializes to zero */
	sieve = calloc(n+1,sizeof(char));
	sieve[0] = 1;
	sieve[1] = 1;
	for(i = 2; i <= m; i++)
		if(!sieve[i])
			for (j = i*i; j <= n; j += i)
				if(!sieve[j]){
					sieve[j] = 1;
					--(*c);
				}
  	return sieve;
}


include std/search.e
include std/console.e

--the string "needle" and example haystacks to test the procedure
sequence searchStr1 = "needle"
sequence haystack1 = { "needle", "needle", "noodle", "node", "need", "needle  ", "needle" }
sequence haystack2 = {"spoon", "fork", "hay", "knife", "needle", "barn", "etcetera", "more hay", "needle", "a cow", "farmer", "needle", "dirt"}
sequence haystack3 = {"needle"}
sequence haystack4 = {"no", "need le s", "in", "this", "haystack"}
sequence haystack5 = {"knee", "needle", "dull", "needle"}
sequence haystack6 = {}

--search procedure with console output
procedure haystackSearch(sequence hStack)
    sequence foundNeedles = find_all(searchStr1, hStack)
    puts(1,"---------------------------------\r\n")
    if object(foundNeedles) and length(foundNeedles) > 0 then
        printf(1, "First needle found at index %d \r\n", foundNeedles[1])

        if length(foundNeedles) > 1 then
            printf(1, "Last needle found at index %d \r\n", foundNeedles[length(foundNeedles)] )

            for i = 1 to length(foundNeedles) do
                printf(1, "Needle #%d ", i)
                printf(1, "was at index %d .\r\n", foundNeedles[i])
            end for

            else
                puts(1, "There was only one needle found in this haystack. \r\n")
        end if

        else
            puts(1, "Simulated exception - No needles found in this haystack.\r\n")
    end if

end procedure

--runs the procedure on all haystacks
haystackSearch(haystack1)
haystackSearch(haystack2)
haystackSearch(haystack3)
haystackSearch(haystack4)
haystackSearch(haystack5)
haystackSearch(haystack6)
--wait for user to press a key to exit
any_key()


using System;
using System.Collections;
using System.Collections.Generic;

namespace SieveOfEratosthenes
{
    class Program
    {
        static void Main(string[] args)
        {
            int maxprime = int.Parse(args[0]);
            var primelist = GetAllPrimesLessThan(maxprime);
            foreach (int prime in primelist)
            {
                Console.WriteLine(prime);
            }
            Console.WriteLine("Count = " + primelist.Count);
            Console.ReadLine();
        }

        private static List<int> GetAllPrimesLessThan(int maxPrime)
        {
            var primes = new List<int>();
            var maxSquareRoot = (int)Math.Sqrt(maxPrime);
            var eliminated = new BitArray(maxPrime + 1);

            for (int i = 2; i <= maxPrime; ++i)
            {
                if (!eliminated[i])
                {
                    primes.Add(i);
                    if (i <= maxSquareRoot)
                    {
                        for (int j = i * i; j <= maxPrime; j += i)
                        {
                            eliminated[j] = true;
                        }
                    }
                }
            }
            return primes;
        }
    }
}


List.findIndex (fun x -> x = "bar") ["foo"; "bar"; "baz"; "bar"]  // -> 1
                                      // A System.Collections.Generic.KeyNotFoundException
                                      // is raised, if the predicate does not evaluate to
                                      // true for any list element.


: find-index ( seq elt -- i )
    '[ _ = ] find drop [ "Not found" throw ] unless* ; inline

: find-last-index ( seq elt -- i )
    '[ _ = ] find-last drop [ "Not found" throw ] unless* ; inline


include lib/row.4th

create haystack
  ," Zig"  ," Zag" ," Wally" ," Ronald" ," Bush" ," Krusty" ," Charlie"
  ," Bush" ," Boz" ," Zag" NULL ,
does>
  dup >r 1 string-key row 2>r type 2r> ."  is "
  if r> - ." at " . else r> drop drop ." not found" then cr
;

s" Washington" haystack s" Bush" haystack


#include <iostream>
#include <algorithm>
#include <vector>

// requires Iterator satisfies RandomAccessIterator
template <typename Iterator>
size_t prime_sieve(Iterator start, Iterator end)
{
    if (start == end) return 0;
    // clear the container with 0
    std::fill(start, end, 0);
    // mark composites with 1
    for (Iterator prime_it = start + 1; prime_it != end; ++prime_it)
    {
        if (*prime_it == 1) continue;
        // determine the prime number represented by this iterator location
        size_t stride = (prime_it - start) + 1;
        // mark all multiples of this prime number up to max
        Iterator mark_it = prime_it;
        while ((end - mark_it) > stride)
        {
            std::advance(mark_it, stride);
            *mark_it = 1;
        }
    }
    // copy marked primes into container
    Iterator out_it = start;
    for (Iterator it = start + 1; it != end; ++it)
    {
        if (*it == 0)
        {
            *out_it = (it - start) + 1;
            ++out_it;
        }
    }
    return out_it - start;
}

int main(int argc, const char* argv[])
{
    std::vector<int> primes(100);
    size_t count = prime_sieve(primes.begin(), primes.end());
    // display the primes
    for (size_t i = 0; i < count; ++i)
        std::cout << primes[i] << " ";
    std::cout << std::endl;
    return 1;
}


program main

 implicit none

 character(len=7),dimension(10) :: haystack = [  &
  'Zig    ',&
  'Zag    ',&
  'Wally  ',&
  'Ronald ',&
  'Bush   ',&
  'Krusty ',&
  'Charlie',&
  'Bush   ',&
  'Boz    ',&
  'Zag    ']

 call find_needle('Charlie')
 call find_needle('Bush')

 contains

	subroutine find_needle(needle)
	implicit none
	character(len=*),intent(in) :: needle
	integer :: i
	do i=1,size(haystack)
		if (needle==haystack(i)) then
			write(*,'(A,I4)') trim(needle)//' found at index:',i
			return
		end if
	end do
	write(*,'(A)') 'Error: '//trim(needle)//' not found.'
	end subroutine find_needle

 end program main


' FB 1.05.0 Win64
' Works FB 1.05.0 Linux Mint 64

Function tryFindString(s() As String, search As String, ByRef index As Integer) As Boolean
  Dim length As Integer = UBound(s) - LBound(s) + 1
  If length = 0 Then
    index = LBound(s) - 1  '' outside array
    Return False
  End If
  For i As Integer = LBound(s) To UBound(s)
    If s(i) = search Then
      index = i  '' first occurrence
      Return True
    End If
  Next
  index = LBound(s) - 1  '' outside array
  Return False
End Function

Function tryFindLastString(s() As String, search As String, ByRef index As Integer) As Boolean
  Dim length As Integer = UBound(s) - LBound(s) + 1
  If length = 0 Then
    index = LBound(s) - 1  '' outside array
    Return False
  End If
  Dim maxIndex As Integer = LBound(s) - 1  '' outside array
  For i As Integer = LBound(s) To UBound(s)
    If s(i) = search Then
      maxIndex = i
    End If
  Next
  If maxIndex > LBound(s) - 1 Then
    index = maxIndex  '' last occurrence
    Return True
  Else
    Return False
  End If
End Function

Dim haystack(1 To 9) As String = {"Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie", "Bush", "Bozo"}
Dim needle(1 To 4)   As String = {"Zag", "Krusty", "Washington", "Bush"}

Dim As Integer index
Dim As Boolean found
For i As Integer  = 1 To 4
  found = tryFindString(haystack(), needle(i), index)
  If found Then
    Print needle(i); " found first at index"; index
  Else
    Print needle(i); " is not present"
  End If
Next
found = tryFindLastString(haystack(), needle(4), index)
If found Then
  Print needle(4); " found last at index"; index
Else
  Print needle(4); " is not present"
End If
Print
Print "Press any key to quit"
Sleep


// yield prime and remove all multiples of it from children sieves
iter sieve(prime):int {

        yield prime;

        var last = prime;
        label candidates for candidate in sieve(prime+1) do {
                for composite in last..candidate by prime do {

                        // candidate is a multiple of this prime
                        if composite == candidate {
                                // remember size of last composite
                                last = composite;
                                // and try the next candidate
                                continue candidates;
                        }
                }

                // candidate cannot need to be removed by this sieve
                // yield to parent sieve for checking
                yield candidate;
        }
}


Public Sub Main()
Dim sHaystack As String[] = ["Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie", "Bush", "Boz", "Zag"]
Dim sNeedle As String = "Charlie"
Dim sOutput As String = "No needle found!"
Dim siCount As Short

For siCount = 0 To sHaystack.Max
  If sNeedle = sHaystack[siCount] Then
    sOutPut = sNeedle & " found at index " & Str(siCount)
    Break
  End If
Next

Print sOutput

End


F char2value(c)
   assert(c !C ‘AEIOU’, ‘No vowels’)
   R Int(c, radix' 36)

V sedolweight = [1, 3, 1, 7, 3, 9]

F checksum(sedol)
   V tmp = sum(zip(sedol, :sedolweight).map((ch, weight) -> char2value(ch) * weight))
   R String((10 - (tmp % 10)) % 10)

V sedols =
|‘710889
  B0YBKJ
  406566
  B0YBLH
  228276
  B0YBKL
  557910
  B0YBKR
  585284
  B0YBKT’

L(sedol) sedols.split("\n")
   print(sedol‘’checksum(sedol))


(defn primes< [n]
   (remove (set (mapcat #(range (* % %) n %)
                        (range 2 (Math/sqrt n))))
           (range 2 n)))


package main

var haystack = []string{"Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty",
    "Charlie", "Bush", "Bozo", "Zag", "mouse", "hat", "cup", "deodorant",
    "television", "soap", "methamphetamine", "severed cat heads", "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", "sodium", "phosphorous", "californium",
    "copernicium", "gold", "thallium", "carbon", "silver", "gold", "copper",
    "helium", "sulfur"}


INT FUNC SedolChecksum(CHAR ARRAY sedol)
  BYTE ARRAY weights=[1 3 1 7 3 9]
  INT i,sum
  CHAR c

  IF sedol(0)#6 THEN
    RETURN (-1)
  FI

  sum=0
  FOR i=1 TO sedol(0)
  DO
    c=sedol(i)
    IF c>='0 AND c<='9 THEN
      sum==+(c-'0)*weights(i-1)
    ELSE
      IF c>='a AND c<='z THEN
        c==-'a-'A
      FI
      IF c='A OR c='E OR c='I OR c='O OR c='U THEN
        RETURN (-1)
      ELSEIF c>='A AND c<='Z THEN
        sum==+(c-'A+10)*weights(i-1)
      ELSE
        RETURN (-1)
      FI
    FI
  OD
  sum=(10-(sum MOD 10)) MOD 10
RETURN (sum)

PROC Test(CHAR ARRAY sedol)
  INT res

  res=SedolChecksum(sedol)
  Print(sedol) Print(" -> ")
  IF res>=0 THEN
    Print(sedol) PrintIE(res)
  ELSE
    PrintE("invalid input")
  FI
RETURN

PROC Main()
  Test("710889")
  Test("B0YBKJ")
  Test("406566")
  Test("B0YBLH")
  Test("228276")
  Test("B0YBKL")
  Test("557910")
  Test("B0YBKR")
  Test("585284")
  Test("B0YBKT")
  Test("B00030")
  Test("12345A")
  Test("12345")
  Test("1234567")
RETURN


//Return the code corresponding to a given character.
//ActionScript does not have a character type, so 1-digit strings
//are used instead
function toSEDOLCode(char:String):uint {
	//Make sure only a single character was sent.
	if(char.length != 1)
		throw new Error("toSEDOL expected string length of 1, got " + char.length);
	//Character is uppercase
	if (char >= "A" && char <= "Z") {
		return SEDOL.charCodeAt() + 10 - "A".charCodeAt();
	}
	//Character is numeric
	else if (char >= "0" && char <= "9"){
		return uint(char);
	}
	//Error: character is neither numeric nor uppercase
	else{
		throw new Error("toSEDOLCode expected numeric or uppercase character, recieved " + char);
	}
}
//Calculate the weighted sum for the SEDOL.
function toSum(str:String):uint {
	if(str.length != 6)
		throw new Error("toSum expected length 6, recieved " + str.length);
	var sum:uint=0;
	for (var i:uint = 0; i < str.length; i++)
		sum+=toSEDOLCode(str.charAt(i))*[1,3,1,7,3,9][i];
	return sum;
}
//Calculate the check digit from the weighted sum.
function toCheck(num:int):uint
{
	return (10 -(num % 10)) % 10;
}
//Print the SEDOL with the check digit added.
function printWithCheck(SEDOL:String):void
{
	trace(SEDOL + toCheck(toSum(SEDOL)));
}
printWithCheck("710889");
printWithCheck("B0YBKJ");
printWithCheck("406566");
printWithCheck("B0YBLH");
printWithCheck("228276");
printWithCheck("B0YBKL");
printWithCheck("557910");
printWithCheck("B0YBKR");
printWithCheck("585284");
printWithCheck("B0YBKT");
printWithCheck("B00030");


% Sieve of Eratosthenes
eratosthenes = proc (n: int) returns (array[bool])
    prime: array[bool] := array[bool]$fill(1, n, true)
    prime[1] := false

    for p: int in int$from_to(2, n/2) do
        if prime[p] then
            for c: int in int$from_to_by(p*p, n, p) do
                prime[c] := false
            end
        end
    end
    return(prime)
end eratosthenes

% Print primes up to 1000 using the sieve
start_up = proc ()
    po: stream := stream$primary_output()
    prime: array[bool] := eratosthenes(1000)
    col: int := 0

    for i: int in array[bool]$indexes(prime) do
        if prime[i] then
            col := col + 1
            stream$putright(po, int$unparse(i), 5)
            if col = 10 then
                col := 0
                stream$putc(po, '\n')
            end
        end
    end
end start_up


def haystack = ["Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo"]
def needles = ["Washington","Bush","Wally"]
needles.each { needle ->
    def index = haystack.indexOf(needle)
    def lastindex = haystack.lastIndexOf(needle)
    if (index < 0) {
        assert lastindex < 0
        println needle + " is not in haystack"
    } else {
        println "First index: " + index + " " + needle
        println "Last index:  " + lastindex + " " + needle
    }
}


import Data.List

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


with Ada.Text_IO;  use Ada.Text_IO;

procedure Test_SEDOL is

   subtype SEDOL_String is String (1..6);
   type SEDOL_Sum is range 0..9;

   function Check (SEDOL : SEDOL_String) return SEDOL_Sum is
      Weight : constant array (SEDOL_String'Range) of Integer := (1,3,1,7,3,9);
      Sum    : Integer := 0;
      Item   : Integer;
   begin
      for Index in SEDOL'Range loop
         Item := Character'Pos (SEDOL (Index));
         case Item is
            when Character'Pos ('0')..Character'Pos ('9') =>
               Item := Item - Character'Pos ('0');
            when Character'Pos ('B')..Character'Pos ('D') |
                 Character'Pos ('F')..Character'Pos ('H') |
                 Character'Pos ('J')..Character'Pos ('N') |
                 Character'Pos ('P')..Character'Pos ('T') |
                 Character'Pos ('V')..Character'Pos ('Z') =>
               Item := Item - Character'Pos ('A') + 10;
            when others =>
               raise Constraint_Error;
         end case;
         Sum := Sum + Item * Weight (Index);
      end loop;
      return SEDOL_Sum ((-Sum) mod 10);
   end Check;

   Test : constant array (1..10) of SEDOL_String :=
             (  "710889", "B0YBKJ", "406566", "B0YBLH", "228276",
                "B0YBKL", "557910", "B0YBKR", "585284", "B0YBKT"
             );
begin
   for Index in Test'Range loop
      Put_Line (Test (Index) & Character'Val (Character'Pos ('0') + Check (Test (Index))));
   end loop;
end Test_SEDOL;


[]INT sedol weights = (1, 3, 1, 7, 3, 9);
STRING reject = "AEIOUaeiou";

PROC strcspn = (STRING s,reject)INT: (
  INT out:=0;
  FOR i TO UPB s DO
    IF char in string(s[i], LOC INT, reject) THEN
      return out
    FI;
    out:=i
  OD;
  return out: out
);

PROC sedol checksum = (REF STRING sedol6)INT:
(
  INT out;

  INT len := UPB sedol6;
  INT sum := 0;

  IF sedol6[len-1] = REPR 10 THEN len-:=1; sedol6[len]:=null char FI;
  IF len = 7 THEN
    putf(stand error, ($"SEDOL code already checksummed? ("g")"l$, sedol6));
    out := ABS ( BIN ABS sedol6[6] AND 16r7f); return out
  FI;
  IF len > 7 OR len < 6 OR strcspn(sedol6, reject) /= 6 THEN
    putf(stand error, ($"not a SEDOL code? ("g")"l$, sedol6));
    out := -1; return out
  FI;
  FOR i TO UPB sedol6 DO
    sum+:=sedol weights[i]*
      IF is digit(sedol6[i]) THEN
        ABS sedol6[i]- ABS "0"
      ELIF is alpha(sedol6[i]) THEN
        (ABS to upper(sedol6[i])-ABS "A") + 10
      ELSE
        putf(stand error, $"SEDOL with not alphanumeric digit"l$);
        out:=-1; return out
      FI
  OD;
  out := (10 - (sum MOD 10)) MOD 10 + ABS "0";
  return out: out
);

main:
(
  STRING line;

  on logical file end(stand in, (REF FILE f)BOOL: done);
  DO getf(stand in, ($gl$,line));
    INT sr := sedol checksum(line);
    IF sr > 0 THEN
      printf(($ggl$, line, REPR sedol checksum(line)))
    FI
  OD;
  done: SKIP
)


function(eratosthenes var limit)
  # Check for integer overflow. With CMake using 32-bit signed integer,
  # this check fails when limit > 46340.
  if(NOT limit EQUAL 0)         # Avoid division by zero.
    math(EXPR i "(${limit} * ${limit}) / ${limit}")
    if(NOT limit EQUAL ${i})
      message(FATAL_ERROR "limit is too large, would cause integer overflow")
    endif()
  endif()

  # Use local variables prime_2, prime_3, ..., prime_${limit} as array.
  # Initialize array to y => yes it is prime.
  foreach(i RANGE 2 ${limit})
    set(prime_${i} y)
  endforeach(i)

  # Gather a list of prime numbers.
  set(list)
  foreach(i RANGE 2 ${limit})
    if(prime_${i})
      # Append this prime to list.
      list(APPEND list ${i})

      # For each multiple of i, set n => no it is not prime.
      # Optimization: start at i squared.
      math(EXPR square "${i} * ${i}")
      if(NOT square GREATER ${limit})   # Avoid fatal error.
        foreach(m RANGE ${square} ${limit} ${i})
          set(prime_${m} n)
        endforeach(m)
      endif()
    endif(prime_${i})
  endforeach(i)
  set(${var} ${list} PARENT_SCOPE)
endfunction(eratosthenes)


CHARACTER haystack='Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo.'
CHARACTER needle*10

DLG(TItle="Enter search string", Edit=needle)

n = EDIT(Text=haystack, Option=2, End, Count=needle) ! Option = word

IF( n == 0 ) THEN
  WRITE(Messagebox="!") needle, "not found"    ! bus not found
ELSE
  first = EDIT(Text=needle, LeXicon=haystack)
  WRITE(ClipBoard) "First ", needle, "found in position ", first
  ! First bush      found in position 5

  last = EDIT(Text=haystack, End, Left=needle, Count=" ") + 1
  WRITE(ClipBoard) "Last ", needle, "found in position ", last
  ! Last bush      found in position 8
ENDIF


link lists

procedure main()
haystack := ["Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo"]  # the haystack
every needle := !["Bush","Washington"] do {                                         # the needles

   if i := lindex(haystack,needle) then {                                           # first occurrence
      write("needle=",needle, " is at position ",i," in haystack.")

      if i <:= last(lindex,[haystack,needle]) then                                  # last occurrence
         write("needle=",needle, " is at last position ",i," in haystack.")
      }
   else {
      write("needle=",needle, " is not in haystack.")
      runerr(500,needle)        # throw an error
      }
   }

end

procedure last(p,arglist)               #: return the last generation of p(arglist) or fail
local i
every i := p!arglist
return \i
end


begin
    % returns the check digit for the specified SEDOL %
    string(1) procedure sedolCheckDigit ( string(6) value sedol ) ;
    begin
        integer       checkSum, checkDigit;
        checkSum := 0;
        for cPos := 0 until 5 do begin
            string(1) c;
            integer   digit;
            c := sedol( cPos // 1 );
            if c >= "0" and c <= "9"
            then digit :=        decode( c ) - decode( "0" )
            else digit := 10 + ( decode( c ) - decode( "A" ) );
            checkSum := checkSum + ( ( case cPos + 1 of ( 1, 3, 1, 7, 3, 9 ) ) * digit )
        end for_cPos ;
        checkDigit := ( 10 - ( checkSum rem 10 ) ) rem 10;
        if checkDigit < 10
        then code( decode( "0" ) +   checkDigit        )
        else code( decode( "A" ) + ( checkDigit - 10 ) )
    end sedolCheckDigit ;

    % task test cases %

    procedure testCheckDigit ( string(6) value sedol; string(1) value expectedCheckDigit ) ;
    begin
        string(1) checkDigit;
        checkDigit := sedolCheckDigit( sedol );
        write( s_w := 0, sedol, checkDigit );
        if checkDigit not = expectedCheckDigit then writeon( " ?? expected: ", expectedCheckDigit )
    end testCheckDigit ;

    testCheckDigit( "710889", "9" );
    testCheckDigit( "B0YBKJ", "7" );
    testCheckDigit( "406566", "3" );
    testCheckDigit( "B0YBLH", "2" );
    testCheckDigit( "228276", "5" );
    testCheckDigit( "B0YBKL", "9" );
    testCheckDigit( "557910", "7" );
    testCheckDigit( "B0YBKR", "5" );
    testCheckDigit( "585284", "2" );
    testCheckDigit( "B0YBKT", "7" );
    testCheckDigit( "B00030", "0" )
end.


on appendCheckDigitToSEDOL(sedol)
    if ((count sedol) is not 6) then ¬
        return {false, "Error in appendCheckDigitToSEDOL handler: " & sedol & " doesn't have 6 characters."}
    set chars to "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    set vowels to "AEIOU"
    set weights to {1, 3, 1, 7, 3, 9}

    set s to 0
    considering diacriticals but ignoring case -- In case these are set otherwise when this handler's called.
        repeat with i from 1 to 6
            set thisCharacter to character i of sedol
            set o to (offset of thisCharacter in chars)
            if ((o is 0) or (thisCharacter is in vowels)) then ¬
                return {false, "Error in appendCheckDigitToSEDOL handler: " & sedol & " contains invalid character(s)."}
            set s to s + (o - 1) * (item i of weights)
        end repeat
    end considering

    return {true, sedol & ((10 - (s mod 10)) mod 10)}
end appendCheckDigitToSEDOL

-- Test code:
set input to "710889
B0YBKJ
406566
B0YBLH
228276
B0YBKL
557910
B0YBKR
585284
B0YBKT
B00030"
set output to {}
repeat with thisSEDOL in paragraphs of input
    set {valid, theResult} to appendCheckDigitToSEDOL(thisSEDOL)
    set end of output to theResult
end repeat
set astid to AppleScript's text item delimiters
set AppleScript's text item delimiters to linefeed
set output to output as text
set AppleScript's text item delimiters to astid
return output


*> Please ignore the asterisks in the first column of the next comments,
*> which are kludges to get syntax highlighting to work.
       IDENTIFICATION DIVISION.
       PROGRAM-ID. Sieve-Of-Eratosthenes.

       DATA DIVISION.
       WORKING-STORAGE SECTION.

       01  Max-Number       USAGE UNSIGNED-INT.
       01  Max-Prime        USAGE UNSIGNED-INT.

       01  Num-Group.
           03  Num-Table PIC X VALUE "P"
                   OCCURS 1 TO 10000000 TIMES DEPENDING ON Max-Number
                   INDEXED BY Num-Index.
               88  Is-Prime VALUE "P" FALSE "N".

       01  Current-Prime    USAGE UNSIGNED-INT.

       01  I                USAGE UNSIGNED-INT.

       PROCEDURE DIVISION.
           DISPLAY "Enter the limit: " WITH NO ADVANCING
           ACCEPT Max-Number
           DIVIDE Max-Number BY 2 GIVING Max-Prime

*          *> Set Is-Prime of all non-prime numbers to false.
           SET Is-Prime (1) TO FALSE
           PERFORM UNTIL Max-Prime < Current-Prime
*              *> Set current-prime to next prime.
               ADD 1 TO Current-Prime
               PERFORM VARYING Num-Index FROM Current-Prime BY 1
                   UNTIL Is-Prime (Num-Index)
               END-PERFORM
               MOVE Num-Index TO Current-Prime

*              *> Set Is-Prime of all multiples of current-prime to
*              *> false, starting from current-prime sqaured.
               COMPUTE Num-Index = Current-Prime ** 2
               PERFORM UNTIL Max-Number < Num-Index
                   SET Is-Prime (Num-Index) TO FALSE
                   SET Num-Index UP BY Current-Prime
               END-PERFORM
           END-PERFORM

*          *> Display the prime numbers.
           PERFORM VARYING Num-Index FROM 1 BY 1
                   UNTIL Max-Number < Num-Index
               IF Is-Prime (Num-Index)
                   DISPLAY Num-Index
               END-IF
           END-PERFORM

           GOBACK
           .


NotFound := Exception clone
List firstIndex := method(obj,
    indexOf(obj) ifNil(NotFound raise)
)
List lastIndex := method(obj,
    reverseForeach(i,v,
        if(v == obj, return i)
    )
    NotFound raise
)

haystack := list("Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo")
list("Washington","Bush") foreach(needle,
    try(
        write("firstIndex(\"",needle,"\"): ")
        writeln(haystack firstIndex(needle))
    )catch(NotFound,
        writeln(needle," is not in haystack")
    )pass
    try(
        write("lastIndex(\"",needle,"\"): ")
        writeln(haystack lastIndex(needle))
    )catch(NotFound,
        writeln(needle," is not in haystack")
    )pass
)


   Haystack =: ;:'Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo'
   Needles  =: ;:'Washington Bush'

   Haystack i. Needles     NB. first positions
9 4
   Haystack i: Needles     NB. last positions
9 7


ord0: to :integer `0`
ord7: to :integer `7`
c2v: function [c][
    ordC: to :integer c
    if? c < `A` -> return ordC - ord0
    else -> return ordC - ord7
]

weight: [1 3 1 7 3 9]

checksum: function [sedol][
    val: new 0
    loop .with:'i sedol 'ch ->
        'val + weight\[i] * c2v ch
    return to :char ord0 + (10 - val % 10) % 10
]

sedols: [
    "710889" "B0YBKJ" "406566" "B0YBLH"
    "228276" "B0YBKL" "557910" "B0YBKR"
    "585284" "B0YBKT" "B00030"
]

loop sedols 'sed ->
    print [sed "->" sed ++ checksum sed]


codes = 710889,B0YBKJ,406566,B0YBLH,228276,B0YBKL,557910,B0YBKR,585284,B0YBKT,B00030,ABCDEF,BBBBBBB
Loop, Parse, codes, `,
    output .= A_LoopField "`t-> " SEDOL(A_LoopField) "`n"
Msgbox %output%

SEDOL(code) {
    Static weight1:=1, weight2:=3, weight3:=1, weight4:=7, weight5:=3, weight6:=9
    If (StrLen(code) != 6)
        Return "Invalid length."
    StringCaseSense On
    Loop, Parse, code
        If A_LoopField is Number
            check_digit += A_LoopField * weight%A_Index%
        Else If A_LoopField in B,C,D,F,G,H,J,K,L,M,N,P,Q,R,S,T,V,W,X,Y,Z
            check_digit += (Asc(A_LoopField)-Asc("A") + 10) * weight%A_Index%
        Else
            Return "Invalid character."
    Return code . Mod(10-Mod(check_digit,10),10)
}


// Sieve of Eratosthenes
input "Limit? ": limit
dim sieve(1:limit)
sqrlimit:=sqr(limit)
sieve(1):=1
p:=2
while p<=sqrlimit do
 while sieve(p) and p<sqrlimit do
  p:=p+1
 endwhile
 if p>sqrlimit then goto done
 for i:=p*p to limit step p do
  sieve(i):=1
 endfor i
 p:=p+1
endwhile
done:
print 2,
for i:=3 to limit do
 if sieve(i)=0 then
  print ", ",i,
 endif
endfor i
print


import java.util.List;
import java.util.Arrays;

List<String> haystack = Arrays.asList("Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo");

for (String needle : new String[]{"Washington","Bush"}) {
    int index = haystack.indexOf(needle);
    if (index < 0)
        System.out.println(needle + " is not in haystack");
    else
        System.out.println(index + " " + needle);
}


var haystack = ['Zig', 'Zag', 'Wally', 'Ronald', 'Bush', 'Krusty', 'Charlie', 'Bush', 'Bozo']
var needles = ['Bush', 'Washington']

for (var i in needles) {
    var found = false;
    for (var j in haystack) {
        if (haystack[j] == needles[i]) {
            found = true;
            break;
        }
    }
    if (found)
        print(needles[i] + " appears at index " + j + " in the haystack");
    else
        throw needles[i] + " does not appear in the haystack"
}


function ord(a)
{
  return amap[a]
}

function sedol_checksum(sed)
{
  sw[1] = 1; sw[2] = 3; sw[3] = 1
  sw[4] = 7; sw[5] = 3; sw[6] = 9
  sum = 0
  for(i=1; i <= 6; i++) {
    c = substr(toupper(sed), i, 1)
    if ( c ~ /[[:digit:]]/ ) {
      sum += c*sw[i]
    } else {
      sum += (ord(c)-ord("A")+10)*sw[i]
    }
  }
  return (10 - (sum % 10)) % 10
}

BEGIN { # prepare amap for ord
  for(_i=0;_i<256;_i++) {
    astr = sprintf("%c", _i)
    amap[astr] = _i
  }
}

/[AEIOUaeiou]/ {
  print "'" $0 "' not a valid SEDOL code"
  next
}
{
  if ( (length($0) > 7) || (length($0) < 6) ) {
    print "'" $0 "' is too long or too short to be valid SEDOL"
    next
  }
  sedol = substr($0, 1, 6)
  sedolcheck = sedol_checksum(sedol)
  if ( length($0) == 7 ) {
    if ( (sedol sedolcheck) != $0 ) {
      print sedol sedolcheck " (original " $0 " has wrong check digit"
    } else {
      print sedol sedolcheck
    }
  } else {
    print sedol sedolcheck
  }
}


(defun sieve-of-eratosthenes (maximum)
  (loop
     with sieve = (make-array (1+ maximum)
                              :element-type 'bit
                              :initial-element 0)
     for candidate from 2 to maximum
     when (zerop (bit sieve candidate))
     collect candidate
     and do (loop for composite from (expt candidate 2)
               to maximum by candidate
               do (setf (bit sieve composite) 1))))


["a","b","c"] | index("b")
# => 1

["a","b","c","b"] | index("b")
# => 1

["a","b","c","b"]
  | index("x") // error("element not found")
# => jq: error: element not found

# Extra task - the last element of an array can be retrieved
# using `rindex/` or by using -1 as an index into the array produced by `indices/1`:
["a","b","c","b","d"] | rindex("b")
# => 3

["a","b","c","b","d"] | indices("b")[-1]
# => 3


@show findfirst(["no", "?", "yes", "maybe", "yes"], "yes")
@show indexin(["yes"], ["no", "?", "yes", "maybe", "yes"])
@show findin(["no", "?", "yes", "maybe", "yes"], ["yes"])
@show find(["no", "?", "yes", "maybe", "yes"] .== "yes")


  Haystack:("Zig";"Zag";"Wally";"Ronald";"Bush";"Krusty";"Charlie";"Bush";"Bozo")
  Needles:("Washington";"Bush")
  {:[y _in x;(y;x _bin y);(y;"Not Found")]}[Haystack]'Needles


DECLARE FUNCTION getSedolCheckDigit! (str AS STRING)
DO
        INPUT a$
        PRINT a$ + STR$(getSedolCheckDigit(a$))
LOOP WHILE a$ <> ""

FUNCTION getSedolCheckDigit (str AS STRING)
    IF LEN(str) <> 6 THEN
        PRINT "Six chars only please"
        EXIT FUNCTION
    END IF
    str = UCASE$(str)
    DIM mult(6) AS INTEGER
    mult(1) = 1: mult(2) = 3: mult(3) = 1
    mult(4) = 7: mult(5) = 3: mult(6) = 9
    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


      PRINT FNsedol("710889")
      PRINT FNsedol("B0YBKJ")
      PRINT FNsedol("406566")
      PRINT FNsedol("B0YBLH")
      PRINT FNsedol("228276")
      PRINT FNsedol("B0YBKL")
      PRINT FNsedol("557910")
      PRINT FNsedol("B0YBKR")
      PRINT FNsedol("585284")
      PRINT FNsedol("B0YBKT")
      PRINT FNsedol("B00030")
      END

      DEF FNsedol(d$)
      LOCAL a%, i%, s%, weights%()
      DIM weights%(6) : weights%() = 0, 1, 3, 1, 7, 3, 9
      FOR i% = 1 TO 6
        a% = ASCMID$(d$,i%) - &30
        s% += (a% + 7 * (a% > 9)) * weights%(i%)
      NEXT
      = d$ + CHR$(&30 + (10 - s% MOD 10) MOD 10)