2016 Update

This commit is contained in:
Tina Müller 2016-12-05 22:15:40 +01:00
parent 948b86eafa
commit dcf5d15da3
7965 changed files with 139854 additions and 31002 deletions

View file

@ -1,4 +1,17 @@
Find the index of a string (needle) in an indexable, ordered collection of strings (haystack). Raise an exception if the needle is missing.
{{task heading}}
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.
{{task heading|Extra credit}}
Return the largest index to a needle that has multiple occurrences in the haystack.
{{task heading|See also}}
* [[Search a list of records]]
<hr>

View file

@ -0,0 +1,106 @@
/* new c++-11 features
* list class
* initialization strings
* auto typing
* lambda functions
* noexcept
* find
* for/in loop
*/
#include <iostream> // std::cout, std::endl
#include <algorithm> // std::find
#include <list> // std::list
#include <vector> // std::vector
#include <string> // string::basic_string
using namespace std; // saves typing of "std::" before everything
int main()
{
// initialization lists
// create objects and fully initialize them with given values
list<string> l { "Zig", "Zag", "Wally", "Homer", "Madge",
"Watson", "Ronald", "Bush", "Krusty", "Charlie",
"Bush", "Bush", "Boz", "Zag" };
list<string> n { "Bush" , "Obama", "Homer", "Sherlock" };
// lambda function with auto typing
// auto is easier to write than looking up the compicated
// specialized iterator type that is actually returned.
// Just know that it returns an iterator for the list at the position found,
// or throws an exception if s in not in the list.
// runtime_error is used because it can be initialized with a message string.
auto contains = [](list<string> l, string s) throw(runtime_error)
{
auto r = find(begin(l), end(l), s );
if ( r == end(l) ) throw runtime_error( s + " not found" );
return r;
};
// returns an int vector with the indexes of the search string
// The & is a "default capture" meaning that it "allows in"
// the variables that are in scope where it is called by their
// name to simplify things.
auto index = [&](list<string> l, string s) noexcept
{
vector<int> index_v;
int idx = 0;
for(auto& r : l)
{
if ( s.compare(r) == 0 ) index_v.push_back(idx); // match -- add to vector
idx++;
}
// even though index_v is local to the lambda function,
// c++11 move semantics does what you want and returns it
// live and intact instead of destroying it or returning a copy.
// (very efficient for large objects!)
return index_v;
};
// for/in loop
for (const string& s : n) // new iteration syntax is simple and intuitive
{
try
{
auto cont = contains( l , s); // checks if there is any match
vector<int> vf = index( l, s );
cout << "l contains: " << s << " at " ;
for (auto x : vf)
{ cout << x << " "; } // if vector is empty this doesn't run
cout << endl ;
}
catch (const runtime_error& r) // string not found
{
cout << r.what() << endl;
continue; // try next string
}
} //for
return 0;
} // main
/* end */

View file

@ -0,0 +1,17 @@
#import system.
#import system'routines.
#import extensions.
#symbol program =
[
#var haystack := ("Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie", "Bush", "Bozo").
("Washington", "Bush") run &each: needle
[
#var index := haystack indexOf:needle.
(index == -1)
? [ console writeLine:needle:" is not in haystack" ]
! [ console writeLine:index:" ":needle ].
].
].

View file

@ -0,0 +1,26 @@
NotFound := Exception clone
List firstIndex := method(obj,
indexOf(obj) ifNil(NotFound raise)
)
List lastIndex := method(obj,
reverseForeach(i,v,
if(v == obj, return i)
)
NotFound raise
)
haystack := list("Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo")
list("Washington","Bush") foreach(needle,
try(
write("firstIndex(\"",needle,"\"): ")
writeln(haystack firstIndex(needle))
)catch(NotFound,
writeln(needle," is not in haystack")
)pass
try(
write("lastIndex(\"",needle,"\"): ")
writeln(haystack lastIndex(needle))
)catch(NotFound,
writeln(needle," is not in haystack")
)pass
)

View file

@ -0,0 +1,5 @@
my @haystack = <Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo>;
for <Washington Bush> -> $needle {
say "$needle -- { @haystack.first($needle, :k) // 'not in haystack' }";
}

View file

