Search a list
You are encouraged to solve this task according to the task description, using any language you may know.
Find the index of a string (needle) in an array of strings (haystack), or else raise an exception if the needle is missing. If there is more then one occurrence then return smallest i such that haystack[i] = needle.
ALGOL 68
With FORMAT value error exception
FORMAT haystack := $c("Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo")$; []STRING needles = ("Washington","Bush"); 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 ); 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(haystack, needle), needle)); end on value error; value error: printf(($g" "gl$,needle, "is not in haystack")); end on value error: reset(needle exception) OD
Output:
Washington is not in haystack 4 Bush
Manual FOR loop - no exception
[]STRING haystack = ("Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo"); PROC index = ([]STRING haystack, STRING needle)INT:( INT index; FOR i FROM LWB haystack TO UPB haystack DO index := i; IF haystack[index] = needle THEN found FI OD; LWB haystack - 1 # not found # EXIT found: index ); []STRING needles = ("Washington","Bush"); FOR i TO UPB needles DO STRING needle := needles[i]; INT result = index(haystack, needle); IF result >= LWB haystack THEN printf(($d" "gl$, result, needle)) ELSE printf(($g" "gl$,needle, "is not in haystack")) FI OD
Output:
Washington is not in haystack 5 Bush
Java
for Lists, they have an indexOf() method: <java>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);
}</java>
for arrays, you have to do it manually: <java>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");
}</java> Output:
Washington is not in haystack 4 Bush
Python
<python> 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"
</python> Output:
Washington is not in haystack 4 Bush