Sha256: d0e1a4a68d507e35aad3d695d3bb9ee428abe7dd1e32ca8ad31c3564e0100442

Contents?: true

Size: 1.42 KB

Versions: 396

Compression:

Stored size: 1.42 KB

Contents

enum BaseError: Error {
    case invalidInputBase
    case invalidOutputBase
    case negativeDigit
    case invalidPositiveDigit
}

struct Base {

    static func outputDigits(inputBase: Int, inputDigits: [Int], outputBase: Int) throws -> [Int] {
        guard inputBase >= 2 else {
            throw BaseError.invalidInputBase
        }

        guard outputBase >= 2 else {
            throw BaseError.invalidOutputBase
        }

        let sum = try getSum(inputDigits, base: inputBase)
        let result = getDigits(sum, base: outputBase)

        return result
    }

    private static func getSum(_ digits: [Int], base: Int) throws -> Int {
        var multiplier = 1
        var sum = 0

        for digit in digits.reversed() {
            guard digit >= 0 else {
                throw BaseError.negativeDigit
            }
            guard digit < base else {
                throw BaseError.invalidPositiveDigit
            }

            sum += digit * multiplier
            multiplier *= base
        }

        return sum
    }

    private static func getDigits(_ sum: Int, base: Int) -> [Int] {
        var sum = sum
        var digits = [Int]()
        var multiplier = 1

        while sum > 0 {
            multiplier *= base
            let value = sum % multiplier
            let digit = value / (multiplier / base)
            digits.append(digit)
            sum -= value
        }

        return digits.reversed()
    }
}

Version data entries

396 entries across 396 versions & 1 rubygems

Version Path
trackler-2.0.0.5 tracks/swift/exercises/all-your-base/AllYourBaseExample.swift
trackler-2.0.0.4 tracks/swift/exercises/all-your-base/AllYourBaseExample.swift
trackler-2.0.0.3 tracks/swift/exercises/all-your-base/AllYourBaseExample.swift
trackler-2.0.0.2 tracks/swift/exercises/all-your-base/AllYourBaseExample.swift
trackler-2.0.0.1 tracks/swift/exercises/all-your-base/AllYourBaseExample.swift
trackler-2.0.0.0 tracks/swift/exercises/all-your-base/AllYourBaseExample.swift
trackler-1.0.4.1 tracks/swift/exercises/all-your-base/AllYourBaseExample.swift
trackler-1.0.4.0 tracks/swift/exercises/all-your-base/AllYourBaseExample.swift
trackler-1.0.3.0 tracks/swift/exercises/all-your-base/AllYourBaseExample.swift
trackler-1.0.2.1 tracks/swift/exercises/all-your-base/AllYourBaseExample.swift
trackler-1.0.2.0 tracks/swift/exercises/all-your-base/AllYourBaseExample.swift
trackler-1.0.1.2 tracks/swift/exercises/all-your-base/AllYourBaseExample.swift
trackler-1.0.1.1 tracks/swift/exercises/all-your-base/AllYourBaseExample.swift
trackler-1.0.1.0 tracks/swift/exercises/all-your-base/AllYourBaseExample.swift
trackler-1.0.0.1 tracks/swift/exercises/all-your-base/AllYourBaseExample.swift
trackler-1.0.0 tracks/swift/exercises/all-your-base/AllYourBaseExample.swift