@ -0,0 +1,13 @@
my Str @haystack = <Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo>;
for <Washingston Bush> -> $needle {
my $first = @haystack.first($needle, :k);
if defined $first {
my $last = @haystack.first($needle, :k, :end);
say "$needle -- first at $first, last at $last";
}
else {
say "$needle -- not in haystack";
}
}

View file

@ -0,0 +1,8 @@
my @haystack = <Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo>;
my %index;
%index{.value} //= .key for @haystack.pairs;
for <Washington Bush> -> $needle {
say "$needle -- { %index{$needle} // 'not in haystack' }";
}

View file

@ -1,20 +0,0 @@
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,57 @@
function Find-Needle
{
[CmdletBinding()]
[OutputType([int])]
Param
(
[Parameter(Mandatory=$true, Position=0)]
[string]
$Needle,
[Parameter(Mandatory=$true, Position=1)]
[string[]]
$Haystack,
[switch]
$LastIndex
)
if ($LastIndex)
{
$index = [Array]::LastIndexOf($Haystack,$Needle)
if ($index -eq -1)
{
Write-Verbose "Needle not found in Haystack"
return $index
}
if ((($Haystack | Group-Object | Where-Object Count -GT 1).Group).IndexOf($Needle) -ne -1)
{
Write-Verbose "Last needle found in Haystack at index $index"
}
else
{
Write-Verbose "Needle found in Haystack at index $index (No duplicates were found)"
}
return $index
}
else
{
$index = [Array]::IndexOf($Haystack,$Needle)
if ($index -eq -1)
{
Write-Verbose "Needle not found in Haystack"
}
else
{
Write-Verbose "Needle found in Haystack at index $index"
}
return $index
}
}
$haystack = @("word", "phrase", "preface", "title", "house", "line", "chapter", "page", "book", "house")

View file

@ -0,0 +1 @@
Find-Needle "house" $haystack

View file

@ -0,0 +1 @@
Find-Needle "house" $haystack -Verbose

View file

@ -0,0 +1 @@
Find-Needle "house" $haystack -LastIndex -Verbose

View file

@ -0,0 +1 @@
Find-Needle "title" $haystack -LastIndex -Verbose

View file

@ -0,0 +1 @@
Find-Needle "something" $haystack -Verbose

View file

@ -1,5 +1,5 @@
/*REXX program searches a collection of strings. */
hay.= /*initialize haystack collection.*/
/*REXX program searches a collection of strings (an array of periodic table elements).*/
hay.= /*initialize the haystack collection. */
hay.1 = 'sodium'
hay.2 = 'phosphorous'
hay.3 = 'californium'
@ -13,18 +13,17 @@ 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. */
needle = 'gold' /*we'll be looking for the gold. */
upper needle /*in case some people capitalize stuff.*/
found=0 /*assume the 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. */
do j=1 while hay.j\=='' /*keep looking in the haystack. */
_=hay.j; upper _ /*make it uppercase to be safe. */
if _=needle then do; found=1 /*we've found the needle in haystack. */
leave /* ··· and stop looking, of course. */
end
end /*j*/
if found then return j /*return haystack index number. */
if found then return j /*return the haystack index number. */
else say needle "wasn't found in the haystack!"
return 0 /*indicates needle wasn't found. */
return 0 /*indicates the needle wasn't found. */

View file

@ -1,6 +1,6 @@
/*REXX program searches a collection of strings. */
hay.0=1000 /*safely indicate highest item #.*/
hay.200 = 'binilnilium'
/*REXX program searches a collection of strings (an array of periodic table elements).*/
hay.0 = 1000 /*safely indicate highest item number. */
hay.200 = 'Binilnilium'
hay.98 = 'californium'
hay.6 = 'carbon'
hay.112 = 'copernicium'
@ -17,28 +17,18 @@ hay.11 = 'sodium'
hay.16 = 'sulfur'
hay.81 = 'thallium'
hay.92 = 'uranium'
/* [↑] sorted by the element name. */
needle = 'gold' /*we'll be looking for the gold. */
upper needle /*in case some people capitalize. */
found=0 /*assume the needle isn't found (yet).*/
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. */
do j=1 for hay.0 /*start looking in haystack, item 1. */
_=hay.j; upper _ /*make it uppercase just to be safe. */
if _=needle then do; found=1 /*we've found the needle in haystack. */
leave /* ··· and stop looking, of course. */
end
end /*j*/
if found then return j /*return haystack index number. */
if found then return j /*return the 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.*/
return 0 /*indicates the needle wasn't found. */

