chore: add hackerrank solutions
This commit is contained in:
92
hacker-rank/sparse-arrays/main.go
Normal file
92
hacker-rank/sparse-arrays/main.go
Normal file
@@ -0,0 +1,92 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strconv"
|
||||
stringz "strings"
|
||||
)
|
||||
|
||||
/*
|
||||
* Complete the 'matchingStrings' function below.
|
||||
*
|
||||
* The function is expected to return an INTEGER_ARRAY.
|
||||
* The function accepts following parameters:
|
||||
* 1. STRING_ARRAY strings
|
||||
* 2. STRING_ARRAY queries
|
||||
*/
|
||||
|
||||
func matchingStrings(strings []string, queries []string) []int32 {
|
||||
// Write your code here
|
||||
res := make([]int32, len(queries))
|
||||
for _, s := range strings {
|
||||
for i, q := range queries {
|
||||
if s == q {
|
||||
res[i]++
|
||||
}
|
||||
}
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
func main() {
|
||||
reader := bufio.NewReaderSize(os.Stdin, 16 * 1024 * 1024)
|
||||
|
||||
stdout, err := os.Create(os.Getenv("OUTPUT_PATH"))
|
||||
checkError(err)
|
||||
|
||||
defer stdout.Close()
|
||||
|
||||
writer := bufio.NewWriterSize(stdout, 16 * 1024 * 1024)
|
||||
|
||||
stringsCount, err := strconv.ParseInt(stringz.TrimSpace(readLine(reader)), 10, 64)
|
||||
checkError(err)
|
||||
|
||||
var strings []string
|
||||
|
||||
for i := 0; i < int(stringsCount); i++ {
|
||||
stringsItem := readLine(reader)
|
||||
strings = append(strings, stringsItem)
|
||||
}
|
||||
|
||||
queriesCount, err := strconv.ParseInt(stringz.TrimSpace(readLine(reader)), 10, 64)
|
||||
checkError(err)
|
||||
|
||||
var queries []string
|
||||
|
||||
for i := 0; i < int(queriesCount); i++ {
|
||||
queriesItem := readLine(reader)
|
||||
queries = append(queries, queriesItem)
|
||||
}
|
||||
|
||||
res := matchingStrings(strings, queries)
|
||||
|
||||
for i, resItem := range res {
|
||||
fmt.Fprintf(writer, "%d", resItem)
|
||||
|
||||
if i != len(res) - 1 {
|
||||
fmt.Fprintf(writer, "\n")
|
||||
}
|
||||
}
|
||||
|
||||
fmt.Fprintf(writer, "\n")
|
||||
|
||||
writer.Flush()
|
||||
}
|
||||
|
||||
func readLine(reader *bufio.Reader) string {
|
||||
str, _, err := reader.ReadLine()
|
||||
if err == io.EOF {
|
||||
return ""
|
||||
}
|
||||
|
||||
return stringz.TrimRight(string(str), "\r\n")
|
||||
}
|
||||
|
||||
func checkError(err error) {
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user