ruby - Linear Search not completing successfully -
performing basic linear search loop on array, , not returning expected value. given:
students = ["alex", "kyle", "libby", "monkey boy"]
i'm trying basic linear search see if name "monkey boy" exists, , return it's index.
def linear_search(array, name) = 0 while < array.length if array[i] == "#{name}" return else return -1 end i+=1 end end linear_search(students, "alex") # returns 0 linear_search(students, "monkey boy") # returns -1, should return 3
very confused. what's going on here?
your while block incorrect if
def linear_search(array, name) = 0 while < array.length if array[i] == "#{name}" return else return -1 end i+=1 end end
when search linear_search(students, "alex")
"alex"
present @ array[0], , array[i] == "#{name}"
true
return , breaks loop
when search linear_search(students, "monkey boy")
"monkey boy"
present @ array[3], , first time array[i] == "#{name}"
false
i.e "alex"
== "monkey boy"
return -1, i.e. executes else part , breaks loop no increment
if remove else part out of while work earlier answer or in more elegant way
def linear_search(array, name) return array.index(name).nil? ? -1 : array.index(name) end linear_search(students, "kyle") # 0 linear_search(students, "monkey boy") # 3 linear_search(students, "monkey") # -1
Comments
Post a Comment