Jump to content

Search a list: Difference between revisions

m
(Dialects of BASIC moved to the BASIC section.)
(Added Odin variant)
m ((Dialects of BASIC moved to the BASIC section.))
Line 408:
Word to search for? (Leave blank to exit)
</pre>
 
==={{header|BBC BASIC}}===
{{works with|BBC BASIC for Windows}}
<syntaxhighlight lang="bbcbasic"> DIM haystack$(27)
haystack$() = "alpha","bravo","charlie","delta","echo","foxtrot","golf", \
\ "hotel","india","juliet","kilo","lima","mike","needle", \
\ "november","oscar","papa","quebec","romeo","sierra","tango", \
\ "needle","uniform","victor","whisky","x-ray","yankee","zulu"
needle$ = "needle"
maxindex% = DIM(haystack$(), 1)
FOR index% = 0 TO maxindex%
IF needle$ = haystack$(index%) EXIT FOR
NEXT
IF index% <= maxindex% THEN
PRINT "First found at index "; index%
FOR last% = maxindex% TO 0 STEP -1
IF needle$ = haystack$(last%) EXIT FOR
NEXT
IF last%<>index% PRINT "Last found at index "; last%
ELSE
ERROR 100, "Not found"
ENDIF</syntaxhighlight>
 
==={{header|IS-BASIC}}===
Line 427 ⟶ 451:
250 DATA foo,bar,baz,quux,quuux,quuuux,bazola,ztesch,foo,bar,thud,grunt,foo,bar,bletch,foo,bar,fum,fred,jim,sheila,barney,flarp,zxc
260 DATA 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</syntaxhighlight>
 
==={{header|FreeBASIC}}===
FreeBASIC doesn't have exceptions so we use a different approach to check if the needle is present or not in the haystack:
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64
' Works FB 1.05.0 Linux Mint 64
 
Function tryFindString(s() As String, search As String, ByRef index As Integer) As Boolean
Dim length As Integer = UBound(s) - LBound(s) + 1
If length = 0 Then
index = LBound(s) - 1 '' outside array
Return False
End If
For i As Integer = LBound(s) To UBound(s)
If s(i) = search Then
index = i '' first occurrence
Return True
End If
Next
index = LBound(s) - 1 '' outside array
Return False
End Function
 
Function tryFindLastString(s() As String, search As String, ByRef index As Integer) As Boolean
Dim length As Integer = UBound(s) - LBound(s) + 1
If length = 0 Then
index = LBound(s) - 1 '' outside array
Return False
End If
Dim maxIndex As Integer = LBound(s) - 1 '' outside array
For i As Integer = LBound(s) To UBound(s)
If s(i) = search Then
maxIndex = i
End If
Next
If maxIndex > LBound(s) - 1 Then
index = maxIndex '' last occurrence
Return True
Else
Return False
End If
End Function
 
Dim haystack(1 To 9) As String = {"Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie", "Bush", "Bozo"}
Dim needle(1 To 4) As String = {"Zag", "Krusty", "Washington", "Bush"}
 
Dim As Integer index
Dim As Boolean found
For i As Integer = 1 To 4
found = tryFindString(haystack(), needle(i), index)
If found Then
Print needle(i); " found first at index"; index
Else
Print needle(i); " is not present"
End If
Next
found = tryFindLastString(haystack(), needle(4), index)
If found Then
Print needle(4); " found last at index"; index
Else
Print needle(4); " is not present"
End If
Print
Print "Press any key to quit"
Sleep</syntaxhighlight>
 
{{out}}
<pre>
Zag found first at index 2
Krusty found first at index 6
Washington is not present
Bush found first at index 5
Bush found last at index 8
</pre>
 
==={{header|FutureBasic}}===
<syntaxhighlight lang="futurebasic">
window 1, @"Search a list"
 
void local fn MyEnumeratorCallback( array as CFArrayRef, obj as CFTypeRef, index as NSUInteger, stp as ^BOOL, userData as ptr )
if ( fn StringIsEqual( obj, userData ) )
print obj;@" found at index ";index
*stp = YES// stop enumeration
end if
if ( index == 0 ) then print userData;@" not found"
end fn
 
void local fn DoIt
CFArrayRef haystack = @[@"Mike",@"Bravo",@"Tango",@"Uniform",@"Golf",
@"Tango",@"Sierra",@"November",@"Zulu",@"Delta",@"Hotel",@"Juliet"]
CFStringRef needle = @"Sierra"
NSInteger index = fn ArrayIndexOfObject( haystack, needle )
if ( index != NSNotFound )
print needle;@" found at index ";index
else
print needle;@" not found"
end if
ArrayEnumerateObjectsWithOptions( haystack, NSEnumerationReverse, @fn MyEnumeratorCallback, (ptr)@"Tango" )
end fn
 
fn DoIt
 
HandleEvents
</syntaxhighlight>
{{out}}
<pre>
Sierra found at index 6
Tango found at index 5
</pre>
 
==={{header|Gambas}}===
'''[https://gambas-playground.proko.eu/?gist=7729d65f8af3f128db6c6992c5f74e98 Click this link to run this code]'''
<syntaxhighlight lang="gambas">Public Sub Main()
Dim sHaystack As String[] = ["Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie", "Bush", "Boz", "Zag"]
Dim sNeedle As String = "Charlie"
Dim sOutput As String = "No needle found!"
Dim siCount As Short
 
For siCount = 0 To sHaystack.Max
If sNeedle = sHaystack[siCount] Then
sOutPut = sNeedle & " found at index " & Str(siCount)
Break
End If
Next
 
Print sOutput
 
End</syntaxhighlight>
Output:
<pre>
Charlie found at index 6
</pre>
 
==={{header|Liberty BASIC}}===
<syntaxhighlight lang="lb">haystack$="apple orange pear cherry melon peach banana needle blueberry mango strawberry needle "
haystack$=haystack$+"pineapple grape kiwi blackberry plum raspberry needle cranberry apricot"
 
idx=1
do until word$(haystack$,idx)=""
idx=idx+1
loop
total=idx-1
 
needle$="needle"
'index of first occurrence
for i = 1 to total
if word$(haystack$,i)=needle$ then exit for
next
print needle$;" first found at index ";i
 
'index of last occurrence
for j = total to 1
if word$(haystack$,j)=needle$ then exit for
next
print needle$;" last found at index ";j
if i<>j then
print "Multiple instances of ";needle$
else
print "Only one instance of ";needle$;" in list."
end if
 
'raise exception
needle$="cauliflower"
for k=1 to total
if word$(haystack$,k)=needle$ then exit for
next
if k>total then
print needle$;" not found in list."
else
print needle$;" found at index ";k
end if</syntaxhighlight>
 
 
==={{header|PowerBASIC}}===
{{works with|PowerBASIC for Windows}}
<syntaxhighlight lang="powerbasic">FUNCTION PBMAIN () AS LONG
DIM haystack(54) AS STRING
ARRAY ASSIGN haystack() = "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"
DIM needle AS STRING, found AS LONG, lastFound AS LONG
DO
needle = INPUTBOX$("Word to search for? (Leave blank to exit)")
IF needle <> "" THEN
' collate ucase -> case insensitive
ARRAY SCAN haystack(), COLLATE UCASE, = needle, TO found
IF found > 0 THEN
lastFound = found
MSGBOX "Found """ & needle & """ at index " & TRIM$(STR$(found - 1))
IF found < UBOUND(haystack) THEN
DO
ARRAY SCAN haystack(lastFound), COLLATE UCASE, = needle, TO found
IF found > 0 THEN
MSGBOX "Another occurence of """ & needle & """ at index " & _
TRIM$(STR$(found + lastFound - 1))
lastFound = found + lastFound
ELSE
MSGBOX "No more occurences of """ & needle & """ found"
EXIT DO 'will exit inner DO, not outer
END IF
LOOP
END IF
ELSE
MSGBOX "No occurences of """ & needle & """ found"
END IF
ELSE
EXIT DO
END IF
LOOP
END FUNCTION</syntaxhighlight>
 
==={{header|PureBasic}}===
<syntaxhighlight lang="purebasic">If OpenConsole() ; Open a simple console to interact with user
NewList Straws.s()
Define Straw$, target$="TBA"
Define found
Restore haystack ; Read in all the straws of the haystack.
Repeat
Read.s Straw$
If Straw$<>""
AddElement(Straws())
Straws()=UCase(Straw$)
Continue
Else
Break
EndIf
ForEver
While target$<>""
Print(#CRLF$+"Enter word to search for (leave blank to quit) :"): target$=Input()
ResetList(Straws()): found=#False
While NextElement(Straws())
If UCase(target$)=Straws()
found=#True
PrintN(target$+" found as index #"+Str(ListIndex(Straws())))
EndIf
Wend
If Not found
PrintN("Not found.")
EndIf
Wend
EndIf
DataSection
haystack:
Data.s "Zig","Zag","Zig","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo",""
EndDataSection</syntaxhighlight>
 
 
==={{header|Run BASIC}}===
<syntaxhighlight lang="runbasic">haystack$ = ("Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo Bush ")
needle$ = "Zag Wally Bush Chicken"
 
while word$(needle$,i+1," ") <> ""
i = i + 1
thisNeedle$ = word$(needle$,i," ") + " "
j = instr(haystack$,thisNeedle$)
k1 = 0
k = instr(haystack$,thisNeedle$,j+1)
while k <> 0
k1 = k
k = instr(haystack$,thisNeedle$,k+1)
wend
if j <> 0 then
print thisNeedle$;" located at:";j;
if k1 <> 0 then print " Last position located at:";k1;
print
else
print thisNeedle$;" is not in the list"
end if
wend</syntaxhighlight>
{{out}}
<pre>Zag located at:5
Wally located at:9
Bush located at:22 Last position located at:52
Chicken is not in the list</pre>
 
==={{header|Yabasic}}===
<syntaxhighlight lang="yabasic">list$ = "mouse,hat,cup,deodorant,television,soap,methamphetamine,severed cat heads,cup"
 
dim item$(1)
 
n = token(list$, item$(), ",")
 
line input "Enter string to search: " line$
for i = 1 to n
if line$ = item$(i) then
if not t print "First index for ", line$, ": ", i
t = i
j = j + 1
end if
next
 
if t = 0 then
print "String not found in list"
else
if j > 1 print "Last index for ", line$, ": ", t
end if</syntaxhighlight>
 
=={{header|Batch File}}==
Line 478 ⟶ 808:
 
Press any key to continue . . .</pre>
 
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<syntaxhighlight lang="bbcbasic"> DIM haystack$(27)
haystack$() = "alpha","bravo","charlie","delta","echo","foxtrot","golf", \
\ "hotel","india","juliet","kilo","lima","mike","needle", \
\ "november","oscar","papa","quebec","romeo","sierra","tango", \
\ "needle","uniform","victor","whisky","x-ray","yankee","zulu"
needle$ = "needle"
maxindex% = DIM(haystack$(), 1)
FOR index% = 0 TO maxindex%
IF needle$ = haystack$(index%) EXIT FOR
NEXT
IF index% <= maxindex% THEN
PRINT "First found at index "; index%
FOR last% = maxindex% TO 0 STEP -1
IF needle$ = haystack$(last%) EXIT FOR
NEXT
IF last%<>index% PRINT "Last found at index "; last%
ELSE
ERROR 100, "Not found"
ENDIF</syntaxhighlight>
 
=={{header|BQN}}==
Line 1,412 ⟶ 1,718:
 
end program main</syntaxhighlight>
 
=={{header|FreeBASIC}}==
FreeBASIC doesn't have exceptions so we use a different approach to check if the needle is present or not in the haystack:
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64
' Works FB 1.05.0 Linux Mint 64
 
Function tryFindString(s() As String, search As String, ByRef index As Integer) As Boolean
Dim length As Integer = UBound(s) - LBound(s) + 1
If length = 0 Then
index = LBound(s) - 1 '' outside array
Return False
End If
For i As Integer = LBound(s) To UBound(s)
If s(i) = search Then
index = i '' first occurrence
Return True
End If
Next
index = LBound(s) - 1 '' outside array
Return False
End Function
 
Function tryFindLastString(s() As String, search As String, ByRef index As Integer) As Boolean
Dim length As Integer = UBound(s) - LBound(s) + 1
If length = 0 Then
index = LBound(s) - 1 '' outside array
Return False
End If
Dim maxIndex As Integer = LBound(s) - 1 '' outside array
For i As Integer = LBound(s) To UBound(s)
If s(i) = search Then
maxIndex = i
End If
Next
If maxIndex > LBound(s) - 1 Then
index = maxIndex '' last occurrence
Return True
Else
Return False
End If
End Function
 
Dim haystack(1 To 9) As String = {"Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie", "Bush", "Bozo"}
Dim needle(1 To 4) As String = {"Zag", "Krusty", "Washington", "Bush"}
 
Dim As Integer index
Dim As Boolean found
For i As Integer = 1 To 4
found = tryFindString(haystack(), needle(i), index)
If found Then
Print needle(i); " found first at index"; index
Else
Print needle(i); " is not present"
End If
Next
found = tryFindLastString(haystack(), needle(4), index)
If found Then
Print needle(4); " found last at index"; index
Else
Print needle(4); " is not present"
End If
Print
Print "Press any key to quit"
Sleep</syntaxhighlight>
 
{{out}}
<pre>
Zag found first at index 2
Krusty found first at index 6
Washington is not present
Bush found first at index 5
Bush found last at index 8
</pre>
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
window 1, @"Search a list"
 
void local fn MyEnumeratorCallback( array as CFArrayRef, obj as CFTypeRef, index as NSUInteger, stp as ^BOOL, userData as ptr )
if ( fn StringIsEqual( obj, userData ) )
print obj;@" found at index ";index
*stp = YES// stop enumeration
end if
if ( index == 0 ) then print userData;@" not found"
end fn
 
void local fn DoIt
CFArrayRef haystack = @[@"Mike",@"Bravo",@"Tango",@"Uniform",@"Golf",
@"Tango",@"Sierra",@"November",@"Zulu",@"Delta",@"Hotel",@"Juliet"]
CFStringRef needle = @"Sierra"
NSInteger index = fn ArrayIndexOfObject( haystack, needle )
if ( index != NSNotFound )
print needle;@" found at index ";index
else
print needle;@" not found"
end if
ArrayEnumerateObjectsWithOptions( haystack, NSEnumerationReverse, @fn MyEnumeratorCallback, (ptr)@"Tango" )
end fn
 
fn DoIt
 
HandleEvents
</syntaxhighlight>
{{out}}
<pre>
Sierra found at index 6
Tango found at index 5
</pre>
 
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=7729d65f8af3f128db6c6992c5f74e98 Click this link to run this code]'''
<syntaxhighlight lang="gambas">Public Sub Main()
Dim sHaystack As String[] = ["Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie", "Bush", "Boz", "Zag"]
Dim sNeedle As String = "Charlie"
Dim sOutput As String = "No needle found!"
Dim siCount As Short
 
For siCount = 0 To sHaystack.Max
If sNeedle = sHaystack[siCount] Then
sOutPut = sNeedle & " found at index " & Str(siCount)
Break
End If
Next
 
Print sOutput
 
End</syntaxhighlight>
Output:
<pre>
Charlie found at index 6
</pre>
 
=={{header|GAP}}==
Line 2,174 ⟶ 2,346:
8
Washington is not in haystack.</pre>
 
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">haystack$="apple orange pear cherry melon peach banana needle blueberry mango strawberry needle "
haystack$=haystack$+"pineapple grape kiwi blackberry plum raspberry needle cranberry apricot"
 
idx=1
do until word$(haystack$,idx)=""
idx=idx+1
loop
total=idx-1
 
needle$="needle"
'index of first occurrence
for i = 1 to total
if word$(haystack$,i)=needle$ then exit for
next
print needle$;" first found at index ";i
 
'index of last occurrence
for j = total to 1
if word$(haystack$,j)=needle$ then exit for
next
print needle$;" last found at index ";j
if i<>j then
print "Multiple instances of ";needle$
else
print "Only one instance of ";needle$;" in list."
end if
 
'raise exception
needle$="cauliflower"
for k=1 to total
if word$(haystack$,k)=needle$ then exit for
next
if k>total then
print needle$;" not found in list."
else
print needle$;" found at index ";k
end if</syntaxhighlight>
 
=={{header|Lingo}}==
Line 3,050 ⟶ 3,183:
The index of "b" is 2
</pre>
 
=={{header|PowerBASIC}}==
{{works with|PowerBASIC for Windows}}
 
<syntaxhighlight lang="powerbasic">FUNCTION PBMAIN () AS LONG
DIM haystack(54) AS STRING
ARRAY ASSIGN haystack() = "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"
DIM needle AS STRING, found AS LONG, lastFound AS LONG
DO
needle = INPUTBOX$("Word to search for? (Leave blank to exit)")
IF needle <> "" THEN
' collate ucase -> case insensitive
ARRAY SCAN haystack(), COLLATE UCASE, = needle, TO found
IF found > 0 THEN
lastFound = found
MSGBOX "Found """ & needle & """ at index " & TRIM$(STR$(found - 1))
IF found < UBOUND(haystack) THEN
DO
ARRAY SCAN haystack(lastFound), COLLATE UCASE, = needle, TO found
IF found > 0 THEN
MSGBOX "Another occurence of """ & needle & """ at index " & _
TRIM$(STR$(found + lastFound - 1))
lastFound = found + lastFound
ELSE
MSGBOX "No more occurences of """ & needle & """ found"
EXIT DO 'will exit inner DO, not outer
END IF
LOOP
END IF
ELSE
MSGBOX "No occurences of """ & needle & """ found"
END IF
ELSE
EXIT DO
END IF
LOOP
END FUNCTION</syntaxhighlight>
 
=={{header|PowerShell}}==
Line 3,254 ⟶ 3,343:
true.
</pre>
 
=={{header|PureBasic}}==
<syntaxhighlight lang="purebasic">If OpenConsole() ; Open a simple console to interact with user
NewList Straws.s()
Define Straw$, target$="TBA"
Define found
Restore haystack ; Read in all the straws of the haystack.
Repeat
Read.s Straw$
If Straw$<>""
AddElement(Straws())
Straws()=UCase(Straw$)
Continue
Else
Break
EndIf
ForEver
While target$<>""
Print(#CRLF$+"Enter word to search for (leave blank to quit) :"): target$=Input()
ResetList(Straws()): found=#False
While NextElement(Straws())
If UCase(target$)=Straws()
found=#True
PrintN(target$+" found as index #"+Str(ListIndex(Straws())))
EndIf
Wend
If Not found
PrintN("Not found.")
EndIf
Wend
EndIf
DataSection
haystack:
Data.s "Zig","Zag","Zig","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo",""
EndDataSection</syntaxhighlight>
 
=={{header|Python}}==
Line 3,708 ⟶ 3,759:
end
#=> Bush appears at index [4, 7]</syntaxhighlight>
 
=={{header|Run BASIC}}==
<syntaxhighlight lang="runbasic">haystack$ = ("Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo Bush ")
needle$ = "Zag Wally Bush Chicken"
 
while word$(needle$,i+1," ") <> ""
i = i + 1
thisNeedle$ = word$(needle$,i," ") + " "
j = instr(haystack$,thisNeedle$)
k1 = 0
k = instr(haystack$,thisNeedle$,j+1)
while k <> 0
k1 = k
k = instr(haystack$,thisNeedle$,k+1)
wend
if j <> 0 then
print thisNeedle$;" located at:";j;
if k1 <> 0 then print " Last position located at:";k1;
print
else
print thisNeedle$;" is not in the list"
end if
wend</syntaxhighlight>
{{out}}
<pre>Zag located at:5
Wally located at:9
Bush located at:22 Last position located at:52
Chicken is not in the list</pre>
 
=={{header|Rust}}==
 
Rust encourages to encode possible errors in function's return type. For example, <code>position</code> returns <code>Option<usize></code>, which can be <code>None</code> or <code>Some(x)</code>.
 
Line 4,378 ⟶ 4,400:
Last index for Zag: 9
</pre>
 
=={{header|Yabasic}}==
<syntaxhighlight lang="yabasic">list$ = "mouse,hat,cup,deodorant,television,soap,methamphetamine,severed cat heads,cup"
 
dim item$(1)
 
n = token(list$, item$(), ",")
 
line input "Enter string to search: " line$
for i = 1 to n
if line$ = item$(i) then
if not t print "First index for ", line$, ": ", i
t = i
j = j + 1
end if
next
 
if t = 0 then
print "String not found in list"
else
if j > 1 print "Last index for ", line$, ": ", t
end if</syntaxhighlight>
 
=={{header|Yorick}}==
2,169

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.