new files
This commit is contained in:
parent
3af7344581
commit
86c034bb8b
1364 changed files with 21352 additions and 0 deletions
4
Task/Search-a-list/0DESCRIPTION
Normal file
4
Task/Search-a-list/0DESCRIPTION
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
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.
|
||||
|
||||
As an extra task, return the largest index to a needle that has multiple occurrences in the haystack.
|
||||
2
Task/Search-a-list/1META.yaml
Normal file
2
Task/Search-a-list/1META.yaml
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
---
|
||||
note: Text processing
|
||||
7
Task/Search-a-list/ACL2/search-a-list.acl2
Normal file
7
Task/Search-a-list/ACL2/search-a-list.acl2
Normal 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))
|
||||
21
Task/Search-a-list/AWK/search-a-list.awk
Normal file
21
Task/Search-a-list/AWK/search-a-list.awk
Normal 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";
|
||||
}
|
||||
}
|
||||
16
Task/Search-a-list/ActionScript/search-a-list-1.as
Normal file
16
Task/Search-a-list/ActionScript/search-a-list-1.as
Normal 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;
|
||||
}
|
||||
7
Task/Search-a-list/ActionScript/search-a-list-2.as
Normal file
7
Task/Search-a-list/ActionScript/search-a-list-2.as
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
package {
|
||||
public class StringNotFoundError extends Error {
|
||||
public function StringNotFoundError(message:String) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
}
|
||||
17
Task/Search-a-list/ActionScript/search-a-list-3.as
Normal file
17
Task/Search-a-list/ActionScript/search-a-list-3.as
Normal 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;
|
||||
}
|
||||
42
Task/Search-a-list/Ada/search-a-list.ada
Normal file
42
Task/Search-a-list/Ada/search-a-list.ada
Normal 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;
|
||||
29
Task/Search-a-list/BASIC/search-a-list.bas
Normal file
29
Task/Search-a-list/BASIC/search-a-list.bas
Normal 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
|
||||
40
Task/Search-a-list/C/search-a-list.c
Normal file
40
Task/Search-a-list/C/search-a-list.c
Normal 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;
|
||||
}
|
||||
5
Task/Search-a-list/Clojure/search-a-list.clj
Normal file
5
Task/Search-a-list/Clojure/search-a-list.clj
Normal 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)))
|
||||
15
Task/Search-a-list/Erlang/search-a-list.erl
Normal file
15
Task/Search-a-list/Erlang/search-a-list.erl
Normal 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]).
|
||||
11
Task/Search-a-list/Forth/search-a-list.fth
Normal file
11
Task/Search-a-list/Forth/search-a-list.fth
Normal 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
|
||||
35
Task/Search-a-list/Fortran/search-a-list.f
Normal file
35
Task/Search-a-list/Fortran/search-a-list.f
Normal 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
|
||||
79
Task/Search-a-list/Go/search-a-list.go
Normal file
79
Task/Search-a-list/Go/search-a-list.go
Normal file
|
|
@ -0,0 +1,79 @@
|
|||
package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
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"}
|
||||
|
||||
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
|
||||
}
|
||||
4
Task/Search-a-list/Haskell/search-a-list-1.hs
Normal file
4
Task/Search-a-list/Haskell/search-a-list-1.hs
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
import Data.List
|
||||
|
||||
haystack=["Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo"]
|
||||
needles = ["Washington","Bush"]
|
||||
2
Task/Search-a-list/Haskell/search-a-list-2.hs
Normal file
2
Task/Search-a-list/Haskell/search-a-list-2.hs
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
*Main> map (\x -> (x,elemIndex x haystack)) needles
|
||||
[("Washington",Nothing),("Bush",Just 4)]
|
||||
2
Task/Search-a-list/Haskell/search-a-list-3.hs
Normal file
2
Task/Search-a-list/Haskell/search-a-list-3.hs
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
*Main> map (\x -> (x,elemIndices x haystack)) needles
|
||||
[("Washington",[]),("Bush",[4,7])]
|
||||
5
Task/Search-a-list/Haskell/search-a-list-4.hs
Normal file
5
Task/Search-a-list/Haskell/search-a-list-4.hs
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
import Control.Monad
|
||||
import Control.Arrow
|
||||
|
||||
*Main> map (ap (,) (flip elemIndex haystack)) needles
|
||||
[("Washington",Nothing),("Bush",Just 4)]
|
||||
12
Task/Search-a-list/Java/search-a-list-1.java
Normal file
12
Task/Search-a-list/Java/search-a-list-1.java
Normal 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);
|
||||
}
|
||||
11
Task/Search-a-list/Java/search-a-list-2.java
Normal file
11
Task/Search-a-list/Java/search-a-list-2.java
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
String[] haystack = {"Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo"};
|
||||
|
||||
OUTERLOOP:
|
||||
for (String needle : new String[]{"Washington","Bush"}) {
|
||||
for (int i = 0; i < haystack.length; i++)
|
||||
if (needle.equals(haystack[i])) {
|
||||
System.out.println(i + " " + needle);
|
||||
continue OUTERLOOP;
|
||||
}
|
||||
System.out.println(needle + " is not in haystack");
|
||||
}
|
||||
16
Task/Search-a-list/JavaScript/search-a-list-1.js
Normal file
16
Task/Search-a-list/JavaScript/search-a-list-1.js
Normal 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"
|
||||
}
|
||||
18
Task/Search-a-list/JavaScript/search-a-list-2.js
Normal file
18
Task/Search-a-list/JavaScript/search-a-list-2.js
Normal 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
|
||||
}
|
||||
}
|
||||
7
Task/Search-a-list/Lua/search-a-list.lua
Normal file
7
Task/Search-a-list/Lua/search-a-list.lua
Normal 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
|
||||
9
Task/Search-a-list/PHP/search-a-list.php
Normal file
9
Task/Search-a-list/PHP/search-a-list.php
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
$haystack = array("Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo");
|
||||
|
||||
foreach (array("Washington","Bush") as $needle) {
|
||||
$i = array_search($needle, $haystack);
|
||||
if ($i === FALSE) // note: 0 is also considered false in PHP, so you need to specifically check for FALSE
|
||||
echo "$needle is not in haystack\n";
|
||||
else
|
||||
echo "$i $needle\n";
|
||||
}
|
||||
13
Task/Search-a-list/Perl/search-a-list-1.pl
Normal file
13
Task/Search-a-list/Perl/search-a-list-1.pl
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
use List::Util qw(first);
|
||||
|
||||
my @haystack = qw(Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo);
|
||||
|
||||
foreach my $needle (qw(Washington Bush)) {
|
||||
my $index = first { $haystack[$_] eq $needle } (0 .. $#haystack); # note that "eq" was used because we are comparing strings
|
||||
# you would use "==" for numbers
|
||||
if (defined $index) {
|
||||
print "$index $needle\n";
|
||||
} else {
|
||||
print "$needle is not in haystack\n";
|
||||
}
|
||||
}
|
||||
13
Task/Search-a-list/Perl/search-a-list-2.pl
Normal file
13
Task/Search-a-list/Perl/search-a-list-2.pl
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
use List::MoreUtils qw(first_index);
|
||||
|
||||
my @haystack = qw(Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo);
|
||||
|
||||
foreach my $needle (qw(Washington Bush)) {
|
||||
my $index = first_index { $_ eq $needle } @haystack; # note that "eq" was used because we are comparing strings
|
||||
# you would use "==" for numbers
|
||||
if (defined $index) {
|
||||
print "$index $needle\n";
|
||||
} else {
|
||||
print "$needle is not in haystack\n";
|
||||
}
|
||||
}
|
||||
13
Task/Search-a-list/Perl/search-a-list-3.pl
Normal file
13
Task/Search-a-list/Perl/search-a-list-3.pl
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
my @haystack = qw(Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo);
|
||||
|
||||
my %haystack_indices;
|
||||
@haystack_indices{ @haystack } = (0 .. $#haystack); # Caution: this finds the largest index, not the smallest
|
||||
|
||||
foreach my $needle (qw(Washington Bush)) {
|
||||
my $index = $haystack_indices{$needle};
|
||||
if (defined $index) {
|
||||
print "$index $needle\n";
|
||||
} else {
|
||||
print "$needle is not in haystack\n";
|
||||
}
|
||||
}
|
||||
10
Task/Search-a-list/PicoLisp/search-a-list.l
Normal file
10
Task/Search-a-list/PicoLisp/search-a-list.l
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
(de lastIndex (Item Lst)
|
||||
(- (length Lst) (index Item (reverse Lst)) -1) )
|
||||
|
||||
(de findNeedle (Fun Sym Lst)
|
||||
(prinl Sym " " (or (Fun Sym Lst) "not found")) )
|
||||
|
||||
(let Lst '(Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo)
|
||||
(findNeedle index 'Washington Lst)
|
||||
(findNeedle index 'Bush Lst)
|
||||
(findNeedle lastIndex 'Bush Lst) )
|
||||
23
Task/Search-a-list/Prolog/search-a-list.pro
Normal file
23
Task/Search-a-list/Prolog/search-a-list.pro
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
search_a_list(N1, N2) :-
|
||||
L = ["Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie", "Bush", "Boz", "Zag"],
|
||||
|
||||
write('List is :'), maplist(my_write, L), nl, nl,
|
||||
|
||||
( nth1(Ind1, L, N1) ->
|
||||
format('~s is in position ~w~n', [N1, Ind1])
|
||||
; format('~s is not present~n', [N1])),
|
||||
( nth1(Ind2, L, N2) ->
|
||||
format('~s is in position ~w~n', [N2, Ind2])
|
||||
; format('~s is not present~n', [N2])),
|
||||
( reverse_nth1(Ind3, L, N1) ->
|
||||
format('~s last position is ~w~n', [N1, Ind3])
|
||||
; format('~s is not present~n', [N1])).
|
||||
|
||||
reverse_nth1(Ind, L, N) :-
|
||||
reverse(L, RL),
|
||||
length(L, Len),
|
||||
nth1(Ind1, RL, N),
|
||||
Ind is Len - Ind1 + 1.
|
||||
|
||||
my_write(Name) :-
|
||||
writef(' %s', [Name]).
|
||||
7
Task/Search-a-list/Python/search-a-list-1.py
Normal file
7
Task/Search-a-list/Python/search-a-list-1.py
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
haystack=["Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo"]
|
||||
|
||||
for needle in ("Washington","Bush"):
|
||||
try:
|
||||
print haystack.index(needle), needle
|
||||
except ValueError, value_error:
|
||||
print needle,"is not in haystack"
|
||||
9
Task/Search-a-list/Python/search-a-list-2.py
Normal file
9
Task/Search-a-list/Python/search-a-list-2.py
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
>>> haystack=["Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo"]
|
||||
>>> haystack.index('Bush')
|
||||
4
|
||||
>>> haystack.index('Washington')
|
||||
Traceback (most recent call last):
|
||||
File "<pyshell#95>", line 1, in <module>
|
||||
haystack.index('Washington')
|
||||
ValueError: list.index(x): x not in list
|
||||
>>>
|
||||
13
Task/Search-a-list/Python/search-a-list-3.py
Normal file
13
Task/Search-a-list/Python/search-a-list-3.py
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
>>> def hi_index(needle, haystack):
|
||||
return len(haystack)-1 - haystack[::-1].index(needle)
|
||||
|
||||
>>> # Lets do some checks
|
||||
>>> for n in haystack:
|
||||
hi = hi_index(n, haystack)
|
||||
assert haystack[hi] == n, "Hi index is of needle"
|
||||
assert n not in haystack[hi+1:], "No higher index exists"
|
||||
if haystack.count(n) == 1:
|
||||
assert hi == haystack.index(n), "index == hi_index if needle occurs only once"
|
||||
|
||||
|
||||
>>>
|
||||
6
Task/Search-a-list/R/search-a-list-1.r
Normal file
6
Task/Search-a-list/R/search-a-list-1.r
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
find.needle <- function(haystack, needle="needle", return.last.index.too=FALSE)
|
||||
{
|
||||
indices <- which(haystack %in% needle)
|
||||
if(length(indices)==0) stop("no needles in the haystack")
|
||||
if(return.last.index.too) range(indices) else min(indices)
|
||||
}
|
||||
8
Task/Search-a-list/R/search-a-list-2.r
Normal file
8
Task/Search-a-list/R/search-a-list-2.r
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
haystack1 <- c("where", "is", "the", "needle", "I", "wonder")
|
||||
haystack2 <- c("no", "sewing", "equipment", "in", "here")
|
||||
haystack3 <- c("oodles", "of", "needles", "needles", "needles", "in", "here")
|
||||
|
||||
find.needle(haystack1) # 4
|
||||
find.needle(haystack2) # error
|
||||
find.needle(haystack3) # 3
|
||||
find.needle(haystack3, needle="needles", ret=TRUE) # 3 5
|
||||
30
Task/Search-a-list/REXX/search-a-list-1.rexx
Normal file
30
Task/Search-a-list/REXX/search-a-list-1.rexx
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
/*REXX program searches a collection of strings. */
|
||||
hay.= /*initialize haystack collection.*/
|
||||
hay.1 = 'sodium'
|
||||
hay.2 = 'phosphorous'
|
||||
hay.3 = 'californium'
|
||||
hay.4 = 'copernicium'
|
||||
hay.5 = 'gold'
|
||||
hay.6 = 'thallium'
|
||||
hay.7 = 'carbon'
|
||||
hay.8 = 'silver'
|
||||
hay.9 = 'curium'
|
||||
hay.10 = 'copper'
|
||||
hay.11 = 'helium'
|
||||
hay.12 = 'sulfur'
|
||||
|
||||
needle='gold' /*we'll be looking for the gold. */
|
||||
upper needle /*in case some people capitalize.*/
|
||||
found=0 /*assume needle isn't found yet. */
|
||||
|
||||
do j=1 while hay.j\=='' /*keep looking in haystack. */
|
||||
_=hay.j; upper _ /*make it uppercase to be safe. */
|
||||
if _=needle then do /*we've found needle in haystack.*/
|
||||
found=1 /*indicate that needle was found,*/
|
||||
leave /* and stop looking, of course. */
|
||||
end
|
||||
end /*j*/
|
||||
|
||||
if found then return j /*return haystack index number. */
|
||||
else say needle "wasn't found in the haystack!"
|
||||
return 0 /*indicates needle wasn't found. */
|
||||
44
Task/Search-a-list/REXX/search-a-list-2.rexx
Normal file
44
Task/Search-a-list/REXX/search-a-list-2.rexx
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
/*REXX program searches a collection of strings. */
|
||||
hay.0=1000 /*safely indicate highest item #.*/
|
||||
hay.200 = 'binilnilium'
|
||||
hay.98 = 'californium'
|
||||
hay.6 = 'carbon'
|
||||
hay.112 = 'copernicium'
|
||||
hay.29 = 'copper'
|
||||
hay.114 = 'flerovium'
|
||||
hay.79 = 'gold'
|
||||
hay.2 = 'helium'
|
||||
hay.1 = 'hydrogen'
|
||||
hay.82 = 'lead'
|
||||
hay.116 = 'livermorium'
|
||||
hay.15 = 'phosphorous'
|
||||
hay.47 = 'silver'
|
||||
hay.11 = 'sodium'
|
||||
hay.16 = 'sulfur'
|
||||
hay.81 = 'thallium'
|
||||
hay.92 = 'uranium'
|
||||
|
||||
needle = 'gold' /*we'll be looking for the gold. */
|
||||
upper needle /*in case some people capitalize.*/
|
||||
found=0 /*assume needle isn't found, yet.*/
|
||||
|
||||
do j=1 for hay.0 /*start looking in haystack item1*/
|
||||
_=hay.j; upper _ /*make it uppercase to be safe. */
|
||||
if _=needle then do /*we've found needle in haystack.*/
|
||||
found=1 /*indicate that needle was found,*/
|
||||
leave /* and stop looking, of course. */
|
||||
end
|
||||
end /*j*/
|
||||
|
||||
if found then return j /*return haystack index number. */
|
||||
else say needle "wasn't found in the haystack!"
|
||||
return 0 /*indicates needle wasn't found. */
|
||||
|
||||
/*─────────────────────────────────────────────── incidentally, to find */
|
||||
/* the number of haystack items: */
|
||||
hayItems=0
|
||||
|
||||
do k=1 for hay.0 /*find item AFTER the last item.*/
|
||||
if hay.k\=='' then hayItems=hayItems+1 /*bump the item counter.*/
|
||||
end /*k*/
|
||||
/*stick a fork in it, we're done.*/
|
||||
29
Task/Search-a-list/REXX/search-a-list-3.rexx
Normal file
29
Task/Search-a-list/REXX/search-a-list-3.rexx
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
/*REXX program searches a collection of strings. */
|
||||
hay.=0 /*initialize haystack collection.*/
|
||||
hay._sodium = 1
|
||||
hay._phosphorous = 1
|
||||
hay._califonium = 1
|
||||
hay._copernicium = 1
|
||||
hay._gold = 1
|
||||
hay._thallium = 1
|
||||
hay._carbon = 1
|
||||
hay._silver = 1
|
||||
hay._copper = 1
|
||||
hay._helium = 1
|
||||
hay._sulfur = 1
|
||||
/*underscores (_) are used to NOT*/
|
||||
/* conflict with variable names.*/
|
||||
|
||||
needle = 'gold' /*we'll be looking for the gold. */
|
||||
|
||||
Xneedle = '_'needle /*prefix an underscore (_) char. */
|
||||
upper Xneedle /*uppercase: how REXX stores 'em.*/
|
||||
|
||||
/*alternative version of above, */
|
||||
/* Xneedle=translate('_'needle)*/
|
||||
|
||||
found=hay.Xneedle /*this is it, it's found or not.*/
|
||||
|
||||
if found then return j /*return haystack index number. */
|
||||
else say needle "wasn't found in the haystack!"
|
||||
return 0 /*indicates needle wasn't found. */
|
||||
24
Task/Search-a-list/REXX/search-a-list-4.rexx
Normal file
24
Task/Search-a-list/REXX/search-a-list-4.rexx
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
/*REXX program searches a collection of strings. */
|
||||
|
||||
haystack=, /*names of the first 200 elements of the periodic table*/
|
||||
'hydrogen helium lithium berylliumbon nitrogen oxygen fluorine neon sodium magnesium aluminum silicon phosphorous sulfur chlorine argon potassium calcium scandium titanium',
|
||||
'vanadium chromium manganese iron kel copper zinc gallium germanium arsenic selenium bromine krypton rubidium strontium yttrium zirconium niobium molybdenum technetium ruthenium',
|
||||
'rhodium palladium silver cadmium antimony tellurium iodine xenon cesium barium lanthanum cerium praseodymium neodymium promethium samarium europium gadolinium terbium dysprosium',
|
||||
'holmium erbium thulium ytterbium afnium tantalum tungsten rhenium osmium irdium platinum gold mercury thallium lead bismuth polonium astatine radon francium radium actinium',
|
||||
'thorium protactinium uranium neptonium americium curium berkelium californium einsteinum fermium mendelevium nobelium lawrencium rutherfordium dubnium seaborgium bohrium hassium',
|
||||
'meitnerium darmstadtium roentgenicium ununtrium flerovium ununpentium livermorium ununseptium ununoctium ununennium unbinilium unbiunium unbibium unbitrium unbiquadium',
|
||||
'unbipentium unbihexium unbiseptiuum unbiennium untrinilium untriunium untribium untritrium untriquadium untripentium untrihexium untriseptium untrioctium untriennium unquadnilium',
|
||||
'unquadunium unquadbium unquadtriuadium unquadpentium unquadhexium unquadseptium unquadoctium unquadennium unpentnilium unpentunium unpentbium unpenttrium unpentquadium',
|
||||
'unpentpentium unpenthexium unpentpentoctium unpentennium unhexnilium unhexunium unhexbium unhextrium unhexquadium unhexpentium unhexhexium unhexseptium unhexoctium unhexennium',
|
||||
'unseptnilium unseptunium unseptbirium unseptquadium unseptpentium unsepthexium unseptseptium unseptoctium unseptennium unoctnilium unoctunium unoctbium unocttrium unoctquadium',
|
||||
'unoctpentium unocthexium unoctsepoctium unoctennium unennilium unennunium unennbium unenntrium unennquadium unennpentium unennhexium unennseptium unennoctium unennennium binilnilium'
|
||||
|
||||
needle = 'gold' /*we'll be looking for the gold. */
|
||||
|
||||
upper needle haystack /*in case some people capitalize.*/
|
||||
|
||||
idx=wordpos(needle,haystack) /*use REXX's bif: WORDPOS */
|
||||
/* bif: built-in function.*/
|
||||
if idx\==0 then return idx /*return haystack index number. */
|
||||
else say needle "wasn't found in the haystack!"
|
||||
return 0 /*indicates needle wasn't found. */
|
||||
4
Task/Search-a-list/Racket/search-a-list-1.rkt
Normal file
4
Task/Search-a-list/Racket/search-a-list-1.rkt
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
(define (index xs y)
|
||||
(for/first ([(x i) (in-indexed xs)]
|
||||
#:when (equal? x y))
|
||||
i))
|
||||
4
Task/Search-a-list/Racket/search-a-list-2.rkt
Normal file
4
Task/Search-a-list/Racket/search-a-list-2.rkt
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
(define (index-last xs y)
|
||||
(for/last ([(x i) (in-indexed xs)]
|
||||
#:when (equal? x y))
|
||||
i))
|
||||
7
Task/Search-a-list/Racket/search-a-list-3.rkt
Normal file
7
Task/Search-a-list/Racket/search-a-list-3.rkt
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
(define haystack '("Zig" "Zag" "Wally" "Ronald" "Bush" "Krusty" "Charlie" "Bush" "Bozo"))
|
||||
|
||||
(for/list ([needle '("Bender" "Bush")])
|
||||
(index haystack needle))
|
||||
|
||||
(for/list ([needle '("Bender" "Bush")])
|
||||
(index-last haystack needle))
|
||||
9
Task/Search-a-list/Ruby/search-a-list-1.rb
Normal file
9
Task/Search-a-list/Ruby/search-a-list-1.rb
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
haystack = %w(Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo)
|
||||
|
||||
%w(Bush Washington).each do |needle|
|
||||
if (i = haystack.index(needle))
|
||||
print i, " ", needle, "\n"
|
||||
else
|
||||
raise "#{needle} is not in haystack\n"
|
||||
end
|
||||
end
|
||||
7
Task/Search-a-list/Ruby/search-a-list-2.rb
Normal file
7
Task/Search-a-list/Ruby/search-a-list-2.rb
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
haystack.each do |item|
|
||||
last = haystack.rindex(item)
|
||||
if last > haystack.index(item)
|
||||
puts "#{item} last appears at index #{last}"
|
||||
break
|
||||
end
|
||||
end
|
||||
3
Task/Search-a-list/Ruby/search-a-list-3.rb
Normal file
3
Task/Search-a-list/Ruby/search-a-list-3.rb
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
multi_item = haystack .each_with_index .group_by {|elem, idx| elem} .find {|key, val| val.length > 1}
|
||||
# multi_item is => ["Bush", [["Bush", 4], ["Bush", 7]]]
|
||||
puts "#{multi_item[0]} last appears at index #{multi_item[1][-1][1]}" unless multi_item.nil?
|
||||
14
Task/Search-a-list/Sather/search-a-list.sa
Normal file
14
Task/Search-a-list/Sather/search-a-list.sa
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
class MAIN is
|
||||
main is
|
||||
haystack :ARRAY{STR} := |"Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie", "Bush", "Bozo"|;
|
||||
needles :ARRAY{STR} := | "Washington", "Bush" |;
|
||||
loop needle ::= needles.elt!;
|
||||
index ::= haystack.index_of(needle);
|
||||
if index < 0 then
|
||||
#OUT + needle + " is not in the haystack\n";
|
||||
else
|
||||
#OUT + index + " " + needle + "\n";
|
||||
end;
|
||||
end;
|
||||
end;
|
||||
end;
|
||||
3
Task/Search-a-list/Scala/search-a-list.scala
Normal file
3
Task/Search-a-list/Scala/search-a-list.scala
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
def findNeedles(needle: String, haystack: Seq[String]) = haystack.zipWithIndex.filter(_._1 == needle).map(_._2)
|
||||
def firstNeedle(needle: String, haystack: Seq[String]) = findNeedles(needle, haystack).head
|
||||
def lastNeedle(needle: String, haystack: Seq[String]) = findNeedles(needle, haystack).last
|
||||
16
Task/Search-a-list/Scheme/search-a-list.ss
Normal file
16
Task/Search-a-list/Scheme/search-a-list.ss
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
(define haystack
|
||||
'("Zig" "Zag" "Wally" "Ronald" "Bush" "Krusty" "Charlie" "Bush" "Bozo"))
|
||||
|
||||
(define index-of
|
||||
(lambda (needle hackstack)
|
||||
(let ((tail (member needle haystack)))
|
||||
(if tail
|
||||
(- (length haystack) (length tail))
|
||||
(throw 'needle-missing)))))
|
||||
|
||||
(define last-index-of
|
||||
(lambda (needle hackstack)
|
||||
(let ((tail (member needle (reverse haystack))))
|
||||
(if tail
|
||||
(- (length tail) 1)
|
||||
(throw 'needle-missing)))))
|
||||
14
Task/Search-a-list/Smalltalk/search-a-list.st
Normal file
14
Task/Search-a-list/Smalltalk/search-a-list.st
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
| haystack |
|
||||
haystack :=
|
||||
'Zig,Zag,Wally,Ronald,Bush,Krusty,Charlie,Bush,Bozo' subStrings: $,.
|
||||
{ 'Washington' . 'Bush' } do: [:i|
|
||||
|t l|
|
||||
t := (haystack indexOf: i).
|
||||
(t = 0) ifTrue: [ ('%1 is not in the haystack' % { i }) displayNl ]
|
||||
ifFalse: [ ('%1 is at index %2' % { i . t }) displayNl.
|
||||
l := ( (haystack size) - (haystack reverse indexOf: i) + 1 ).
|
||||
( t = l ) ifFalse: [
|
||||
('last occurence of %1 is at index %2' %
|
||||
{ i . l }) displayNl ]
|
||||
]
|
||||
].
|
||||
8
Task/Search-a-list/Tcl/search-a-list-1.tcl
Normal file
8
Task/Search-a-list/Tcl/search-a-list-1.tcl
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
set haystack {Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo}
|
||||
foreach needle {Bush Washington} {
|
||||
if {[set idx [lsearch -exact $haystack $needle]] == -1} {
|
||||
error "$needle does not appear in the haystack"
|
||||
} else {
|
||||
puts "$needle appears at index $idx in the haystack"
|
||||
}
|
||||
}
|
||||
9
Task/Search-a-list/Tcl/search-a-list-2.tcl
Normal file
9
Task/Search-a-list/Tcl/search-a-list-2.tcl
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
set haystack {Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo}
|
||||
foreach needle {Bush Washington} {
|
||||
set indices [lsearch -all -exact $haystack $needle]
|
||||
if {[llength $indices] == 0} {
|
||||
error "$needle does not appear in the haystack"
|
||||
} else {
|
||||
puts "$needle appears first at index [lindex $indices 0] and last at [lindex $indices end]"
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue