Senior
// Implement autocomplete for movies: // by entering the first 3+ letters, output the top-3 matches alphabetically. // ["macarthur", "interstellar", "intrusion", "macao", "into the abyss", "internship"] // me -> [] // mac -> ["macao", "macarthur", "machinist"] // int -> ["internship", "interstellar", "into the abyss"] // interstellar -> ["interstellar"] // intr -> ["intrusion"] // intrusion -> ["intrusion"] // into -> ["into the abyss"] // stellaris -> [] package main func main() {}
sobes.tech AI
Answer from AI
go package main
import ( "fmt" "sort" "strings" )
func autocomplete(movies []string, input string) []string { if len(input) < 3 { return []string{} }
input = strings.ToLower(input)
matches := []string{}
for _, movie := range movies {
if strings.HasPrefix(strings.ToLower(movie), input) {
matches = append(matches, movie)
}
}
sort.Strings(matches)
if len(matches) > 3 {
matches = matches[:3]
}
return matches
}
func main() { movies := []string{"macarthur", "interstellar", "intrusion", "macao", "into the abyss", "internship"}
tests := []string{"me", "mac", "int", "interstellar", "intr", "intrusion", "into", "stellaris"}
for _, test := range tests {
fmt.Printf("%s -> %v\n", test, autocomplete(movies, test))
}
}
This code implements autocomplete based on the first 3 or more letters, returning up to three matches in alphabetical order.