Last active
June 3, 2022 03:29
-
-
Save hoangbits/2eddcb71cb33399f983c415b97e08697 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# =begin | |
# Mã vạch (ISBN-10) là 1 chuỗi gồm 9 chữ số (0-9) và 1 ký tự kiểm tra (ký tự này có thể là 1 chữ | |
# số hoặc chữ X). Trường hợp ký tự kiểm tra là X thì nó có giá trị bằng 10. | |
# Các ký tự có thể nối với nhau bằng dấu gạch nối '-', hoặc không có gạch nối. | |
# VD: 3-598-21508-8, 3-598-21507-X, 3598215088 | |
# Kiểm tra tính hợp lệ của mã vạch bằng công thức: | |
# (x1 * 10 + x2 * 9 + x3 * 8 + x4 * 7 + x5 * 6 + x6 * 5 + x7 * 4 + x8 * 3 + x9 * 2 + x10 * 1) mod 11 == 0 | |
# Bằng 0 thì hợp lệ. Trong đó x1->x10 lần lượt là các số từ trái sang phải (không bao gồm gạch nối) | |
# VD mã vạch 3-598-21508-8 hợp lệ vì | |
# (3 * 10 + 5 * 9 + 9 * 8 + 8 * 7 + 2 * 6 + 1 * 5 + 5 * 4 + 0 * 3 + 8 * 2 + 8 * 1) mod 11 == 0 | |
# Đề bài: | |
# Input: String | |
# Output: In ra kết quả input string có là mã vạch hợp lệ hay không. | |
# 3-598-21508-8 (valid) | |
# 3-598-21508-9 (invalid) | |
# (valid) | |
# 3-598-21507-A (invalid) | |
# 3-598-P1581-X (invalid) | |
# 3-598-2X507-9 (invalid) | |
# 3598215088 (valid) | |
# 359821507X (valid) | |
# 359821507 (invalid) | |
# 3598215078X (invalid) | |
# 00 (invalid) | |
# =end | |
def checkBarcode | |
puts "enter string ISBN : " | |
input_from_ternimal = gets.to_s.chomp | |
list_without_strike_through = input_from_ternimal.split("").difference(["-"]) | |
list_with_number_or_x = | |
list_without_strike_through.select{|val| is_number?(val) or val == "X"} | |
list_with_all_numbers = list_with_number_or_x.map{|value| (value == "X" or value == "x") ? 10 : value} | |
puts "list_without_strike_through:" | |
print list_without_strike_through | |
puts "" | |
puts "list_with_number_or_x:" | |
print list_with_number_or_x | |
puts "" | |
puts "list_with_all_numbers:" | |
print list_with_all_numbers | |
puts "" | |
if list_with_all_numbers.length == 10 | |
g = list_with_all_numbers.map.with_index { |e, i| e.to_i * (list_with_all_numbers.length - i) } | |
if g.sum % 11 == 0 | |
puts "valid" | |
else | |
puts "inalid" | |
end | |
else | |
puts "invalid" | |
end | |
end | |
# ref: https://stackoverflow.com/questions/5661466/test-if-string-is-a-number-in-ruby-on-rails/5661695 | |
def is_number? string | |
true if Float(string) rescue false | |
end | |
checkBarcode | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment