Skip to content

Implement exercise - luhn #249

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Apr 8, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ foreach(exercise
isogram
reverse-string
acronym
luhn
)
travis_fixup(${exercise} ${alt_exercise_tree})
add_subdirectory(${alt_exercise_tree}/${exercise})
Expand Down
24 changes: 17 additions & 7 deletions config.json
Original file line number Diff line number Diff line change
Expand Up @@ -301,7 +301,7 @@
"topics": [
"arrays",
"math"
]
]
},
{
"slug": "crypto-square",
Expand Down Expand Up @@ -389,12 +389,12 @@
"unlocked_by": null,
"difficulty": 4,
"topics": [
"control_flow_loops",
"classes",
"conditionals",
"control_flow_loops",
"pairs",
"strings",
"variables",
"pairs"
"variables"
]
},
{
Expand Down Expand Up @@ -495,7 +495,7 @@
"strings"
]
},
{
{
"slug": "binary-search",
"uuid": "abdd7aa3-25f6-4d27-a4dc-6bd1ea2f718c",
"core": false,
Expand All @@ -514,7 +514,7 @@
"core": false,
"unlocked_by": "gigasecond",
"difficulty": 10,
"topics":[
"topics": [
"algorithms",
"classes"
]
Expand All @@ -531,7 +531,17 @@
"loops",
"mathematics"
]
},
{
"slug": "luhn",
"uuid": "885865bc-a197-436f-94bc-b1998d5cc081",
"core": false,
"unlocked_by": null,
"difficulty": 1,
"topics": [
"math",
"strings"
]
}
]
}

47 changes: 47 additions & 0 deletions exercises/luhn/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
# Get the exercise name from the current directory
get_filename_component(exercise ${CMAKE_CURRENT_SOURCE_DIR} NAME)

# Basic CMake project
cmake_minimum_required(VERSION 3.1.3)

# Name the project after the exercise
project(${exercise} CXX)

# Get a source filename from the exercise name by replacing -'s with _'s
string(REPLACE "-" "_" file ${exercise})

# Implementation could be only a header
if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/${file}.cpp)
set(exercise_cpp ${file}.cpp)
else()
set(exercise_cpp "")
endif()

# Build executable from sources and headers
add_executable(${exercise} ${file}_test.cpp ${exercise_cpp} ${file}.h)

set_target_properties(${exercise} PROPERTIES
CXX_STANDARD 11
CXX_STANDARD_REQUIRED OFF
CXX_EXTENSIONS OFF
)

if("${CMAKE_CXX_COMPILER_ID}" MATCHES "(GNU|Clang)")
set_target_properties(${exercise} PROPERTIES
COMPILE_FLAGS "-Wall -Wextra -Wpedantic -Werror"
)
endif()

# Configure to run all the tests?
if(${EXERCISM_RUN_ALL_TESTS})
target_compile_definitions(${exercise} PRIVATE EXERCISM_RUN_ALL_TESTS)
endif()

# Tell MSVC not to warn us about unchecked iterators in debug builds
if(${MSVC})
set_target_properties(${exercise} PROPERTIES
COMPILE_DEFINITIONS_DEBUG _SCL_SECURE_NO_WARNINGS)
endif()

# Run the tests on every build
add_custom_target(test_${exercise} ALL DEPENDS ${exercise} COMMAND ${exercise})
104 changes: 104 additions & 0 deletions exercises/luhn/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
# Luhn

Given a number determine whether or not it is valid per the Luhn formula.

The [Luhn algorithm](https://en.wikipedia.org/wiki/Luhn_algorithm) is
a simple checksum formula used to validate a variety of identification
numbers, such as credit card numbers and Canadian Social Insurance
Numbers.

The task is to check if a given string is valid.

Validating a Number
------

Strings of length 1 or less are not valid. Spaces are allowed in the input,
but they should be stripped before checking. All other non-digit characters
are disallowed.

## Example 1: valid credit card number

```text
4539 1488 0343 6467
```

The first step of the Luhn algorithm is to double every second digit,
starting from the right. We will be doubling

```text
4_3_ 1_8_ 0_4_ 6_6_
```

If doubling the number results in a number greater than 9 then subtract 9
from the product. The results of our doubling:

```text
8569 2478 0383 3437
```

Then sum all of the digits:

```text
8+5+6+9+2+4+7+8+0+3+8+3+3+4+3+7 = 80
```

If the sum is evenly divisible by 10, then the number is valid. This number is valid!

## Example 2: invalid credit card number

```text
8273 1232 7352 0569
```

Double the second digits, starting from the right

```text
7253 2262 5312 0539
```

Sum the digits

```text
7+2+5+3+2+2+6+2+5+3+1+2+0+5+3+9 = 57
```

57 is not evenly divisible by 10, so this number is not valid.

## Getting Started

Make sure you have read the [Installing](https://exercism.io/tracks/cpp/installation) and
[Running the Tests](https://exercism.io/tracks/cpp/tests) pages for C++ on exercism.io.
This covers the basic information on setting up the development
environment expected by the exercises.

## Passing the Tests

Get the first test compiling, linking and passing by following the [three
rules of test-driven development](http://butunclebob.com/ArticleS.UncleBob.TheThreeRulesOfTdd).
Create just enough structure by declaring namespaces, functions, classes,
etc., to satisfy any compiler errors and get the test to fail. Then write
just enough code to get the test to pass. Once you've done that,
uncomment the next test by moving the following line past the next test.

```C++
#if defined(EXERCISM_RUN_ALL_TESTS)
```

This may result in compile errors as new constructs may be invoked that
you haven't yet declared or defined. Again, fix the compile errors minimally
to get a failing test, then change the code minimally to pass the test,
refactor your implementation for readability and expressiveness and then
go on to the next test.

Try to use standard C++11 facilities in preference to writing your own
low-level algorithms or facilities by hand. [CppReference](http://en.cppreference.com/)
is a wiki reference to the C++ language and standard library. If you
are new to C++, but have programmed in C, beware of
[C traps and pitfalls](http://www.slideshare.net/LegalizeAdulthood/c-traps-and-pitfalls-for-c-programmers).

## Source

The Luhn Algorithm on Wikipedia [http://en.wikipedia.org/wiki/Luhn_algorithm](http://en.wikipedia.org/wiki/Luhn_algorithm)

## Submitting Incomplete Solutions
It's possible to submit an incomplete solution so you can see how others have completed the exercise.
32 changes: 32 additions & 0 deletions exercises/luhn/example.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
#include "luhn.h"

using namespace std;

namespace luhn {
bool valid(string const& input_str) {
int result = 0;
int counter = 0;
for (auto c = input_str.rbegin(); c != input_str.rend(); c++) {
if (*c == ' ') {
continue;
} else if (isdigit(*c)) {
const int digit = (int)*c - '0';
if (counter % 2 == 1) {
result = (digit * 2 > 9) ? (result + digit * 2 - 9)
: (result + digit * 2);
} else {
result = result + digit;
}
counter++;
} else {
return false;
}
}

if (counter > 1) {
return result % 10 == 0;
} else {
return false;
}
}
} // namespace luhn
10 changes: 10 additions & 0 deletions exercises/luhn/example.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
#if !defined(LUHN_H)
#define LUHN_H

#include <string>

namespace luhn {
bool valid(std::string const&);
}

#endif // LUHN_H
Loading