Add other solution for find pick along the array

This commit is contained in:
2024-05-20 16:15:37 -06:00
parent f8534fff74
commit 8d951dd0e6
4 changed files with 178 additions and 0 deletions

Binary file not shown.

33
findPeak.go Normal file
View File

@@ -0,0 +1,33 @@
package main
import "fmt"
// FindPeak finds the peak element in the array
func findPeak(arr []int) int {
n := len(arr)
// first or last element is peak element
if n == 1 {
return 0
}
if arr[0] >= arr[1] {
return 0
}
if arr[n-1] >= arr[n-2] {
return n - 1
}
// check for ever other element
for i := 1; i < n-1; i++ {
// check if the neighbors are smaller
if arr[i] >= arr[i-1] && arr[i] >= arr[i+1] {
return i
}
}
return -1 // inficating no peak found
}
func main() {
arr := []int{1, 3, 20, 4, 1, 21, 0}
fmt.Println("Index of a peak point is", findPeak(arr))
}

BIN
findPeak2.pdf Normal file

Binary file not shown.

145
findPeak2.tex Normal file
View File

@@ -0,0 +1,145 @@
\documentclass[]{article}
\usepackage[utf8]{inputenc}
\usepackage[spanish]{babel}
\usepackage{listings}
\usepackage{xcolor}
\usepackage[a4paper, total={6.5in, 8in}]{geometry}
\definecolor{codegreen}{rgb}{0,0.6,0}
\definecolor{codegray}{rgb}{0.5,0.5,0.5}
\definecolor{codepurple}{rgb}{0.58,0,0.82}
\definecolor{backcolour}{rgb}{0.95,0.95,0.92}
\lstdefinestyle{mystyle}{
backgroundcolor=\color{backcolour},
commentstyle=\color{codegreen},
keywordstyle=\color{magenta},
numberstyle=\tiny\color{codegray},
stringstyle=\color{codepurple},
basicstyle=\ttfamily\footnotesize,
breakatwhitespace=false,
breaklines=true,
captionpos=b,
keepspaces=true,
numbers=left,
numbersep=5pt,
showspaces=false,
showstringspaces=false,
showtabs=false,
tabsize=2
}
\lstset{style=mystyle}
\newcommand{\quotes}[1]{``#1''}
%opening
\title{Soluciones a los principales problemas con arreglos}
\author{betology}
\date{}
\begin{document}
\maketitle
\section{Código en Go para la función findPeak}
La siguiente función en Go encuentra todos los picos en un arreglo. Un elemento es considerado un pico si es mayor o igual a sus vecinos. A continuación, se presenta el código con su respectiva explicación.
\begin{lstlisting}[language=Go, caption={Código en Go para encontrar todos los picos en un arreglo}]
package main
import "fmt"
// findPeaks finds all peaks in the array
func findPeaks(arr []int) []int {
var peaks []int
n := len(arr)
if n == 0 {
return peaks
}
// Check if the first element is a peak
if n == 1 || arr[0] >= arr[1] {
peaks = append(peaks, arr[0])
}
// Check for peaks in the middle of the array
for i := 1; i < n-1; i++ {
if arr[i] >= arr[i-1] && arr[i] >= arr[i+1] {
peaks = append(peaks, arr[i])
}
}
// Check if the last element is a peak
if n > 1 && arr[n-1] >= arr[n-2] {
peaks = append(peaks, arr[n-1])
}
return peaks
}
func main() {
arr := []int{1, 3, 20, 4, 1, 0, 5, 2, 1, 4, 1}
peaks := findPeaks(arr)
fmt.Println("Peaks are:", peaks)
}
\end{lstlisting}
\section{Explicación del código en Go}
Explicación de cada línea:
\begin{lstlisting}[language=Go, numbers=left, stepnumber=1]
package main
import "fmt"
\end{lstlisting}
\textbf{Líneas 1-2:} Definimos el paquete principal \texttt{main} y luego importamos el paquete \texttt{fmt}, que necesitaremos para imprimir los resultados en la consola.
\begin{lstlisting}[language=Go, numbers=left, firstnumber=3]
// findPeaks finds all peaks in the array
func findPeaks(arr []int) []int {
\end{lstlisting}
\textbf{Líneas 3-5:} Definimos una función llamada \texttt{findPeaks} que toma una matriz de enteros como entrada y devuelve una slice de enteros (que contiene todos los picos).
\begin{lstlisting}[language=Go, numbers=left, firstnumber=6]
var peaks []int
n := len(arr)
if n == 0 {
return peaks
}
\end{lstlisting}
\textbf{Líneas 6-10:} Inicializamos una slice vacía llamada \texttt{peaks} para almacenar los picos encontrados. Luego, obtenemos la longitud de la matriz de entrada \texttt{arr} y verificamos si está vacía. Si lo está, devolvemos la slice vacía.
\begin{lstlisting}[language=Go, numbers=left, firstnumber=11]
// Check if the first element is a peak
if n == 1 || arr[0] >= arr[1] {
peaks = append(peaks, arr[0])
}
\end{lstlisting}
\textbf{Líneas 11-15:} Comprobamos si el primer elemento de la matriz es un pico. Si la longitud de la matriz es 1 o si el primer elemento es mayor o igual que el segundo, entonces añadimos el primer elemento a la slice de picos.
\begin{lstlisting}[language=Go, numbers=left, firstnumber=16]
// Check for peaks in the middle of the array
for i := 1; i < n-1; i++ {
if arr[i] >= arr[i-1] && arr[i] >= arr[i+1] {
peaks = append(peaks, arr[i])
}
}
\end{lstlisting}
\textbf{Líneas 16-20:} Iteramos a través de los elementos intermedios de la matriz y verificamos si cada elemento es un pico comparándolo con sus vecinos. Si es así, lo añadimos a la slice de picos.
\begin{lstlisting}[language=Go, numbers=left, firstnumber=21]
// Check if the last element is a peak
if n > 1 && arr[n-1] >= arr[n-2] {
peaks = append(peaks, arr[n-1])
}
\end{lstlisting}
\textbf{Líneas 21-24:} Comprobamos si el último elemento de la matriz es un pico y lo añadimos a