Learn algorithms with Go @ Full search_Linear search method

The purpose is to understand Go basic syntax and algorithm brain training.

About the algorithm

What is full search?

This is a method to investigate all the possibilities and solve the problem. It's a method of checking everything thoroughly. Even at work, I often use it when I can't isolate the cause of a problem.

What is a linear search method?

This is a search method that searches each element in order. For the time being, it's probably the most muddy category of all the searches, such as searching from head to butt.

Sample code

I will put the code for the time being.

main.go


package main

import "fmt"

func main() {
	l := []int{1, 2, 3, 4, 5}
	m := 5
	r := solve(l, m)
	fmt.Printf("%v", r)
}

func solve(a []int, b int) string {
	r := "NG"
	for i := 0; i < len(a); i++ {
		if a[i] == b {
			r = "ok"
		}
	}
	return r
}

Brief explanation

It is a code to check whether a specific numerical value is included in an int type slice (array). Examine from the beginning to the last element.
	l := []int{1, 2, 3, 4, 5}
	m := 5

At the above time, I was able to confirm that the numerical value was included in the loop processing at the end of the for statement,

	l := []int{1, 2, 3, 4, 5}
	m := 1

In such a case, you are doing useless processing other than the first loop processing. Therefore, it is best to write as follows.

		if a[i] == b {
			r = "ok"
			break
		}

Impressions

Anyway, it's simple and I like to check everything.

Recommended Posts

Learn algorithms with Go @ Full search_Linear search method
Bit full search with Go
Learn algorithms with Go @ recursive call
Full bit search with Python
Learn search with Python # 2bit search, permutation search
Bit full search with Go
Hello world with full features of Go language
Learn Service Bus Queue with Azure SDK for Go (1)