Last active
August 15, 2019 00:52
-
-
Save lerox/a6e2dca2d6e410f8240dbbc1a36acf24 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# https://www.hackerrank.com/challenges/ctci-array-left-rotation/problem | |
package main | |
import ( | |
"bufio" | |
"fmt" | |
"io" | |
"os" | |
"strconv" | |
"strings" | |
) | |
// Complete the rotLeft function below. | |
func rotLeft(a []int32, d int32) []int32 { | |
pos := int(d) % len(a) | |
if pos == 0 { | |
return a | |
} | |
newSlice := make([]int32, len(a), len(a)) | |
for i := 0; i < len(a); i++ { | |
j := pos + i | |
if j >= len(a) { | |
j = j - len(a) | |
} | |
newSlice[i] = a[j] | |
} | |
return newSlice | |
} | |
func main() { | |
reader := bufio.NewReaderSize(os.Stdin, 1024*1024) | |
stdout, err := os.Create(os.Getenv("OUTPUT_PATH")) | |
checkError(err) | |
defer stdout.Close() | |
writer := bufio.NewWriterSize(stdout, 1024*1024) | |
nd := strings.Split(readLine(reader), " ") | |
nTemp, err := strconv.ParseInt(nd[0], 10, 64) | |
checkError(err) | |
n := int32(nTemp) | |
dTemp, err := strconv.ParseInt(nd[1], 10, 64) | |
checkError(err) | |
d := int32(dTemp) | |
aTemp := strings.Split(readLine(reader), " ") | |
var a []int32 | |
for i := 0; i < int(n); i++ { | |
aItemTemp, err := strconv.ParseInt(aTemp[i], 10, 64) | |
checkError(err) | |
aItem := int32(aItemTemp) | |
a = append(a, aItem) | |
} | |
result := rotLeft(a, d) | |
for i, resultItem := range result { | |
fmt.Fprintf(writer, "%d", resultItem) | |
if i != len(result)-1 { | |
fmt.Fprintf(writer, " ") | |
} | |
} | |
fmt.Fprintf(writer, "\n") | |
writer.Flush() | |
} | |
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