Repository navigation
Expand file tree
/
Copy path수식 최대화.swift
More file actions
73 lines (58 loc) · 1.93 KB
/
Copy path수식 최대화.swift
File metadata and controls
73 lines (58 loc) · 1.93 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
//
// 수식 최대화.swift
// Programmers1
//
// Created by hwangJi on 2023/03/27.
//
import Foundation
func solution(expression:String) -> Int64 {
let numArr = expression.split(whereSeparator: { $0 == "+" || $0 == "*" || $0 == "-" }).map({ Int($0)! })
let operArr = expression.split(whereSeparator: { $0.isNumber }).map({ String($0) })
let formulaPermutation = permutation(Array(Set(operArr)), Set(operArr).count)
var maxValue = 0
for i in formulaPermutation {
maxValue = max(maxValue, calbyFormula(i, operArr, numArr))
}
return Int64(maxValue)
}
// 우선순위 수식 기반으로 값을 계산하는 메서드
func calbyFormula(_ priority: [String], _ operArr: [String], _ numArr: [Int]) -> Int {
var numArr = numArr
var operArr = operArr
for i in priority {
while operArr.contains(String(i)) {
let idx = operArr.firstIndex(of: String(i)) ?? -1
if i == "*" {
numArr[idx] = numArr[idx] * numArr[idx + 1]
} else if i == "+" {
numArr[idx] = numArr[idx] + numArr[idx + 1]
} else {
numArr[idx] = numArr[idx] - numArr[idx + 1]
}
numArr.remove(at: idx + 1)
operArr.remove(at: idx)
}
}
return abs(numArr[0])
}
// 순열 생성 메서드
func permutation(_ array: [String], _ n: Int) -> Set<[String]> {
var result = Set<[String]>()
if array.count < n { return result }
var visited = Array(repeating: false, count: array.count)
func cycle(_ now: [String]) {
if now.count == n {
result.insert(now)
return
}
for i in 0..<array.count {
if !visited[i] {
visited[i] = true
cycle(now + [array[i]])
visited[i] = false
}
}
}
cycle([])
return result
}