It lasted for 4 days after leaving the shaven for 3 days. Click here for the 3rd day <Implementing the algorithm in Ruby: Day 3 -Binary search->
A method of finding a specific value by comparing random data one by one from the beginning. If found, the process ends there. It ’s a very simple algorithm. Let's move on to coding as soon as we understand the mechanism
linerSearch.rb
#Linear search
def linerSearch(data, target)
bool = -1
count = 0
while count <= data.length
if data[count] == target
bool = count
break
end
count += 1
end
bool
end
#Run
print "Value to store:"
data = gets.split().map(&:to_i)
print "Value to look for:"
target = gets.to_i
search = linerSearch(data, target)
if search >= 0
puts "#{target}Is#{search+1}Found second."
else
puts "#{target}Was not found."
end
linerSearch takes an array of numbers and the value to look for as arguments. Loop until count indicating the position of the array exceeds the size of the array If data is found, assign the location of the array at that time to bool and end the loop. If not found, bool returns -1.
If the output is found, the location where it was found. If not found, output that it was not found.
After all it was very easy compared to yesterday However, I sometimes find it difficult to implement what I can imagine as I imagined.
Next time, let's try the Tower of Hanoi, which is the most famous for recursion. .. ..
Recommended Posts