-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
97 lines (79 loc) · 2.28 KB
/
main.go
File metadata and controls
97 lines (79 loc) · 2.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package main
import (
"encoding/json"
"fmt"
"net/http"
"sort"
"sync"
"time"
)
func main() {
http.HandleFunc("/process-single", processSingle)
http.HandleFunc("/process-concurrent", processConcurrent)
http.ListenAndServe(":8000", nil)
}
func processSingle(w http.ResponseWriter, r *http.Request) {
var inputData struct {
ToSort [][]int `json:"to_sort"`
}
err := json.NewDecoder(r.Body).Decode(&inputData)
if err != nil {
http.Error(w, fmt.Sprintf("Error decoding JSON: %s", err), http.StatusBadRequest)
return
}
startTime := time.Now()
sortedArrays := make([][]int, len(inputData.ToSort))
for i, arr := range inputData.ToSort {
sortedArrays[i] = make([]int, len(arr))
copy(sortedArrays[i], arr)
sort.Ints(sortedArrays[i])
}
elapsedTime := time.Since(startTime).Nanoseconds()
response := createResponse(sortedArrays, elapsedTime)
encodeJSON(w, response)
}
func processConcurrent(w http.ResponseWriter, r *http.Request) {
var inputData struct {
ToSort [][]int `json:"to_sort"`
}
err := json.NewDecoder(r.Body).Decode(&inputData)
if err != nil {
http.Error(w, fmt.Sprintf("Error decoding JSON: %s", err), http.StatusBadRequest)
return
}
startTime := time.Now()
var wg sync.WaitGroup
sortedArrays := make([][]int, len(inputData.ToSort))
ch := make(chan int, len(inputData.ToSort))
for i, arr := range inputData.ToSort {
wg.Add(1)
go func(i int, arr []int) {
defer wg.Done()
sortedArray := make([]int, len(arr))
copy(sortedArray, arr)
sort.Ints(sortedArray)
sortedArrays[i] = sortedArray
ch <- 1
}(i, arr)
}
wg.Wait()
close(ch)
elapsedTime := time.Since(startTime).Nanoseconds()
response := createResponse(sortedArrays, elapsedTime)
encodeJSON(w, response)
}
func createResponse(sortedArrays [][]int, elapsedTime int64) map[string]interface{} {
response := map[string]interface{}{
"sorted_arrays": sortedArrays,
"time_ns": elapsedTime,
}
return response
}
func encodeJSON(w http.ResponseWriter, data interface{}) {
w.Header().Set("Content-Type", "application/json")
err := json.NewEncoder(w).Encode(data)
if err != nil {
http.Error(w, fmt.Sprintf("Error encoding JSON: %s", err), http.StatusInternalServerError)
return
}
}