langs a-z

This commit is contained in:
Ingy döt Net 2013-04-10 22:43:41 -07:00
parent db842d013d
commit d066446780
11389 changed files with 98361 additions and 1020 deletions

View file

@ -0,0 +1,106 @@
/* NetRexx */
options replace format comments java crossref symbols nobinary
driver(arg) -- call the test wrapper
return
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method searchListOfWords(haystack, needle, forwards = (1 == 1), respectCase = (1 == 1)) public static signals Exception
if \respectCase then do
needle = needle.upper()
haystack = haystack.upper()
end
if forwards then wp = haystack.wordpos(needle)
else wp = haystack.words() - haystack.reverse().wordpos(needle.reverse()) + 1
if wp = 0 then signal Exception('*** Error! "'needle'" not found in list ***')
return wp
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method searchIndexedList(haystack, needle, forwards = (1 == 1), respectCase = (1 == 1)) public static signals Exception
if forwards then do
strtIx = 1
endIx = haystack[0]
incrIx = 1
end
else do
strtIx = haystack[0]
endIx = 1
incrIx = -1
end
wp = 0
loop ix = strtIx to endIx by incrIx
if respectCase then
if needle == haystack[ix] then wp = ix
else nop
else
if needle.upper() == haystack[ix].upper() then wp = ix
else nop
if wp > 0 then leave ix
end ix
if wp = 0 then signal Exception('*** Error! "'needle'" not found in indexed list ***')
return wp
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- Test wrapper
method driver(arg) public static
-- some manifests
TRUE_ = (1 == 1); FALSE_ = \TRUE_
FORWARDS_ = TRUE_; BACKWARDS_ = FALSE_
CASERESPECT_ = TRUE_; CASEIGNORE_ = \CASERESPECT_
-- test data
needles = ['barley', 'quinoa']
-- a simple list of words. Lists of words are indexable in NetRexx via the word(N) function
hayrick = 'Barley maize barley sorghum millet wheat rice rye barley Barley oats flax'
-- a Rexx indexed string made up from the words in hayrick
cornstook = ''
loop w_ = 1 to hayrick.words() -- populate the indexed string
cornstook[0] = w_
cornstook[w_] = hayrick.word(w_)
end w_
loop needle over needles
do -- process the list of words
say 'Searching for "'needle'" in the list "'hayrick'"'
idxF = searchListOfWords(hayrick, needle)
idxL = searchListOfWords(hayrick, needle, BACKWARDS_)
say ' The first occurence of "'needle'" is at index' idxF 'in the list'
say ' The last occurence of "'needle'" is at index' idxL 'in the list'
idxF = searchListOfWords(hayrick, needle, FORWARDS_, CASEIGNORE_)
idxL = searchListOfWords(hayrick, needle, BACKWARDS_, CASEIGNORE_)
say ' The first caseless occurence of "'needle'" is at index' idxF 'in the list'
say ' The last caseless occurence of "'needle'" is at index' idxL 'in the list'
say
catch ex = Exception
say ' 'ex.getMessage()
say
end
do -- process the indexed list
corn = ''
loop ci = 1 to cornstook[0]
corn = corn cornstook[ci]
end ci
say 'Searching for "'needle'" in the indexed list "'corn.space()'"'
idxF = searchIndexedList(cornstook, needle)
idxL = searchIndexedList(cornstook, needle, BACKWARDS_)
say ' The first occurence of "'needle'" is at index' idxF 'in the indexed list'
say ' The last occurence of "'needle'" is at index' idxL 'in the indexed list'
idxF = searchIndexedList(cornstook, needle, FORWARDS_, CASEIGNORE_)
idxL = searchIndexedList(cornstook, needle, BACKWARDS_, CASEIGNORE_)
say ' The first caseless occurence of "'needle'" is at index' idxF 'in the indexed list'
say ' The last caseless occurence of "'needle'" is at index' idxL 'in the indexed list'
say
catch ex = Exception
say ' 'ex.getMessage()
say
end
end needle
return

View file

@ -0,0 +1,23 @@
# let find_index pred lst =
let rec loop n = function
[] -> raise Not_found
| x::xs -> if pred x then n
else loop (n+1) xs
in
loop 0 lst;;
val find_index : ('a -> bool) -> 'a list -> int = <fun>
# let haystack =
["Zig";"Zag";"Wally";"Ronald";"Bush";"Krusty";"Charlie";"Bush";"Bozo"];;
val haystack : string list =
["Zig"; "Zag"; "Wally"; "Ronald"; "Bush"; "Krusty"; "Charlie"; "Bush";
"Bozo"]
# List.iter (fun needle ->
try
Printf.printf "%i %s\n" (find_index ((=) needle) haystack) needle
with Not_found ->
Printf.printf "%s is not in haystack\n" needle)
["Washington"; "Bush"];;
Washington is not in haystack
4 Bush
- : unit = ()

View file

@ -0,0 +1,18 @@
use Structure;
bundle Default {
class Test {
function : Main(args : String[]) ~ Nil {
haystack := ["Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo"];
values := CompareVector->New();
each(i : haystack) {
values->AddBack(haystack[i]->As(Compare));
};
needles := ["Washington", "Bush"];
each(i : needles) {
values->Has(needles[i]->As(Compare))->PrintLine();
};
}
}
}

View file

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

View file

@ -0,0 +1,10 @@
NSArray *haystack = [NSArray arrayWithObjects:@"Zig",@"Zag",@"Wally",@"Ronald",@"Bush",@"Krusty",@"Charlie",@"Bush",@"Bozo",nil];
id needle;
NSEnumerator *enm = [[NSArray arrayWithObjects:@"Washington",@"Bush",nil] objectEnumerator];
while ((needle = [enm nextObject]) != nil) {
int index = [haystack indexOfObject:needle];
if (index == NSNotFound)
NSLog(@"%@ is not in haystack", needle);
else
NSLog(@"%i %@", index, needle);
}

View file

@ -0,0 +1,24 @@
declare
%% Lazy list of indices of Y in Xs.
fun {Indices Y Xs}
for
X in Xs
I in 1;I+1
yield:Yield
do
if Y == X then {Yield I} end
end
end
fun {Index Y Xs}
case {Indices Y Xs} of X|_ then X
else raise index(elementNotFound Y) end
end
end
Haystack = ["Zig" "Zag" "Wally" "Ronald" "Bush" "Krusty" "Charlie" "Bush" "Bozo"]
in
{Show {Index "Bush" Haystack}}
{Show {List.last {Indices "Bush" Haystack}}}
{Show {Index "Washington" Haystack}} %% throws

View file

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

View file

@ -0,0 +1,21 @@
search: procedure () returns (fixed binary);
declare haystack (0:9) character (200) varying static initial
('apple', 'banana', 'celery', 'dumpling', 'egg', 'flour',
'grape', 'pomegranate', 'raisin', 'sugar' );
declare needle character (200) varying;
declare i fixed binary;
declare missing_needle condition;
on condition(missing_needle) begin;
put skip list ('your string ''' || needle ||
''' does not exist in the haystack.');
end;
put ('Please type a string');
get edit (needle) (L);
do i = lbound(haystack,1) to hbound(haystack,1);
if needle = haystack(i) then return (i);
end;
signal condition(missing_needle);
return (lbound(haystack,1)-1);
end search;

View file

@ -0,0 +1,20 @@
sub find ($matcher, $container) {
for $container.kv -> $k, $v {
$v ~~ $matcher and return $k;
}
fail 'No values matched';
}
my Str @haystack = <Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo>;
for <Washingston Bush> -> $needle {
my $pos = find $needle, @haystack;
if defined $pos {
say "Found '$needle' at index $pos";
say 'Largest index: ', @haystack.end -
find { $needle eq $^x }, reverse @haystack;
}
else {
say "'$needle' not in haystack";
}
}

View file

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

View file

@ -0,0 +1,36 @@
If OpenConsole() ; Open a simple console to interact with user
NewList Straws.s()
Define Straw$, target$="TBA"
Define found
Restore haystack ; Read in all the straws of the haystack.
Repeat
Read.s Straw$
If Straw$<>""
AddElement(Straws())
Straws()=UCase(Straw$)
Continue
Else
Break
EndIf
ForEver
While target$<>""
Print(#CRLF$+"Enter word to search for (leave blank to quit) :"): target$=Input()
ResetList(Straws()): found=#False
While NextElement(Straws())
If UCase(target$)=Straws()
found=#True
PrintN(target$+" found as index #"+Str(ListIndex(Straws())))
EndIf
Wend
If Not found
PrintN("Not found.")
EndIf
Wend
EndIf
DataSection
haystack:
Data.s "Zig","Zag","Zig","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo",""
EndDataSection

View file

@ -0,0 +1,40 @@
REBOL [
Title: "List Indexing"
Author: oofoe
Date: 2009-12-06
URL: http://rosettacode.org/wiki/Index_in_a_list
]
locate: func [
"Find the index of a string (needle) in string collection (haystack)."
haystack [series!] "List of values to search."
needle [string!] "String to find in value list."
/largest "Return the largest index if more than one needle."
/local i
][
i: either largest [
find/reverse tail haystack needle][find haystack needle]
either i [return index? i][
throw reform [needle "is not in haystack."]
]
]
; Note that REBOL uses 1-base lists instead of 0-based like most
; computer languages. Therefore, the index provided will be one
; higher than other results on this page.
haystack: parse "Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo" none
print "Search for first occurance:"
foreach needle ["Washington" "Bush"] [
print catch [
reform [needle "=>" locate haystack needle]
]
]
print [crlf "Search for last occurance:"]
foreach needle ["Washington" "Bush"] [
print catch [
reform [needle "=>" locate/largest haystack needle]
]
]

View file

@ -0,0 +1,21 @@
haystack$ = ("Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo Bush ")
needle$ = "Zag Wally Bush Chicken"
while word$(needle$,i+1," ") <> ""
i = i + 1
thisNeedle$ = word$(needle$,i," ") + " "
j = instr(haystack$,thisNeedle$)
k1 = 0
k = instr(haystack$,thisNeedle$,j+1)
while k <> 0
k1 = k
k = instr(haystack$,thisNeedle$,k+1)
wend
if j <> 0 then
print thisNeedle$;" located at:";j;
if k1 <> 0 then print " Last position located at:";k1;
print
else
print thisNeedle$;" is not in the list"
end if
wend

View file

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

View file

@ -0,0 +1,15 @@
fun find_index (pred, lst) = let
fun loop (n, []) = NONE
| loop (n, x::xs) = if pred x then SOME n
else loop (n+1, xs)
in
loop (0, lst)
end;
val haystack = ["Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo"];
app (fn needle =>
case find_index (fn x => x = needle, haystack) of
SOME i => print (Int.toString i ^ " " ^ needle ^ "\n")
| NONE => print (needle ^ " is not in haystack\n"))
["Washington", "Bush"];

View file

@ -0,0 +1,16 @@
$$ MODE TUSCRIPT
SET haystack="Zig'Zag'Wally'Ronald'Bush'Krusty'Charlie'Bush'Bozo"
PRINT "haystack=",haystack
LOOP needle="Washington'Bush'Wally"
SET table =QUOTES (needle)
BUILD S_TABLE needle = table
IF (haystack.ct.needle) THEN
BUILD R_TABLE needle = table
SET position=FILTER_INDEX(haystack,needle,-)
RELEASE R_TABLE needle
PRINT "haystack contains ", needle, " on position(s): ",position
ELSE
PRINT "haystack not contains ",needle
ENDIF
RELEASE S_TABLE needle
ENDLOOP

View file

@ -0,0 +1,35 @@
function findIn(%haystack,%needles)
{
%hc = getWordCount(%haystack);
%nc = getWordCount(%needles);
for(%i=0;%i<%nc;%i++)
{
%nword = getWord(%needles,%i);
%index[%nword] = -1;
}
for(%i=0;%i<%hc;%i++)
{
%hword = getWord(%haystack,%i);
for(%j=0;%j<%nc;%j++)
{
%nword = getWord(%needles,%j);
if(%hword $= %nword)
{
%index[%nword] = %i;
}
}
}
for(%i=0;%i<%nc;%i++)
{
%nword = getWord(%needles,%i);
%string = %string SPC %nword@"_"@%index[%nword];
%string = trim(%string);
}
return %string;
}

View file

@ -0,0 +1 @@
echo(findIn("Hello world, you are quite sunny today.","quite hello somethingelse"));

View file

@ -0,0 +1 @@
=> "quite_4 hello_0 somethingelse_-1"

View file

@ -0,0 +1,3 @@
#import std
indices = ||<'missing'>!% ~&nSihzXB+ ~&lrmPE~|^|/~& num

View file

@ -0,0 +1,3 @@
#cast %nW
test = indices/'bar' <'foo','bar','baz','bar'>

View file

@ -0,0 +1,25 @@
\Based on C example:
include c:\cxpl\stdlib; \provides StrCmp routine, etc.
int Haystack; \('int' is used instead of 'char' for 2D array)
func Search(Str, First); \Return first (or last) index for string in haystack
char Str; int First;
int I, SI;
[I:= 0; SI:= 0;
repeat if StrCmp(Str, Haystack(I)) = 0 then
[if First then return I;
SI:= I; \save index
];
I:= I+1;
until Haystack(I) = 0;
return SI;
];
[Haystack:= ["Zig", "Zag", "Wally", "Ronald", "Bush",
"Krusty", "Charlie", "Bush", "Boz", "Zag", 0];
Text(0, "Bush is at "); IntOut(0, Search("Bush", true)); CrLf(0);
if Search("Washington", true) = 0 then
Text(0, "Washington is not in the haystack^M^J");
Text(0, "First index for Zag: "); IntOut(0, Search("Zag", true)); CrLf(0);
Text(0, "Last index for Zag: "); IntOut(0, Search("Zag", false)); CrLf(0);
]

View file

@ -0,0 +1,10 @@
haystack = ["Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie", "Bush", "Bozo"];
needles = ["Bush", "Washington"];
for(i = 1; i <= numberof(needles); i++) {
w = where(haystack == needles(i));
if(!numberof(w))
error, "Needle "+needles(i)+" not found";
write, format="Needle %s appears first at index %d\n", needles(i), w(1);
if(numberof(w) > 1)
write, format="Needle %s appears last at index %d\n", needles(i), w(0);
}