Created
March 28, 2021 16:46
-
-
Save woodycatliu/49b8e46a262caaea5201ce0105a3faaf 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
//: [Previous](@previous) | |
import Foundation | |
let input = """ | |
7 | |
4 6 | |
2 1 | |
7 12 | |
7 2 | |
2 1000 | |
77 298 | |
100 500 | |
""" | |
var lines = input.components(separatedBy: "\n") | |
func readLine() -> String? { | |
let firstStr = lines.first | |
lines.remove(at: 0) | |
return firstStr! | |
} | |
func getIntegersOf(line: String, separatedBy separator: String) -> [Int] { | |
let stringArray = line.components(separatedBy: separator) | |
return stringArray.map { Int($0)! } | |
} | |
// Reversort | |
func checkSort(arr: [Int], count: Int)-> Bool { | |
let result = doSomething(arr) | |
return count == result | |
} | |
func doSomething(_ input: [Int])-> Int { | |
var result: Int = 0 | |
var input = input | |
// (i, exchange) | |
for i in 0..<input.count - 1 { | |
var exchange = i | |
var min: Int = input[i] | |
for j in i + 1..<input.count { | |
if min > input[j] { | |
min = input[j] | |
exchange = j | |
} | |
} | |
let reversed = Array(input[i...exchange].reversed()) | |
for k in i...exchange { | |
input[k] = reversed[k - i] | |
} | |
result += ( exchange - i + 1) | |
} | |
return result | |
} | |
func createArray(range: Int)-> [Int] { | |
var result: [Int] = [] | |
for i in 1...range { | |
result.append(i) | |
} | |
return result | |
} | |
func checkList(arr: [Int], cas: Int, count: Int)-> String { | |
var arr = arr | |
if checkSort(arr: arr, count: count) { | |
let string = arr.map{ String($0)}.joined(separator: " ") | |
let result = "Case #\(cas): \(string)" | |
return result | |
} | |
for i in arr.indices { | |
for j in i + 1..<arr.count { | |
let num = arr[i] | |
arr[i] = arr[j] | |
arr[j] = num | |
if checkSort(arr: arr, count: count) { | |
let string = arr.map{ String($0)}.joined(separator: " ") | |
let result = "Case #\(cas): \(string)" | |
return result | |
} | |
} | |
} | |
return "Case #\(cas): IMPOSSIBLE" | |
} | |
func check(line: String, cas: Int)-> String { | |
let lineArr = getIntegersOf(line: line, separatedBy: " ") | |
let n = lineArr[0] | |
let c = lineArr[1] | |
let arr = createArray(range: n) | |
return checkList(arr: arr, cas: cas, count: c) | |
} | |
let t: Int = Int(readLine()!)! | |
var cas: Int = 0 | |
while cas < t { | |
cas += 1 | |
print(check(line: readLine()!, cas: cas)) | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment