Created
June 6, 2024 21:09
-
-
Save PattoMotto/4c29cd6201e9db755509c23fd260bdc3 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
import Foundation | |
func rejectRequest(_ requests: [String], rateLimit: Int) -> [Int] { | |
var ids = [Int]() | |
var requestMap = [String: [Int]]() | |
requests.forEach { request in | |
let rawData = request.split(separator: " ") | |
let ipAddress = String(rawData[1]) | |
guard let requestId = Int(rawData[0]), | |
let time = Int(rawData[2]) else { | |
fatalError("Invalid input") | |
} | |
var requestHistory: [Int] | |
if let history = requestMap[ipAddress] { | |
requestHistory = history + [time] | |
} else { | |
requestHistory = [time] | |
} | |
let newValue = requestHistory.filter { (time - $0) <= 1000 } | |
requestMap[ipAddress] = newValue | |
if newValue.count > rateLimit { | |
ids.append(requestId) | |
} | |
} | |
return ids | |
} | |
let request1 = ["1 192.168.1.1 50000", "2 192.168.1.1 50100", "3 192.168.1.1 52100", "4 192.168.1.1 53100", "5 192.168.1.1 54000"] | |
let rateLimit1 = 1 | |
print(rejectRequest(request1, rateLimit: rateLimit1)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment