Implement the algorithm in Ruby: Day 4-Linear search-

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->

What is a linear 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

code

#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.

Finally

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

Implement the algorithm in Ruby: Day 4-Linear search-
Implement the algorithm in Ruby: Day 3 -Binary search-
Implement the algorithm in Ruby: Day 1 -Euclidean algorithm-
Implement the algorithm in Ruby: Day 2 -Bubble sort-
I tried to implement the Euclidean algorithm in Java
Try to implement Yubaba in Ruby
Implement a gRPC client in Ruby
How to implement search functionality in Rails
Linear search
Implemented basic search / sort algorithm in Java
The ruby version is managed in the .rbenv / version file
[Ruby] Code to display the day of the week
Implement the Like feature in Ajax with Rails.
How Docker works ~ Implement the container in 60 lines
How to build the simplest blockchain in Ruby
How to implement Pagination in GraphQL (for ruby)
I want to get the value in Ruby
ruby search problem
Class in Ruby
Heavy in Ruby! ??
Count the number of occurrences of a string in Ruby
Implement post search function in Rails application (where method)
[Ruby] The role of subscripts in learning elements in arrays
About the difference between classes and instances in Ruby
[Ruby / Rails] Set a unique (unique) value in the class
Get the URL of the HTTP redirect destination in Ruby