Ruby Array Serach
# As not mentioned I am assuming you want the cide in python language
# just because the given code syntax just look like python
# If you want in any other language just folluw the same approach
# That will provide you the same result
# search for track by name.
# Returns the index of the track or -1 if not found
def search_for_track_name(tracks, search_string):
# Using while loop
# just by traversing the tracks array if search_string found
# return Index and chnge flag to 1 and print found and if after traversing full array
# take a variable flag if it is 0 return not found
flag = 0
i = 0
found_index=0
while(tracks.length()--):
if (tracks[i] == search_string):
flag = 1
found_index = i
break;
i += 1
if flag == 0:
return - 1;
return found_index
end
def main():
music_file = File.new("album.txt", "r")
tracks = read_tracks(music_file)
music_file.close()
# taking the input of search string
search_string = read_string("Enter the track name you wish to find: ")
# calling function to search string
index = search_for_track_name(tracks, search_string)
if index > -1
puts "Found " + tracks[index].name + " at " + index.to_s()
else
puts "Entry not Found"
end
end
main()
Healthy Hornet