How to resolve the algorithm Search a list step by step in the Icon and Unicon programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Search a list step by step in the Icon and Unicon programming language
Table of Contents
Problem Statement
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. Return the largest index to a needle that has multiple occurrences in the haystack.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Search a list step by step in the Icon and Unicon programming language
Source code in the icon programming language
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
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
You may also check:How to resolve the algorithm Yellowstone sequence step by step in the jq programming language
You may also check:How to resolve the algorithm Here document step by step in the SequenceL programming language
You may also check:How to resolve the algorithm Comments step by step in the Perl programming language
You may also check:How to resolve the algorithm Disarium numbers step by step in the Go programming language
You may also check:How to resolve the algorithm Priority queue step by step in the Rust programming language