go package main
// Реализовать autocomplete для фильмов:
go package main
Короткий ответ
Что ответить на собеседовании
Подробный разбор
Ответ с пояснениями
Условие
// Реализовать autocomplete для фильмов: // по введённым первым 3+ буквам выводить топ-3 совпадения по алфавиту. // ["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() {}
Ответ
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))
}
}
Этот код реализует автодополнение по первым 3 и более буквам, возвращая до трёх совпадений в алфавитном порядке.