Skip to content

Instantly share code, notes, and snippets.

@yogasw
Created September 5, 2022 23:46
Show Gist options
  • Save yogasw/05f30d24a5f039470bcbcb385fe36b3f to your computer and use it in GitHub Desktop.
Save yogasw/05f30d24a5f039470bcbcb385fe36b3f to your computer and use it in GitHub Desktop.
ZigZagSequence.go
package main
import (
"bufio"
"fmt"
"io"
"os"
"sort"
"strconv"
"strings"
)
func findZigZagSequence(n int64, list []int64) []int64 {
mid := (n+1)/2 - 1
println("MID: ", mid)
println("N: ", n)
sort.Slice(list, func(i, j int) bool { return list[i] < list[j] })
list[mid], list[n-1] = list[n-1], list[mid]
st := mid + 1
ed := n - 1 - 1
println("ST: ", st)
println("ED: ", ed)
for i := st; i < ed; i++ {
list[st], list[ed] = list[ed], list[st]
st = st + 1
ed = ed - 1
}
return list
}
func main() {
reader := bufio.NewReaderSize(os.Stdin, 16*1024*1024)
aTemp, err := strconv.ParseInt(strings.TrimSpace(readLine(reader)), 10, 64)
checkError(err)
nTemp, err2 := strconv.ParseInt(strings.TrimSpace(readLine(reader)), 10, 64)
checkError(err2)
temp := strings.Split(strings.TrimSpace(readLine(reader)), " ")
var v []int64
for i := aTemp - 1; i < nTemp; i++ {
aItemTemp, err := strconv.ParseInt(temp[i], 10, 64)
checkError(err)
aItem := aItemTemp
v = append(v, aItem)
}
result := findZigZagSequence(nTemp, v)
for i, v := range result {
if i == len(result)-1 {
fmt.Printf("%d\n", v)
} else {
fmt.Printf("%d ", v)
}
}
}
func readLine(reader *bufio.Reader) string {
str, _, err := reader.ReadLine()
if err == io.EOF {
return ""
}
return strings.TrimRight(string(str), "\r\n")
}
func checkError(err error) {
if err != nil {
panic(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment