Initial data commit

This commit is contained in:
Ingy döt Net 2023-07-01 11:58:00 -04:00
parent 72d218235f
commit f23f22d71c
199087 changed files with 3378941 additions and 0 deletions

View file

@ -0,0 +1,3 @@
---
from: http://rosettacode.org/wiki/Search_a_list
note: Text processing

View file

@ -0,0 +1,18 @@
{{task heading}}
Find the index of a string (needle) in an indexable, ordered collection of strings (haystack).
Raise an exception if the needle is missing.
If there is more than one occurrence then return the smallest index to the needle.
{{task heading|Extra credit}}
Return the largest index to a needle that has multiple occurrences in the haystack.
{{task heading|See also}}
* [[Search a list of records]]
<hr>

View file

@ -0,0 +1,7 @@
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)

View file

@ -0,0 +1,7 @@
(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))

View file

@ -0,0 +1,24 @@
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
)

View file

@ -0,0 +1,28 @@
[]STRING hay stack = ("Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo");
PROC index = ([]STRING hay stack, STRING needle)INT:(
INT index;
FOR i FROM LWB hay stack TO UPB hay stack DO
index := i;
IF hay stack[index] = needle THEN
found
FI
OD;
else:
LWB hay stack - 1
EXIT
found:
index
);
test:(
[]STRING needles = ("Washington","Bush");
FOR i TO UPB needles DO
STRING needle := needles[i];
INT result = index(hay stack, needle);
IF result >= LWB hay stack THEN
printf(($d" "gl$, result, needle))
ELSE
printf(($g" "gl$,needle, "is not in haystack"))
FI
OD
)

View file

@ -0,0 +1,21 @@
#! /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";
}
}

View file

@ -0,0 +1,40 @@
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

View file

@ -0,0 +1,16 @@
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;
}

View file

@ -0,0 +1,7 @@
package {
public class StringNotFoundError extends Error {
public function StringNotFoundError(message:String) {
super(message);
}
}
}

View file

@ -0,0 +1,17 @@
import StringNotFoundError;
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 StringNotFoundError("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 StringNotFoundError("String not found: " + searchString);
return index;
}

View file

@ -0,0 +1,42 @@
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;

View file

@ -0,0 +1,27 @@
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;
}

View file

@ -0,0 +1,8 @@
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]
]

View file

@ -0,0 +1,9 @@
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"
}

View file

@ -0,0 +1,29 @@
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

View file

@ -0,0 +1,19 @@
list$ = "mouse,hat,cup,deodorant,television,soap,methamphetamine,severed cat heads,cup"
n$ = explode(list$, ",")
t = 0 : j = 0
input string "Enter string to search: ", linea$
for i = 0 to n$[?]-1
if linea$ = n$[i] then
if not t then print "First index for "; linea$; ": "; i
t = i
j += 1
end if
next
if t = 0 then
print "String not found in list"
else
if j > 1 then print "Last index for "; linea$; ": "; t
end if

View file

@ -0,0 +1,21 @@
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

View file

@ -0,0 +1,10 @@
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"

View file

@ -0,0 +1,9 @@
2 10
2
! "Error: 'Hi' Not found in list"
("Error: '" 𝕩 "' Not found in list") ! (𝕨)ind 𝕨𝕩
^
list IndexOf "Hi"
^^^^^^^

View file

@ -0,0 +1,40 @@
@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

View file

@ -0,0 +1,23 @@
( 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."
)
);

View file

@ -0,0 +1,2 @@
blsq ) {"Zig" "Zag" "Wally" "Bush" "Ronald" "Bush"}"Bush"Fi
3

View file

@ -0,0 +1,2 @@
blsq ) {"Zig" "Zag" "Wally" "Bush" "Ronald" "Bush"}{"Bush"==}fI
{3 5}

View file

@ -0,0 +1,112 @@
#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");
}

View file