View file

@ -1,29 +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.*/
/*REXX program searches a collection of strings (an array of periodic table elements).*/
hay.=0 /*initialize the haystack collection. */
hay._sodium = 1
hay._phosphorous = 1
hay._californium = 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. */
needle = 'gold' /*we'll be looking for the gold. */
Xneedle = '_'needle /*prefix an underscore (_) char. */
upper Xneedle /*uppercase: how REXX stores 'em.*/
Xneedle = '_'needle /*prefix an underscore (_) character. */
upper Xneedle /*uppercase: how REXX stores them. */
/*alternative version of above, */
/* Xneedle=translate('_'needle)*/
/*alternative version of above: */
/* Xneedle=translate('_'needle) */
found=hay.Xneedle /*this is it, it's found or not.*/
found=hay.Xneedle /*this is it, it's found (or maybe not)*/
if found then return j /*return haystack index number. */
if found then return j /*return the haystack index number. */
else say needle "wasn't found in the haystack!"
return 0 /*indicates needle wasn't found. */
return 0 /*indicates the needle wasn't found. */

View file

@ -1,24 +1,21 @@
/*REXX program searches a collection of strings. */
/*REXX program searches a collection of strings (an array of periodic table elements).*/
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'
haystack=, /*names of the first 200 elements of the periodic table*/
'hydrogen helium lithium beryllium boron carbon nitrogen oxygen fluorine neon sodium magnesium aluminum silicon phosphorous sulfur chlorine argon potassium calcium scandium titanium',
'vanadium chromium manganese iron cobalt nickel copper zinc gallium germanium arsenic selenium bromine krypton rubidium strontium yttrium zirconium niobium molybdenum technetium ruthenium',
'rhodium palladium silver cadmium indium tin antimony tellurium iodine xenon cesium barium lanthanum cerium praseodymium neodymium promethium samarium europium gadolinium terbium dysprosium',
'holmium erbium thulium ytterbium lutetium hafnium tantalum tungsten rhenium osmium iridium platinum gold mercury thallium lead bismuth polonium astatine radon francium radium actinium',
'thorium protactinium uranium neptunium plutonium americium curium berkelium californium einsteinium fermium mendelevium nobelium lawrencium rutherfordium dubnium seaborgium bohrium hassium',
'meitnerium darmstadtium roentgenium copernicium Ununtrium flerovium Ununpentium livermorium Ununseptium Ununoctium Ununennium Unbinilium Unbiunium Unbibium Unbitrium Unbiquadium',
'Unbipentium Unbihexium Unbiseptium Unbioctium Unbiennium Untrinilium Untriunium Untribium Untritrium Untriquadium Untripentium Untrihexium Untriseptium Untrioctium Untriennium Unquadnilium',
'Unquadunium Unquadbium Unquadtrium Unquadquadium Unquadpentium Unquadhexium Unquadseptium Unquadoctium Unquadennium Unpentnilium Unpentunium Unpentbium Unpenttrium Unpentquadium',
'Unpentpentium Unpenthexium Unpentseptium Unpentoctium Unpentennium Unhexnilium Unhexunium Unhexbium Unhextrium Unhexquadium Unhexpentium Unhexhexium Unhexseptium Unhexoctium Unhexennium',
'Unseptnilium Unseptunium Unseptbium Unsepttrium Unseptquadium Unseptpentium Unsepthexium Unseptseptium Unseptoctium Unseptennium Unoctnilium Unoctunium Niobium Unocttrium Unoctquadium',
'Unoctpentium Unocthexium Unoctseptium Unoctoctium 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. */
needle = 'gold' /*we'll be looking for the gold. */
upper needle haystack /*in case some people capitalize stuff. */
idx=wordpos(needle,haystack) /*use REXX's BIF: WORDPOS */
if idx\==0 then return idx /*return the haystack index number. */
else say needle "wasn't found in the haystack!"
return 0 /*indicates needle wasn't found. */
return 0 /*indicates the needle wasn't found. */