How to resolve the algorithm Search a list step by step in the Picat programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Search a list step by step in the Picat 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 Picat programming language

Source code in the picat programming language

import util.

go =>
  Haystack=["Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Bush", "Charlie", "Bush", "Boz", "Zag"],

  println("First 'Bush'"=search_list(Haystack,"Bush")),
  println("Last 'Bush'"=search_list_last(Haystack,"Bush")),

  println("All 'Bush'"=search_list_all(Haystack,"Bush")),

  catch(WaldoIx=search_list(Haystack,"Waldo"),E,println(E)),
  println("Waldo"=WaldoIx),

  nl.

% Wrapping find_first_of/2 and find_last_of/2 with exceptions
search_list(Haystack,Needle) = Ix =>
  Ix = find_first_of(Haystack,Needle),
  if Ix < 0 then
    throw $error(search_list(Needle),not_found)
  end.

search_list_last(Haystack,Needle) = Ix =>
  Ix = find_last_of(Haystack,Needle),
  if Ix < 0 then
    throw $error(search_list_last(Needle),not_found)
  end.

% Find all indices
search_list_all(Haystack,Needle) = Ixs =>
  Ixs = [Ix : {W,Ix} in zip(Haystack,1..Haystack.len), W == Needle],
  if Ixs == [] then
    throw $error(search_list_all(Needle),not_found)
  end.

  

You may also check:How to resolve the algorithm Find the missing permutation step by step in the Maple programming language
You may also check:How to resolve the algorithm Rock-paper-scissors step by step in the Erlang programming language
You may also check:How to resolve the algorithm Conditional structures step by step in the C++ programming language
You may also check:How to resolve the algorithm Execute HQ9+ step by step in the Delphi programming language
You may also check:How to resolve the algorithm Comments step by step in the Swift programming language