Skip to content

Instantly share code, notes, and snippets.

@donarb
Created March 26, 2016 00:21
Show Gist options
  • Save donarb/fd519025112b75ea89f9 to your computer and use it in GitHub Desktop.
Save donarb/fd519025112b75ea89f9 to your computer and use it in GitHub Desktop.
//
// Note: This is coded for an XCode Swift playground
//
import Foundation
//
// Using the last 15 characters of a FedEx ground "96" barcode, determine the check digit.
//
// From page 38 of
// http:images.fedex.com/us/solutions/ppe/FedEx_Ground_Label_Layout_Specification.pdf
//
// SHIPPER ID PACKAGE NUMBER CD
// ------------------- ------------------- --
// 1 1 1 1 1 1
// Position 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1
// Odd/Even O E O E O E O E O E O E O E O
// -------------------------------------------
// DATA 9 8 7 6 5 4 3 1 2 3 4 5 6 7 2
//
// * Add the even positions starting with pos 2 from the right
//
// 7 + 5 + 3 + 1 + 4 + 6 + 8 = 34
//
// * Multiply by 3
//
// 34 * 3 = 102
//
// * Add the odd positions starting with pos 3 from the right
//
// 6 + 4 + 2 + 3 + 5 + 7 + 9 = 36
//
// * Add two sums together
//
// 102 + 36 = 138
//
// * Subtract from next highest multiple of 10
//
// 140 - 138 = 2
//
// * The check digit is 2
//
func fedex_check_digit(str: String) -> String? {
var sum = 0
let reversedCharacters = str.characters.reverse().map { String($0) }
for (idx, element) in reversedCharacters.enumerate() {
guard let digit = Int(element) else { return nil }
switch ((idx % 2 == 1)) {
case true: sum += (idx > 0) ? digit * 3 : 0
case false: sum += (idx > 1) ? digit : 0
}
}
let x = Int(ceil(Double(sum)/10)*10)
return String(x - sum)
}
// The actual code is 9611020 9876543 12345672
let tracking_number = "987654312345672"
print("Check digit of '\(tracking_number)' is " + fedex_check_digit(tracking_number)!)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment