Just Math 24 Game

Just math 24 is a Math Game created with swift

struct Data {

let value : Int

let description: String

static func + (a : Data, b: Data)-> Data{

return Data(value: a.value+b.value,

description: "( (a.description) + (b.description) )")}

static func - (a : Data, b: Data)-> Data{

return Data(value: a.value-b.value,

description: "( (a.description) - (b.description) )")}

static func * (a : Data, b: Data)-> Data{

return Data(value: a.value*b.value,

description: "( (a.description) * (b.description) )")}

static func / (a : Data, b: Data)-> Data{

return Data(value: a.value/b.value,

description: "( (a.description) / (b.description) )")}}

func additive(_ a: [[Data]],_ b : Data) -> [[[Data]]] {

return a.compactMap{ stride(from: ($0.count)-1, through: 0, by: -1).reduce( [[$0 + [b]]], {

let index = $1

return $0 + $0.last!.compactMap{

let array = $0

let aa = array[index + 1]

let bb = array[index]

return (aa.value == 0 ? [(bb+aa), (bb-aa) , (bb*aa)]

.map{[Data](array.dropLast(2)) + [$0]}

: [(bb+aa), (bb-aa) , (bb*aa) , (bb/aa)]

.map{ [Data](array.dropLast(2)) + [$0] })}}).flatMap{$0}}}

func Calculate24(_ a: [Int]) -> String {

let a = a.map{Data(value: $0, description: "($0)")}

return a.dropFirst().reduce([[a.first!]], {

additive($0, $1).flatMap{$0}

}).filter{$0.count == 1 && $0[0].value == 24}

.map{$0[0].description}.joined(separator: " ")

}

Home
@2019 Just Math 24 Game