@ -0,0 +1,114 @@
/* new c++-11 features
* list class
* initialization strings
* auto typing
* lambda functions
* noexcept
* find
* for/in loop
*/
#include <iostream> // std::cout
#include <algorithm> // std::find
#include <list> // std::list
#include <vector> // std::vector
#include <string> // string::basic_string
using namespace std; // saves typing of "std::" before everything
int main()
{
// initialization lists
// create objects and fully initialize them with given values
list<string> l { "Zig", "Zag", "Wally", "Homer", "Madge",
"Watson", "Ronald", "Bush", "Krusty", "Charlie",
"Bush", "Bush", "Boz", "Zag" };
list<string> n { "Bush" , "Obama", "Homer", "Sherlock" };
// lambda function with auto typing
// auto is easier to write than looking up the complicated
// specialized iterator type that is actually returned.
// Just know that it returns an iterator for the list at the position found,
// or throws an exception if s in not in the list.
// runtime_error is used because it can be initialized with a message string.
auto contains = [](list<string> l, string s) throw(runtime_error)
{
auto r = find(begin(l), end(l), s );
if( r == end(l) )
throw runtime_error( s + " not found" );
return r;
};
// returns an int vector with the indexes of the search string
// The & is a "default capture" meaning that it "allows in"
// the variables that are in scope where it is called by their
// name to simplify things.
auto index = [&](list<string> l, string s) noexcept
{
vector<int> index_v;
int idx = 0;
for(const string& r : l)
{
if( s.compare(r) == 0 ) // match -- add to vector
index_v.push_back(idx);
idx++;
}
// even though index_v is local to the lambda function,
// c++11 move semantics does what you want and returns it
// live and intact instead of destroying it or returning a copy.
// (very efficient for large objects!)
return index_v;
};
// range-based for loop
// s is a read-only reference, not a copy
for (const string& s : n) // new iteration syntax is simple and intuitive
{
try
{
auto cont = contains( l , s); // checks if there is any match
if( cont != l.end() ) // found at least one
{
vector<int> vf = index( l, s );
cout << "l contains: " << s << " at " ;
for(auto x : vf) // auto will resolve to int
{ cout << x << " "; } // if vector is empty this doesn't run
cout << "\n";
}
}
catch (const runtime_error& r) // string not found
{
cout << r.what() << "\n";
continue; // try next string
}
} //for
return 0;
} // main
/* end */

View file

@ -0,0 +1,15 @@
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);
}
}
}

View file

@ -0,0 +1,40 @@
#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;
}

View file

@ -0,0 +1,32 @@
% 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

View file

@ -0,0 +1,63 @@
*> 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
.

View file

@ -0,0 +1,11 @@
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);
}

View file

@ -0,0 +1,5 @@
(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)))

View file

@ -0,0 +1,6 @@
(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"))))))

View file

@ -0,0 +1,8 @@
CL-USER> (defparameter *list* '(Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo))
*LIST*
CL-USER> (position 'Bush *list*)
4
CL-USER> (position 'Bush *list* :from-end t)
7
CL-USER> (position 'Washington *list*)
NIL

View file

@ -0,0 +1,18 @@
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);
}

View file

@ -0,0 +1,11 @@
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

View file

@ -0,0 +1,36 @@
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.

View file

@ -0,0 +1,12 @@
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

View file

@ -0,0 +1,21 @@
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)
}
}
}

View file

@ -0,0 +1,7 @@
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)

View file

@ -0,0 +1,15 @@
-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]).

View file

@ -0,0 +1,46 @@
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()

View file

@ -0,0 +1,4 @@
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.

View file

@ -0,0 +1,5 @@
: 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

View file

@ -0,0 +1,11 @@
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

View file

@ -0,0 +1,29 @@
include FMS-SI.f
include FMS-SILib.f
${ Dishonest Fake Left Karl Hillary Monica Bubba Hillary Multi-Millionaire } constant haystack
: needleIndex { addr len $list | cnt -- idx }
0 to cnt $list uneach:
begin
$list each:
while
@: addr len compare 0= if cnt exit then
cnt 1+ to cnt
repeat true abort" Not found" ;
: LastIndexOf { addr len $list | cnt last-found -- idx }
0 to cnt 0 to last-found $list uneach:
begin
$list each:
while
@: addr len compare 0= if cnt to last-found then
cnt 1+ to cnt
repeat
last-found if last-found
else true abort" Not found"
then ;
s" Hillary" haystack needleIndex . \ => 4
s" Hillary" haystack LastIndexOf . \ => 7
s" Washington" haystack needleIndex . \ => aborted: Not found

View file

@ -0,0 +1,35 @@
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

View file

@ -0,0 +1,61 @@
' 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

View file

@ -0,0 +1,29 @@
window 1, @"Search a list"
void local fn MyEnumeratorCallback( array as CFArrayRef, obj as CFTypeRef, index as NSUInteger, stp as ^BOOL, userData as ptr )
if ( fn StringIsEqual( obj, userData ) )
print obj;@" found at index ";index
*stp = YES// stop enumeration
end if
if ( index == 0 ) then print userData;@" not found"
end fn
void local fn DoIt
CFArrayRef haystack = @[@"Mike",@"Bravo",@"Tango",@"Uniform",@"Golf",
@"Tango",@"Sierra",@"November",@"Zulu",@"Delta",@"Hotel",@"Juliet"]
CFStringRef needle = @"Sierra"
NSInteger index = fn ArrayIndexOfObject( haystack, needle )
if ( index != NSNotFound )
print needle;@" found at index ";index
else
print needle;@" not found"
end if
ArrayEnumerateObjectsWithOptions( haystack, NSEnumerationReverse, @fn MyEnumeratorCallback, (ptr)@"Tango" )
end fn
fn DoIt
HandleEvents

View file

@ -0,0 +1,27 @@
# First position is built-in
haystack := Eratosthenes(10000);;
needle := 8999;;
Position(haystack, needle);
# 1117
LastPosition := function(L, x)
local old, new;
old := 0;
new := 0;
while new <> fail do
new := Position(L, x, old);
if new <> fail then
old := new;
fi;
od;
return old;
end;
a := Shuffle(List([1 .. 100], x -> x mod 10));
# [ 0, 2, 4, 5, 3, 1, 0, 4, 8, 8, 2, 7, 6, 3, 3, 6, 4, 4, 3, 0, 7, 1, 8, 7, 2, 4, 7, 9, 4, 9, 4, 5, 9, 9, 6, 7, 8, 2, 3,
# 5, 1, 5, 4, 2, 0, 9, 6, 1, 1, 2, 2, 0, 5, 7, 6, 8, 8, 3, 1, 9, 5, 1, 9, 6, 8, 9, 2, 0, 6, 2, 1, 6, 1, 1, 2, 5, 3, 3,
# 0, 3, 5, 7, 5, 4, 6, 8, 0, 9, 8, 3, 7, 8, 0, 4, 9, 7, 0, 6, 5, 7 ]
Position(a, 0);
# 1
LastPosition(a, 0);
# 97

View file

@ -0,0 +1,16 @@
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

View file

@ -0,0 +1,14 @@
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"}

View file

@ -0,0 +1,66 @@
package main
import "fmt"
func main() {
// first task
printSearchForward("soap")
printSearchForward("gold")
printSearchForward("fire")
// extra task
printSearchReverseMult("soap")
printSearchReverseMult("gold")
printSearchReverseMult("fire")
}
// First task solution uses panic as an exception-like mechanism, as requested
// by the task. Note however, this is not idiomatic in Go and in fact
// is considered bad practice.
func printSearchForward(s string) {
fmt.Printf("Forward search: %s: ", s)
defer func() {
if x := recover(); x != nil {
if err, ok := x.(string); ok && err == "no match" {
fmt.Println(err)
return
}
panic(x)
}
}()
fmt.Println("smallest index =", searchForwardPanic(s))
}
func searchForwardPanic(s string) int {
for i, h := range haystack {
if h == s {
return i
}
}
panic("no match")
return -1
}
// Extra task, a quirky search for multiple occurrences. This is written
// without panic, and shows more acceptable Go programming practice.
func printSearchReverseMult(s string) {
fmt.Printf("Reverse search for multiples: %s: ", s)
if i := searchReverseMult(s); i > -1 {
fmt.Println("largest index =", i)
} else {
fmt.Println("no multiple occurrence")
}
}
func searchReverseMult(s string) int {
largest := -1
for i := len(haystack) - 1; i >= 0; i-- {
switch {
case haystack[i] != s:
case largest == -1:
largest = i
default:
return largest
}
}
return -1
}

View file

@ -0,0 +1,13 @@
package main
import "fmt"
func main() {
m := map[string][]int{}
for i, needle := range haystack {
m[needle] = append(m[needle], i)
}
for _, n := range []string{"soap", "gold", "fire"} {
fmt.Println(n, m[n])
}
}

View file

@ -0,0 +1,13 @@
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
}
}

View file

@ -0,0 +1,4 @@
import Data.List
haystack=["Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo"]
needles = ["Washington","Bush"]

View file

@ -0,0 +1,2 @@
*Main> map (\x -> (x,elemIndex x haystack)) needles
[("Washington",Nothing),("Bush",Just 4)]

View file

@ -0,0 +1,2 @@
*Main> map (\x -> (x,elemIndices x haystack)) needles
[("Washington",[]),("Bush",[4,7])]

View file

@ -0,0 +1,2 @@
*Main> ((,) <*> flip elemIndex haystack) <$> needles
[("Washington",Nothing),("Bush",Just 4)]

View file

@ -0,0 +1,18 @@
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

View file

@ -0,0 +1,17 @@
100 PROGRAM "Search.bas"
110 STRING A$(1 TO 55)*8
120 FOR I=1 TO 55
130 READ A$(I)
140 PRINT A$(I);" ";
150 NEXT
160 DO
170 PRINT :INPUT PROMPT "Word to seatch for? (Leave blank to exit) ":S$
180 LET S$=LCASE$(LTRIM$(RTRIM$(S$))):LET FOUND=0
190 IF S$="" THEN EXIT DO
200 FOR I=LBOUND(A$) TO UBOUND(A$)
210 IF A$(I)=S$ THEN LET FOUND=-1:PRINT "Found """;S$;""" at index";I
220 NEXT
230 IF NOT FOUND THEN PRINT """";S$;""" not found."
240 LOOP
250 DATA foo,bar,baz,quux,quuux,quuuux,bazola,ztesch,foo,bar,thud,grunt,foo,bar,bletch,foo,bar,fum,fred,jim,sheila,barney,flarp,zxc
260 DATA 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

View file

@ -0,0 +1,25 @@
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

View file

@ -0,0 +1,7 @@
procedure lindex(lst, x) #: generate indices for items matching x
local i
every i := 1 to *lst do
if lst[i] === x then suspend i
end

View file

@ -0,0 +1,26 @@
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
)

View file

@ -0,0 +1,7 @@
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

View file

@ -0,0 +1,4 @@
Needles e. Haystack
0 1
1 2 3 4 5 6 7 8 9 e. 2 3 5 60
0 1 1 0 1 0 0 0 0

View file

@ -0,0 +1,4 @@
1 2 3 4 5 6 7 8 9 I. 2 3 5 60 6.66
1 2 4 9 6
(;:'eight five four nine one seven six three two') I. ;:'two three five sixty'
8 7 1 7

View file

@ -0,0 +1,3 @@
Haystack ;:^:_1@(] ,. [ ((<'is not in haystack')"_)`(#@[ I.@:= ])`(8!:0@])} i.) Needles
Washington is not in haystack
Bush 4

View file

@ -0,0 +1,8 @@
msg=: (<'is not in haystack')"_ NB. not found message
idxmissing=: #@[ I.@:= ] NB. indices of items not found
fmtdata=: 8!:0@] NB. format atoms as boxed strings
findLastIndex=: ;:inv@(] ,. [ msg`idxmissing`fmtdata} i:)
Haystack findLastIndex Needles NB. usage
Washington is not in haystack
Bush 7

View file

@ -0,0 +1,12 @@
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);
}

View file

@ -0,0 +1,11 @@
import java.util.Arrays;
String[] haystack = { "Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo"};
for (String needle : new String[]{"Washington","Bush"}) {
int index = Arrays.binarySearch(haystack, needle);
if (index < 0)
System.out.println(needle + " is not in haystack");
else
System.out.println(index + " " + needle);
}

View file

@ -0,0 +1,16 @@
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"
}

View file

@ -0,0 +1,18 @@
for each (var needle in needles) {
var idx = haystack.indexOf(needle);
if (idx == -1)
throw needle + " does not appear in the haystack"
else
print(needle + " appears at index " + idx + " in the haystack");
}
// extra credit
for each (var elem in haystack) {
var first_idx = haystack.indexOf(elem);
var last_idx = haystack.lastIndexOf(elem);
if (last_idx > first_idx) {
print(elem + " last appears at index " + last_idx + " in the haystack");
break
}
}

View file

@ -0,0 +1,47 @@
(function () {
function findIndex(fnPredicate, list) {
for (var i = 0, lng = list.length; i < lng; i++) {
if (fnPredicate(list[i])) {
return i;
}
}
return Error("not found");
};
// DEFINING A PARTICULAR TYPE OF SEARCH MATCH
function matchCaseInsensitive(s, t) {
return s.toLowerCase() === t.toLowerCase();
}
var lstHaystack = [
'Zig', 'Zag', 'Wally', 'Ronald', 'Bush',
'Krusty', 'Charlie', 'Bush', 'Bozo'
],
lstReversed = lstHaystack.slice(0).reverse(),
iLast = lstHaystack.length - 1,
lstNeedles = ['bush', 'washington'];
return {
'first': lstNeedles.map(function (s) {
return [s, findIndex(function (t) {
return matchCaseInsensitive(s, t);
},
lstHaystack)];
}),
'last': lstNeedles.map(function (s) {
var varIndex = findIndex(function (t) {
return matchCaseInsensitive(s, t);
},
lstReversed);
return [
s,
typeof varIndex === 'number' ?
iLast - varIndex : varIndex
];
})
}
})();

View file

@ -0,0 +1,22 @@
{
"first": [
[
"bush",
4
],
[
"washington",
"Error: not found"
]
],
"last": [
[
"bush",
7
],
[
"washington",
"Error: not found"
]
]
}

View file

@ -0,0 +1,17 @@
["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

View file

@ -0,0 +1,4 @@
@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")

View file

@ -0,0 +1,3 @@
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

View file

@ -0,0 +1,4 @@
(("Washington"
"Not Found")
("Bush"
4))

View file

@ -0,0 +1,3 @@
Haystack2: Haystack,,"Bush"
Needles2:Needles,,"Zag"
{+(x;{:[#&x;,/?(*&x;*|&x);"Not found"]}'+x _sm/:y)}[Needles2;Haystack2]

View file

@ -0,0 +1,6 @@
(("Washington"
"Not found")
("Bush"
4 9)
("Zag"
1))

View file

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

View file

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

View file

@ -0,0 +1,9 @@
local(haystack) = array('Zig', 'Zag', 'Wally', 'Ronald', 'Bush', 'Krusty', 'Charlie', 'Bush', 'Bozo')
#haystack->findindex('Bush')->first // 5
#haystack->findindex('Bush')->last // 8
protect => {^
handle_error => {^ error_msg ^}
fail_if(not #haystack->findindex('Washington')->first,'Washington is not in haystack.')
^}

View file

@ -0,0 +1,37 @@
haystack$="apple orange pear cherry melon peach banana needle blueberry mango strawberry needle "
haystack$=haystack$+"pineapple grape kiwi blackberry plum raspberry needle cranberry apricot"
idx=1
do until word$(haystack$,idx)=""
idx=idx+1
loop
total=idx-1
needle$="needle"
'index of first occurrence
for i = 1 to total
if word$(haystack$,i)=needle$ then exit for
next
print needle$;" first found at index ";i
'index of last occurrence
for j = total to 1
if word$(haystack$,j)=needle$ then exit for
next
print needle$;" last found at index ";j
if i<>j then
print "Multiple instances of ";needle$
else
print "Only one instance of ";needle$;" in list."
end if
'raise exception
needle$="cauliflower"
for k=1 to total
if word$(haystack$,k)=needle$ then exit for
next
if k>total then
print needle$;" not found in list."
else
print needle$;" found at index ";k
end if

View file

@ -0,0 +1,11 @@
haystack = ["apples", "oranges", "bananas", "oranges"]
needle = "oranges"
pos = haystack.getPos(needle)
if pos then
put "needle found at index "&pos
else
put "needle not found in haystack"
end if
-- "needle found at index 2"

View file

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

View file

@ -0,0 +1,13 @@
to indexof :item :list
if empty? :list [(throw "NOTFOUND 0)]
if equal? :item first :list [output 1]
output 1 + indexof :item butfirst :list
end
to showindex :item :list
make "i catch "NOTFOUND [indexof :item :list]
ifelse :i = 0 [(print :item [ not found in ] :list)] [(print :item [ found at position ] :i [ in ] :list)]
end
showindex "dog [My dog has fleas] ; dog found at position 2 in My dog has fleas
showindex "cat [My dog has fleas] ; cat not found in My dog has fleas

View file

@ -0,0 +1,7 @@
list = {"mouse", "hat", "cup", "deodorant", "television", "soap", "methamphetamine", "severed cat heads"} --contents of my desk
item = io.read()
for i,v in ipairs(list)
if v == item then print(i) end
end

View file

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

View file

@ -0,0 +1,25 @@
Module CheckThis {
Inventory Queue Haystack= "foo", "bar", "baz", "quux", "quuux", "quuuux", "bazola", "ztesch", "foo", "bar", "thud", "grunt"
Append Haystack, "foo", "bar", "bletch", "foo", "bar", "fum", "fred", "jim", "sheila", "barney", "flarp", "zxc"
Append Haystack, "spqr", "wombat", "shme", "foo", "bar", "baz", "bongo", "spam", "eggs", "snork", "foo", "bar"
Append Haystack, "zot", "blarg", "wibble", "toto", "titi", "tata", "tutu", "pippo", "pluto", "paperino", "aap"
Append Haystack, "noot", "mies", "oogle", "foogle", "boogle", "zork", "gork", "bork"
\\ Print all list
Print Haystack
\\ inventory queue can get same keys
\\ inventory use hashtable.
\\ Inventory put same keys in a linked list, so we can found easy
Do
Input "Word to search for? (Leave blank press enter to exit) ", needle$
if needle$="" then exit
n=1
s$=lcase$(needle$)
While exist(Haystack, s$, n)
\\ number, key and position (zero based convert to one based)
Print n, Eval$(HayStack!), Eval(HayStack!)+1
n++
End While
If n=1 Then Print needle$;" not found"
Always
}
CheckThis

View file

@ -0,0 +1 @@
stringCollection = {'string1','string2',...,'stringN'}

View file

@ -0,0 +1 @@
stringCollection = {{'string1'},{'string2'},{...},{'stringN'}}

View file

@ -0,0 +1,13 @@
function index = searchCollection(list,searchItem,firstLast)
%firstLast is a string containing either 'first' or 'last'. The 'first'
%flag will cause searchCollection to return the index of the first
%instance of the item being searched. 'last' will cause
%searchCollection to return the index of the last instance of the item
%being searched.
indicies = cellfun(@(x)x==searchItem,list);
index = find(indicies,1,firstLast);
assert(~isempty(index),['The string ''' searchItem ''' does not exist in this collection of strings.']);
end

View file

@ -0,0 +1,16 @@
>> list = {'a','b','c','d','e','c','f','c'};
>> searchCollection(list,'c','first')
ans =
3
>> searchCollection(list,'c','last')
ans =
8
>> searchCollection(list,'g','last')
??? Error using ==> searchCollection at 11
The string 'g' does not exist in this collection of strings.

View file

@ -0,0 +1,15 @@
haystack=#("Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo")
for needle in #("Washington","Bush") do
(
index = findItem haystack needle
if index == 0 then
(
format "% is not in haystack\n" needle
)
else
(
format "% %\n" index needle
)
)

View file

@ -0,0 +1,2 @@
Washington is not in haystack
5 Bush

View file

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

View file

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

View file

@ -0,0 +1,3 @@
2
7
{2,7}

Some files were not shown because too many files have changed in this diff Show more