Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

isbn.cpp 2.0 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
  1. #include <Rcpp.h>
  2. using namespace Rcpp;
  3. // [[Rcpp::export]]
  4. char isbn_checkdigit(std::string isbn) {
  5. if (isbn.size() == 10) {
  6. int wsum = 0;
  7. for (int i = 0; i < 9; i++) {
  8. int weight = 10 - i;
  9. char c = isbn[i];
  10. int digit = c - '0';
  11. if (digit < 0 || digit > 9) {
  12. stop("'isbn' must only have digits");
  13. }
  14. wsum += digit * weight;
  15. }
  16. int cks = (11 - wsum % 11) % 11;
  17. return cks == 10 ? 'X' : '0' + cks;
  18. } else if (isbn.size() == 13) {
  19. int wsum;
  20. for (int i = 0; i < 12; i++) {
  21. int weight = i % 2 ? 3 : 1;
  22. char c = isbn[i];
  23. int digit = c - '0';
  24. if (digit < 0 || digit > 9) {
  25. stop("'isbn' must only have digits");
  26. }
  27. wsum += weight * digit;
  28. }
  29. int mod = 10 - (wsum % 10);
  30. return mod == 10 ? '0' : ('0' + mod);
  31. } else {
  32. stop("'isbn' must have length 10 or 13");
  33. }
  34. }
  35. bool is_valid_isbn(std::string isbn) {
  36. size_t len = isbn.size();
  37. if (len == 10) {
  38. int wsum = 0;
  39. for (int j = 0; j < len; j++) {
  40. char c = isbn[j];
  41. int digit = c == 'X' ? 10 : c - '0';
  42. if (c < 0 || c > 10) return false;
  43. wsum += digit * (10 - j);
  44. }
  45. return (wsum % 11) == 0;
  46. } else if (len == 13) {
  47. int wsum = 0;
  48. for (int j = 0; j < len; j++) {
  49. char c = isbn[j];
  50. int digit = c - '0';
  51. if (c < 0 || c > 9) return false;
  52. wsum += digit * (j % 2 ? 3 : 1);
  53. }
  54. return (wsum % 10) == 0;
  55. } else {
  56. return false;
  57. }
  58. }
  59. // [[Rcpp::export]]
  60. LogicalVector is_valid_isbn(CharacterVector isbns) {
  61. int n = isbns.size();
  62. LogicalVector out(n);
  63. for (int i = 0; i < n; i++) {
  64. String ri = isbns[i];
  65. std::string isbn = ri;
  66. out[i] = is_valid_isbn(isbn);
  67. }
  68. return out;
  69. }
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...