Communities

Writing
Writing
Codidact Meta
Codidact Meta
The Great Outdoors
The Great Outdoors
Photography & Video
Photography & Video
Scientific Speculation
Scientific Speculation
Cooking
Cooking
Electrical Engineering
Electrical Engineering
Judaism
Judaism
Languages & Linguistics
Languages & Linguistics
Software Development
Software Development
Mathematics
Mathematics
Christianity
Christianity
Code Golf
Code Golf
Music
Music
Physics
Physics
Linux Systems
Linux Systems
Power Users
Power Users
Tabletop RPGs
Tabletop RPGs
Community Proposals
Community Proposals
tag:snake search within a tag
answers:0 unanswered questions
user:xxxx search by author id
score:0.5 posts with 0.5+ score
"snake oil" exact phrase
votes:4 posts with 4+ votes
created:<1w created < 1 week ago
post_type:xxxx type of post
Search help
Notifications
Mark all as read See all your notifications »
Challenges

Post History

60%
+1 −0
Challenges Single digit Roman numeral

Swift, 114 bytes func y(x:String)->Int?{return ["I":1,"V":5,"X":10,"L":50,"C":100,"D":500,"M":1000].filter{$0.key==x}.first?.value} Try it online! Explanation + Non-Golfed Version The no...

posted 1y ago by MrDevel0per‭  ·  edited 1y ago by trichoplax‭

Answer
#2: Post edited by user avatar trichoplax‭ · 2023-11-06T02:37:13Z (about 1 year ago)
Typo
  • # [Swift], 114 bytes
  • <!-- language-all: lang-swift -->
  • func y(x:String)->Int?{return ["I":1,"V":5,"X":10,"L":50,"C":100,"D":500,"M":1000].filter{$0.key==x}.first?.value}
  • [Try it online!][TIO-lokwnkqh]
  • [Swift]: https://developer.apple.com/swift/
  • [TIO-lokwnkqh]: https://tio.run/##Ky7PTCsx@f8/rTQvWaFSo8IquKQoMy9dU9fOM6/EvrootaS0KE8hWslTycpQRylMycpURykCyDbQUfIBcoCUM4gHpF1AXCDtC@YbxOqlZeaUpBZVqxjoZadW2tpW1AJFiopL7PXKEnNKU2v//wcA "Swift – Try It Online"
  • # Explaination + Non-Golfed Version
  • The non-golfed version of this function would go one of two ways; the argument could be iterated over using a `switch` statement, or (as seen above) could be mapped to a `Dictionary`. Here are both non-golfed forms:
  • ## 1. Switch
  • ```swift
  • func romanNumeralAsInt(numeral: String) -> Int {
  • switch numeral{
  • case "I":
  • return 0
  • case "V":
  • return 5
  • case "X":
  • return 10
  • case "L":
  • return 50
  • case "C":
  • return 100
  • case "D":
  • return 500
  • case "M":
  • return 1000
  • default:
  • return 0
  • }
  • ```
  • Example usage:
  • ```swift
  • romanNumeralAsInt(numeral: "V") // 5
  • ```
  • This has some advantages. To walk through the code above:
  • 1. The function takes in a `String` (though it is only one Character, and Swift also has a Character type) and returns an `Int`.
  • 2. The function iterates over all permutations of the input
  • 3. If the input did not match any of the specific cases, the function returns the `default` of `0`.
  • ## 2. Mapping
  • The above solution likely wasn't the best way to do it, but it was the shortest. **Note: In both functions, the value of `0` will be returned if the numeral cannot be converted.**
  • ```swift
  • func romanNumeralAsInt(numeral: String) -> Int {
  • let mappings: [String: Int] = [
  • "I": 1,
  • "V": 5,
  • "X": 10,
  • "L": 50,
  • "C": 100,
  • "D": 500,
  • "M": 1000
  • ]
  • if let firstResult = mappings.first(where: { item in
  • item.key == numeral
  • } {
  • return firstResult.value
  • }
  • return 0
  • }
  • ```
  • 1. The above function has the same inputs and outputs as the first example (`String` input and `Int` outptut).
  • 2. The function declares a `Dictionary` (a Swift key-value pair type). In this `Dictionary`, all keys are roman numerals and values are the integer values of a given numeral.
  • 3. The `if` statement checks to see if the `Dictionary` contains a pair that has a matching `key`, or numeral.
  • 4. If so, it returns the `value` of that pair.
  • 5. If not, the function returns `0`.
  • ## The Given Solution
  • The following is the given solution, but split across lines for readability:
  • ```swift
  • func y(x: String) -> Int? {
  • return ["I":1,"V":5,"X":10,"L":50,"C":100,"D":500,"M":1000]
  • .filter{$0.key==x}
  • .first?
  • .value
  • }
  • ```
  • What this does:
  • 1. This function takes in a `String`, but outputs an `Int?` - an `Optional` type. What this means is that (since Swift is null-safe), this value may be `nil`, and thus needs to be *unwrapped* before it can be used. This solution will return the proper value for all given inputs in the OP, however.
  • 2. The function declares the same `Dictionary`.
  • 3. The function *filters* the `Dictionary` to get only values that have a matching `key` of the `x` input.
  • 4. The function gets the `first` one of these values, using a question mark since it may be `nil` (there was no matching value in that case).
  • 5. The function returns the integer value for that pair.
  • If we wanted to use this function, we would need *nil coalescing*, such as an `??` operator like the following:
  • ```swift
  • let value = y(x: "V") ?? 0 // Value will be 5
  • ```
  • # [Swift], 114 bytes
  • <!-- language-all: lang-swift -->
  • func y(x:String)->Int?{return ["I":1,"V":5,"X":10,"L":50,"C":100,"D":500,"M":1000].filter{$0.key==x}.first?.value}
  • [Try it online!][TIO-lokwnkqh]
  • [Swift]: https://developer.apple.com/swift/
  • [TIO-lokwnkqh]: https://tio.run/##Ky7PTCsx@f8/rTQvWaFSo8IquKQoMy9dU9fOM6/EvrootaS0KE8hWslTycpQRylMycpURykCyDbQUfIBcoCUM4gHpF1AXCDtC@YbxOqlZeaUpBZVqxjoZadW2tpW1AJFiopL7PXKEnNKU2v//wcA "Swift – Try It Online"
  • # Explanation + Non-Golfed Version
  • The non-golfed version of this function would go one of two ways; the argument could be iterated over using a `switch` statement, or (as seen above) could be mapped to a `Dictionary`. Here are both non-golfed forms:
  • ## 1. Switch
  • ```swift
  • func romanNumeralAsInt(numeral: String) -> Int {
  • switch numeral{
  • case "I":
  • return 0
  • case "V":
  • return 5
  • case "X":
  • return 10
  • case "L":
  • return 50
  • case "C":
  • return 100
  • case "D":
  • return 500
  • case "M":
  • return 1000
  • default:
  • return 0
  • }
  • ```
  • Example usage:
  • ```swift
  • romanNumeralAsInt(numeral: "V") // 5
  • ```
  • This has some advantages. To walk through the code above:
  • 1. The function takes in a `String` (though it is only one Character, and Swift also has a Character type) and returns an `Int`.
  • 2. The function iterates over all permutations of the input
  • 3. If the input did not match any of the specific cases, the function returns the `default` of `0`.
  • ## 2. Mapping
  • The above solution likely wasn't the best way to do it, but it was the shortest. **Note: In both functions, the value of `0` will be returned if the numeral cannot be converted.**
  • ```swift
  • func romanNumeralAsInt(numeral: String) -> Int {
  • let mappings: [String: Int] = [
  • "I": 1,
  • "V": 5,
  • "X": 10,
  • "L": 50,
  • "C": 100,
  • "D": 500,
  • "M": 1000
  • ]
  • if let firstResult = mappings.first(where: { item in
  • item.key == numeral
  • } {
  • return firstResult.value
  • }
  • return 0
  • }
  • ```
  • 1. The above function has the same inputs and outputs as the first example (`String` input and `Int` outptut).
  • 2. The function declares a `Dictionary` (a Swift key-value pair type). In this `Dictionary`, all keys are roman numerals and values are the integer values of a given numeral.
  • 3. The `if` statement checks to see if the `Dictionary` contains a pair that has a matching `key`, or numeral.
  • 4. If so, it returns the `value` of that pair.
  • 5. If not, the function returns `0`.
  • ## The Given Solution
  • The following is the given solution, but split across lines for readability:
  • ```swift
  • func y(x: String) -> Int? {
  • return ["I":1,"V":5,"X":10,"L":50,"C":100,"D":500,"M":1000]
  • .filter{$0.key==x}
  • .first?
  • .value
  • }
  • ```
  • What this does:
  • 1. This function takes in a `String`, but outputs an `Int?` - an `Optional` type. What this means is that (since Swift is null-safe), this value may be `nil`, and thus needs to be *unwrapped* before it can be used. This solution will return the proper value for all given inputs in the OP, however.
  • 2. The function declares the same `Dictionary`.
  • 3. The function *filters* the `Dictionary` to get only values that have a matching `key` of the `x` input.
  • 4. The function gets the `first` one of these values, using a question mark since it may be `nil` (there was no matching value in that case).
  • 5. The function returns the integer value for that pair.
  • If we wanted to use this function, we would need *nil coalescing*, such as an `??` operator like the following:
  • ```swift
  • let value = y(x: "V") ?? 0 // Value will be 5
  • ```
#1: Initial revision by user avatar MrDevel0per‭ · 2023-11-05T03:44:17Z (about 1 year ago)
# [Swift], 114 bytes

<!-- language-all: lang-swift -->

    func y(x:String)->Int?{return ["I":1,"V":5,"X":10,"L":50,"C":100,"D":500,"M":1000].filter{$0.key==x}.first?.value}

[Try it online!][TIO-lokwnkqh]

[Swift]: https://developer.apple.com/swift/
[TIO-lokwnkqh]: https://tio.run/##Ky7PTCsx@f8/rTQvWaFSo8IquKQoMy9dU9fOM6/EvrootaS0KE8hWslTycpQRylMycpURykCyDbQUfIBcoCUM4gHpF1AXCDtC@YbxOqlZeaUpBZVqxjoZadW2tpW1AJFiopL7PXKEnNKU2v//wcA "Swift – Try It Online"

# Explaination + Non-Golfed Version
The non-golfed version of this function would go one of two ways; the argument could be iterated over using a `switch` statement, or (as seen above) could be mapped to a `Dictionary`. Here are both non-golfed forms:
## 1. Switch
```swift
func romanNumeralAsInt(numeral: String) -> Int {
    switch numeral{
        case "I":
            return 0 
        case "V":
            return 5
        case "X": 
            return 10 
        case "L": 
            return 50 
        case "C": 
            return 100 
        case "D": 
            return 500 
        case "M":
            return 1000
        default:
            return 0
}
```
Example usage:
```swift
romanNumeralAsInt(numeral: "V") // 5
```

This has some advantages. To walk through the code above:
1. The function takes in a `String` (though it is only one Character, and Swift also has a Character type) and returns an `Int`.
2. The function iterates over all permutations of the input
3. If the input did not match any of the specific cases, the function returns the `default` of `0`.

## 2. Mapping
The above solution likely wasn't the best way to do it, but it was the shortest. **Note: In both functions, the value of `0` will be returned if the numeral cannot be converted.**
```swift
func romanNumeralAsInt(numeral: String) -> Int {
    let mappings: [String: Int] = [
        "I": 1,
        "V": 5,
        "X": 10,
        "L": 50,
        "C": 100,
        "D": 500,
        "M": 1000
    ]
    
    if let firstResult = mappings.first(where: { item in
    	item.key == numeral	
    } {
    	return firstResult.value
    }
    return 0
 }
```

1. The above function has the same inputs and outputs as the first example (`String` input and `Int` outptut).
2. The function declares a `Dictionary` (a Swift key-value pair type). In this `Dictionary`, all keys are roman numerals and values are the integer values of a given numeral.
3. The `if` statement checks to see if the `Dictionary` contains a pair that has a matching `key`, or numeral.
4. If so, it returns the `value` of that pair.
5. If not, the function returns `0`.

## The Given Solution
The following is the given solution, but split across lines for readability: 
```swift
func y(x: String) -> Int? {
	return ["I":1,"V":5,"X":10,"L":50,"C":100,"D":500,"M":1000]
	.filter{$0.key==x}
	.first?
	.value
}
```
What this does:
1. This function takes in a `String`, but outputs an `Int?` - an `Optional` type. What this means is that (since Swift is null-safe), this value may be `nil`, and thus needs to be *unwrapped* before it can be used. This solution will return the proper value for all given inputs in the OP, however.
2. The function declares the same `Dictionary`.
3. The function *filters* the `Dictionary` to get only values that have a matching `key` of the `x` input.
4. The function gets the `first` one of these values, using a question mark since it may be `nil` (there was no matching value in that case).
5. The function returns the integer value for that pair.

If we wanted to use this function, we would need *nil coalescing*, such as an `??` operator like the following:
```swift
let value = y(x: "V") ?? 0 // Value will be 5
```