{ "cells": [ { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "t := \"haystack needle haystack\" // \"text\" - thing we search in\n", "p := \"needle\" // \"pattern\" - thing we search for" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "func naive(p, t string) []int {\n", " // assume len(p) <= len(t)\n", " occurrences := []int{}\n", " for i := 0; i < len(t) - len(p) + 1; i++ { // for each alignment of p to t\n", " match := true // assume we match until proven wrong\n", " for j := 0; j < len(p); j++ { // for each position of p\n", " if t[i+j] != p[j] {\n", " match = false // at least 1 char mismatches\n", " break\n", " }\n", " }\n", " if match {\n", " occurrences = append(occurrences, i)\n", " }\n", " }\n", " return occurrences\n", "}" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[9]" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "naive(p, t)" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "needle" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "t[9:9+len(p)]" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[0 6 12]" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "naive(\"needle\", \"needleneedleneedle\")" ] } ], "metadata": { "kernelspec": { "display_name": "Go", "language": "go", "name": "gophernotes" }, "language_info": { "codemirror_mode": "", "file_extension": ".go", "mimetype": "", "name": "go", "nbconvert_exporter": "", "pygments_lexer": "", "version": "go1.11" } }, "nbformat": 4, "nbformat_minor": 2 }