Problem 93: Arithmetic expressions

By using each of the digits from the set, {1, 2, 3, 4}, exactly once, and making use of the four arithmetic operations (+, -, *, /) and brackets/parentheses,
it is possible to form different positive integer targets.

Note that concatenations of the digits, like 12 + 34, are not allowed.

Using the set, {1, 2, 3, 4}, it is possible to obtain thirty-one different target numbers of which 36 is the maximum,
and each of the numbers 1 to 28 can be obtained before encountering the first non-expressible number.

Find the set of four distinct digits, a < b < c < d, for which the longest set of consecutive positive integers, 1 to n,
can be obtained, giving your answer as a string: abcd.

My Algorithm

No matter what brackets or operators are used, the basic pattern is always the same:
1. an operation on two out of the four numbers is executed
2. the result will become part of the equation which consists now of three numbers
3. an operation on two out of the three numbers is executed
4. the result will become part of the equation which consists now of two numbers
5. an operation on the final two numbers is executed

I generate all sets of digits {a, b, c, d} where a < b < c < d. There are 126 such sets and four nested loops produce these sets in main.
My eval function accepts an arbitrary set of numbers and does the following:

pick any two numbers and execute all operations on these numbers, thus reducing numbers by one element

call itself recursively

when only one element is left in numbers then mark the result as used

There a a few pitfalls:

values may temporarily be non-integer, e.g. (1/3)*6+7 = 9, but may produce a valid integer result.

Especially the first pitfall (rational numbers) is tough to handle without floating-point numbers.
However, double (or float) may have some rounding issues, that's why I added an Epsilon to make sure that results like 3.9999 are treated as 4.

getSequenceLength is the glue between main and eval:
It finds the first gap, that means the first number not represented by any combination of arithmetic operations.

Interactive test

You can submit your own input to my program and it will be instantly processed at my server:

Number of test cases (1-5):

Input data (separated by spaces or newlines):

This is equivalent toecho "1 " | ./93

Output:

(please click 'Go !')

(this interactive test is still under development, computations will be aborted after one second)

My code

… was written in C++11 and can be compiled with G++, Clang++, Visual C++. You can download it, too.

The code contains #ifdefs to switch between the original problem and the Hackerrank version.Enable #ifdef ORIGINAL to produce the result for the original problem (default setting for most problems).

#include<vector>

#include<iostream>

#include<cmath>

constdouble Epsilon = 0.00001;

// try all arithmetic operations of any two elements of "numbers", set their result in "used" to true

voideval(conststd::vector<double>& numbers, std::vector<bool>& used)

{

// 1. if array holds just one element, add it to the "used" list and we are done

// 2. pick any two numbers

// 3. loop through all operators

// 4. add result to the array and call eval() recursively

// step 1

if (numbers.size() == 1)

{

auto result = numbers.front() + Epsilon;

// reject non-integer result (caused by division)

if (fmod(result, 1) > 10*Epsilon)

return;

int index = int(result + Epsilon);

// reject negative and very large results

if (index >= 0 && index < (int)used.size())

used[index] = true;

return;

}

// step 2

auto next = numbers;

for (size_t i = 0; i < numbers.size(); i++)

for (size_t j = i + 1; j < numbers.size(); j++)

{

// fetch two numbers

double a = numbers[i];

double b = numbers[j];

// prepare for next recursive step

next = numbers;

next.erase(next.begin() + j); // delete the higher index first

next.erase(next.begin() + i);

// steps 3 and 4 (unrolled)

next.push_back(a + b); // add

eval(next, used);

next.back() = a - b; // subtract (I)

eval(next, used);

next.back() = b - a; // subtract (II)

eval(next, used);

next.back() = a * b; // multiply

eval(next, used);

if (b != 0)

{

next.back() = a / b; // divide (I)

eval(next, used);

}

if (a != 0)

{

next.back() = b / a; // divide (II)

eval(next, used);

}

// note: I overwrite the last element because that's simpler than

// pop_back(); push_back(...);

}

}

// evaluate all expressions and count how many numbers from 1 to x can be expressed without any gaps

Changelog

Hackerrank

Difficulty

15%
Project Euler ranks this problem at 15% (out of 100%).

Hackerrank describes this problem as medium.

Note:Hackerrank has strict execution time limits (typically 2 seconds for C++ code) and often a much wider input range than the original problem.In my opinion, Hackerrank's modified problems are usually a lot harder to solve. As a rule thumb: brute-force is rarely an option.

Those links are just an unordered selection of source code I found with a semi-automatic search script on Google/Bing/GitHub/whatever.
You will probably stumble upon better solutions when searching on your own.
Maybe not all linked resources produce the correct result and/or exceed time/memory limits.

Heatmap

Please click on a problem's number to open my solution to that problem:

green

solutions solve the original Project Euler problem and have a perfect score of 100% at Hackerrank, too

yellow

solutions score less than 100% at Hackerrank (but still solve the original problem easily)

gray

problems are already solved but I haven't published my solution yet

blue

solutions are relevant for Project Euler only: there wasn't a Hackerrank version of it (at the time I solved it) or it differed too much

orange

problems are solved but exceed the time limit of one minute or the memory limit of 256 MByte

red

problems are not solved yet but I wrote a simulation to approximate the result or verified at least the given example - usually I sketched a few ideas, too

black

problems are solved but access to the solution is blocked for a few days until the next problem is published

[new]

the flashing problem is the one I solved most recently

I stopped working on Project Euler problems around the time they released 617.

The 310 solved problems (that's level 12) had an average difficulty of 32.6&percnt; at Project Euler and
I scored 13526 points (out of 15700 possible points, top rank was 17 out of &approx;60000 in August 2017)
at Hackerrank's Project Euler+.

My username at Project Euler is stephanbrumme while it's stbrumme at Hackerrank.

Copyright

I hope you enjoy my code and learn something - or give me feedback how I can improve my solutions.All of my solutions can be used for any purpose and I am in no way liable for any damages caused.You can even remove my name and claim it's yours. But then you shall burn in hell.

The problems and most of the problems' images were created by Project Euler.Thanks for all their endless effort !!!

more about me can be found on my homepage,
especially in my coding blog.
some names mentioned on this site may be trademarks of their respective owners.
thanks to the KaTeX team for their great typesetting library !