Sudoku checker algorithm in C++ - c++

I'm currently working on an algorithm to find all numbers with 9 digits using numbers 1-9 without any repeats. I'm testing a theory I have that filtering numbers as such will make for a more efficient sudoku checker.
The code that I implemented does the following. It uses a for loop for places 1-9 in a number, such that (a)(b)(c)(d)(e)(f)(g)(h)(i) = #########.
My theory is that by checking if the sum of the numbers (a-i) is equal to 45, that the product of a through i is equal to 9! and that the sum of the inverses of a-i is equal to roughly 2.828968 (or 1 + 1/2 + 1/3 ... 1/9)
The issue is that after I filter the 9-digit numbers by the sum of the inverses of a-i, the count of possible 9-digit numbers predicted is less than 9! (the actual amount of possible numbers). I'm not sure why it's filtering so much, but the numbers that it does catch do not have any repeats (which is good).
My thoughts are that the way I am playing with doubles is messing up the algorithm.
Here is my code:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int product;
int sum;
int count=0;
double inverseSum;
double correctInverseSum=(1.0/1.0)+(1.0/2.0)+(1.0/3.0)+(1.0/4.0)+(1.0/5.0)+
(1.0/6.0)+(1.0/7.0)+(1.0/8.0)+(1.0/9.0);
for(double a=1.0; a<10.0; a++){
for(double b=1.0; b<10.0; b++){
for(double c=1.0; c<10.0; c++){
for(double d=1.0; d<10.0; d++){
for(double e=1.0; e<10.0; e++){
for(double f=1.0; f<10.0; f++){
for(double g=1.0; g<10.0; g++){
for(double h=1.0; h<10.0; h++){
for(double i=1.0; i<10.0; i++){
product=a*b*c*d*e*f*g*h*i;
sum=a+b+c+d+e+f+g+h+i;
if(product==9*8*7*6*5*4*3*2*1 && sum==45){
inverseSum=(1.0/a)+(1.0/b)+(1.0/c)+(1.0/d)+
(1.0/e)+(1.0/f)+(1.0/g)+(1.0/h)+(1.0/i);
if(inverseSum==correctInverseSum)
{
count++;
}
}
}
}
}
}
}
}
}
}
}
cout<<"This is the count:"<<count<<endl;
return 0;
}

Now that I washed my eyes after seeing so many for loops, I'd say a candidate is:
if(inverseSum==correctInverseSum)
doubles aren't exactly representable, so you'll have to check for equality using a small epsilon. Something like:
if (fabs(inverseSum - correctInverseSum) < std::numeric_limits<double>::epsilon())
You'll need to #include <limits>.

You're going to need some error tolerance in your checking:
if(fabs(inverseSum-correctInverseSum) < 1e-6) count++
Alternatively, multiply through by 9!, you get
b*c*d*e*f*g*h*i + a*c*d*e*f*g*h*i ...
(one missing factor in each term the sum). Then you can use integer arithmetic instead of floats.

Let's run a quick experiment: Let's try to compute the inverse sum from big to small and in reverse order:
#include <algorithm>
#include <numeric>
#include <iostream>
#include <iterator>
#include <vector>
struct generator
{
generator(): d_value() {}
double operator()() { return 1.0 / ++this->d_value; }
double d_value;
};
int main()
{
std::vector<double> values;
std::generate_n(std::back_inserter(values), 9, generator());
double ordered(std::accumulate(values.begin(), values.end(), 0.0));
double reversed(std::accumulate(values.rbegin(), values.rend(), 0.0));
std::cout << "ordered=" << ordered << " "
<< "reversed=" << reversed << " "
<< "difference=" << (reversed - ordered) << " "
<< "\n";
}
If this where exact math, clearly this should yield the same sum. After all, they are the same set of values. Unfortunately, it turns out that the values are not exactly the same. Here is the output it shows for me:
ordered=2.82897 reversed=2.82897 difference=4.44089e-16
The problem is that the values are not exact and adding two of these non-exact values introduces some error. Often the error doesn't matter too much but trying to compare the results for identity won't work: depending on the order of the operations different operands with different rounded results are involved.

An old adage, but please: Don't repeat yourself.
Keep it DRY.
When you find yourself writing this kind of code you should ask yourself why Do I need to repeat myself in this way.
There are plenty of other options.
1 - recursion. get yourself comfortable with the concept.
2 - the mod operator for i = 0 to 100 r = i % 10, c = i / 10
3 - reevaluating the problem. You are trying to solve a problem that is harder than necessary

Haven't you heard about std::bitset? You only need nine bits to verify, which is probably within your budget.
I've been meaning to get some practice with variadic templates, so I wrote this for you: (c++11 experts, feel free to rip it to pieces.)
#include <bitset>
#include <iostream>
template<unsigned long i>
bool test_helper(std::bitset<i> seen) {
return seen.count() == i;
}
template<unsigned long i, typename T, typename... Args>
bool test_helper(std::bitset<i> seen, T arg1, Args... args) {
return test_helper(seen.set(arg1 - 1), args...);
}
template<typename... Args>
bool test(Args... args) {
return test_helper(std::bitset<sizeof... (Args)>(), args...);
}
template<unsigned long size, bool done = false>
struct Counter {
template<typename ... Args>
unsigned long operator()(Args... args) {
unsigned long count = 0;
for (int a = 1; a < 10; ++a)
count += Counter<size, size == sizeof...(Args)+1>()(a, args...);
return count;
}
};
template<unsigned long i>
struct Counter<i, true> {
template<typename ... Args>
unsigned long operator()(Args... args) {
return test(args...);
}
};
int main(int argc, char** argv) {
std::cout << Counter<9>()() << std::endl;
return 0;
}
If you really insist on using complicated and heuristics, you could also get some experience with rational arithmetic to compute your inverse sum. It should be clear sum of 1/ai is Σj (Πi ai)/aj all divided by Πi ai; you're already computing the denominator, so it only is necessary to compute the numerator, whose maximum value is 99. But, still, the bitset solution seems a lot simpler to me.

Related

C++ function to approximate sine using taylor series expansion

Hi I am trying to calculate the results of the Taylor series expansion for sine to the specified number of terms.
I am running into some problems
Your task is to implement makeSineToOrder(k)
This is templated by the type of values used in the calculation.
It must yield a function that takes a value of the specified type and
returns the sine of that value (in the specified type again)
double factorial(double long order){
#include <iostream>
#include <iomanip>
#include <cmath>
double fact = 1;
for(int i = 1; i <= num; i++){
fact *= i;
}
return fact;
}
void makeSineToOrder(long double order,long double precision = 15){
double value = 0;
for(int n = 0; n < precision; n++){
value += pow(-1.0, n) * pow(num, 2*n+1) / factorial(2*n + 1);
}
return value;
int main()
{
using namespace std;
long double pi = 3.14159265358979323846264338327950288419716939937510L;
for(int order = 1;order < 20; order++) {
auto sine = makeSineToOrder<long double>(order);
cout << "order(" << order << ") -> sine(pi) = " << setprecision(15) << sine(pi) << endl;
}
return 0;
}
I tried debugging
here is a version that at least compiles and gives some output
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
double factorial(double long num) {
double fact = 1;
for (int i = 1; i <= num; i++) {
fact *= i;
}
return fact;
}
double makeSineToOrder(double num, double precision = 15) {
double value = 0;
for (int n = 0; n < precision; n++) {
value += pow(-1.0, n) * pow(num, 2 * n + 1) / factorial(2 * n + 1);
}
return value;
}
int main(){
long double pi = 3.14159265358979323846264338327950288419716939937510L;
for (int order = 1; order < 20; order++) {
auto sine = makeSineToOrder(order);
cout << "order(" << order << ") -> sine(pi) = " << setprecision(15) << sine << endl;
}
return 0;
}
not sure what that odd sine(pi) was supposed to be doing
Apart the obvious syntax errors (the includes should be before your factorial header) in your code:
I see no templates in your code which your assignment clearly states to use
so I would expect template like:
<class T> T mysin(T x,int n=15){ ... }
using pow for generic datatype is not safe
because inbuild pow will use float or double instead of your generic type so you might expect rounding/casting problems or even unresolved function in case of incompatible type.
To remedy that you can rewrite the code to not use pow as its just consequent multiplication in loop so why computing pow again and again?
using factorial function is waste
you can compute it similar to pow in the same loop no need to compute the already computed multiplications again and again. Also not using template for your factorial makes the same problems as using pow
so putting all together using this formula:
along with templates and exchanging pow,factorial functions with consequent iteration I got this:
template <class T> T mysin(T x,int n=15)
{
int i;
T y=0; // result
T x2=x*x; // x^2
T xi=x; // x^i
T ii=1; // i!
if (n>0) for(i=1;;)
{
y+=xi/ii; xi*=x2; i++; ii*=i; i++; ii*=i; n--; if (!n) break;
y-=xi/ii; xi*=x2; i++; ii*=i; i++; ii*=i; n--; if (!n) break;
}
return y;
}
so factorial ii is multiplied by i+1 and i+2 every iteration and power xi is multiplied by x^2 every iteration ... the sign change is hard coded so for loop does 2 iterations per one run (that is the reason for the break;)
As you can see this does not use anything funny so you do not need any includes for this not even math ...
You might want to add x=fmod(x,6.283185307179586476925286766559) at the start of mysin in order to use more than just first period however in that case you have to ensure fmod implementation uses T or compatible type to it ... Also the 2*pi constant should be in target precision or higher
beware too big n will overflow both int and generic type T (so you might want to limit n based on used type somehow or just use it wisely).
Also note on 32bit floats you can not get better than 5 decimal places no matter what n is with this kind of computation.
Btw. there are faster and more accurate methods of computing goniometrics like Chebyshev and CORDIC

Power function in a loop

I need help with writing power function. So, I need to write a porogramm, that will output a table from 1 to 10 in a power in a LOOP. NOT USING POW or EXP
Example of output:
0^0 == 1
1^1 == 1
2^2 == 4
3^3 == 27
4^4 == 256
(and so on, up to)
10^10 == 10000000000
NOT USING Cmath (NO POW or EXP)
for example:
e.g. power( 3.0, 5 ) will return 243 because 3*3*3*3*3 is 243
e.g. power( 173, 0 ) will return 1 because any number raised to the power of 0 is 1.
I did this Simple loop, But I have no idea how to insert power formula in it. I was also thinking about while loop
#include <iostream>
#include <string>
using namespace std;
int main(){
int number = 0, tot;
for (int table = 0; table < 10; table++)
{
tot = number * table;
cout << tot << endl;
number++;
}
}
This is a recursive function that can calculate a value raised to an integer power
double power(double base, unsigned int exp)
{
if (exp == 0)
{
return 1.0;
}
else
{
return base * power(base, exp - 1);
}
}
An iterative method to do this would be
double power(double base, unsigned int exp)
{
double product = 1.0;
for (unsigned int i = 0; i < exp; ++i)
{
product *= base;
}
return product;
}
You can test either method with something like
int main()
{
std::cout << power(5, 3);
}
Output
125
I think you already know the answer to your own question by now, but still; some hints:
Exponentiation is a repeated multiplication of the base, the repetition is defined by the exponent.
In C++, or any modern programming language, loops allow repetition of certain blocks of code: when the number of iterations is known beforehand, use the for-loop, otherwise, use the while-loop.
Combining both hints: you'll need to use a loop to repeat a multiplication; the amount of repetition (or iterations) is known beforehand, thus, a for-loop will be best.
int exponentiation(int base, int exponent) {
int result = 1;
for (int i = 0; i < exponent; ++i)
result = result * base;
return result;
}
Note: this will only suffice for integer exponentiation with positive exponents!
You can then call this function in a for-loop to let it compute the values you want:
#include <iostream>
int main(int argc, char** argv) {
for(int i = 0; i <= 10; ++i)
std::cout << exponentiation(i, i) << '\n';
}

Determining if square root is an integer

In my program, I am trying to take the find the largest prime factor of the number 600851475143. I have made one for loop that determines all the factors of that number and stores them in a vector array. The problem I am having is that I don't know how to determine if the factor can be square rooted and give a whole number rather than a decimal. My code so far is:
#include <iostream>
#include <vector>
#include <math.h>
using namespace std;
vector <int> factors;
int main()
{
double num = 600851475143;
for (int i=1; i<=num; i++)
{
if (fmod(num,i)==0)
{
factors.push_back(i);
}
}
for (int i=0; i<factors.size(); i++)
{
if (sqrt(factor[i])) // ???
}
}
Can someone show me how to determine whether a number can be square rooted or not through my if statement?
int s = sqrt(factor[i]);
if ((s * s) == factor[i])
As hobbs pointed out in the comments,
Assuming that double is the usual 64-bit IEEE-754 double-precision float, for values less than 2^53 the difference between one double and the next representable double is less than or equal to 1. Above 2^53, the precision is worse than integer.
So if your int is 32 bits you are safe. If you have to deal with numbers bigger than 2^53, you may have some precision errors.
Perfect squares can only end in 0, 1, 4, or 9 in base 16, So for 75% of your inputs (assuming they are uniformly distributed) you can avoid a call to the square root in exchange for some very fast bit twiddling.
int isPerfectSquare(int n)
{
int h = n & 0xF; // h is the last hex "digit"
if (h > 9)
return 0;
// Use lazy evaluation to jump out of the if statement as soon as possible
if (h != 2 && h != 3 && h != 5 && h != 6 && h != 7 && h != 8)
{
int t = (int) floor( sqrt((double) n) + 0.5 );
return t*t == n;
}
return 0;
}
usage:
for ( int i = 0; i < factors.size(); i++) {
if ( isPerfectSquare( factor[ i]))
//...
}
Fastest way to determine if an integer's square root is an integer
The following should work. It takes advantage of integer truncation.
if (int (sqrt(factor[i])) * int (sqrt(factor[i])) == factor[i])
It works because the square root of a non-square number is a decimal. By converting to an integer, you remove the fractional part of the double. Once you square this, it is no longer equal to the original square root.
You also have to take into account the round-off error when comparing to cero. You can use std::round if your compiler supports c++11, if not, you can do it yourself (here)
#include <iostream>
#include <vector>
#include <math.h>
using namespace std;
vector <int> factors;
int main()
{
double num = 600851475143;
for (int i=1; i<=num; i++)
{
if (round(fmod(num,i))==0)
{
factors.push_back(i);
}
}
for (int i=0; i<factors.size(); i++)
{
int s = sqrt(factor[i]);
if ((s * s) == factor[i])
}
}
You are asking the wrong question. Your algorithm is wrong. (Well, not entirely, but if it were to be corrected following the presented idea, it would be quite inefficient.) With your approach, you need also to check for cubes, fifth powers and all other prime powers, recursively. Try to find all factors of 5120=5*2^10 for example.
The much easier way is to remove a factor after it was found by dividing
num=num/i
and only increase i if it is no longer a factor. Then, if the iteration encounters some i=j^2 or i=j^3,... , all factors j, if any, were already removed at an earlier stage, when i had the value j, and accounted for in the factor array.
You could also have mentioned that this is from the Euler project, problem 3. Then you would have, possibly, found the recent discussion "advice on how to make my algorithm faster" where more efficient variants of the factorization algorithm were discussed.
Here is a simple C++ function I wrote for determining whether a number has an integer square root or not:
bool has_sqrtroot(int n)
{
double sqrtroot=sqrt(n);
double flr=floor(sqrtroot);
if(abs(sqrtroot - flr) <= 1e-9)
return true;
return false;
}
As sqrt() function works with floating-point it is better to avoid working with its return value (floating-point calculation occasionally gives the wrong result, because of precision error). Rather you can write a function- isSquareNumber(int n), which will decide if the number is a square number or not and the whole calculation will be done in integer.
bool isSquareNumber(int n){
int l=1, h=n;
while(l<=h){
int m = (l+h) / 2;
if(m*m == n){
return true;
}else if(m*m > n){
h = m-1;
}else{
l = m+1;
}
}
return false;
}
int main()
{
// ......
for (int i=0; i<factors.size(); i++){
if (isSquareNumber(factor[i]) == true){
/// code
}
}
}

Split floating point number into fractional and integral parts

I'm writing a template class designed to work with any floating point type. For some of the methods I need to split a number into its integral and fractional parts. With primitive floating point types I can just cast to an integer to truncate the fractional part, but this wouldn't work with a big number class. Ideally my class would only use the four basic arithmetic operations (addition, subtraction, multiplication, division) in its calculations.
The method below is the solution I came up with. All it does is subtract powers of ten until the original number is less than 1. It works well, but seems like a brute-force approach. Is there a more efficient way to do this?
template< typename T >
class Math
{
public:
static T modf( T const & x, T & intpart )
{
T sub = 1;
T ret = x;
while( x >= sub )
{
sub *= 10;
}
sub /= 10;
while( sub >= 1 )
{
while( ret >= sub )
{
ret -= sub;
}
sub /= 10;
}//while [sub] > 0
intpart = x - ret;
return ret;
}
}
Note that I've removed the sign management code for brevity.
You could perhaps replace the subtraction loop with a binary search, although that's not an improvement in complexity class.
What you have requires a number of subtractions approximately equal to the sum of the decimal digits of x, whereas a binary search requires a number of addition-and-divide-by-two operations approximately equal to 3-and-a-bit times the number of decimal digits of x.
With what you're doing and with the binary search, there's no particular reason to use powers of 10 when looking for the upper bound, you could use any number. Some other number might be a bit quicker on average, although it probably depends on the type T.
Btw, I would also be tempted to make modf a function template within Math (or a free template function in a namespace), rather than Math a class template. That way you can specialize or overload one function at a time for particular types (especially the built-in types) without having to specialize the whole of Math.
Example:
namespace Math
{
template <typename T>
T modf( T const & x, T & intpart )
{ ... }
}
Call it like this:
float f = 1.5, fint;
std::cout << Math::modf(f, fint) << '\n';
double d = 2.5, dint;
std::cout << Math::modf(d, dint) << '\n';
mpf_class ff(3.5), ffint(0); // GNU multi-precision
std::cout << Math::modf(ff, ffint) << '\n';
Overload it like this:
namespace Math {
double modf(double x, double &intpart) {
return std::modf(x, &intpart);
}
mpf_class modf(const mpf_class &x, mpf_class &intpart) {
intpart = floor(x);
return x - intpart;
}
}
mb use std::modf is better?
for custom type you can release Math class specialization.
#include <cmath>
#include <iostream>
template<typename T>
class Math
{
public:
static T modf(const T& x, T& integral_part)
{
return std::modf(x, &integral_part);
}
};
int main()
{
double d_part = 0.;
double res = Math<double>::modf(5.2123, d_part);
std::cout << d_part << " " << res << std::endl;
}
I don't know how strict your "ideally use only mathematical operations" restraint is, but nonetheless for the fractional part, could you extract it to a string and convert back to a float?

print number in reverse

im simple asking if this is ok. i was asked to do the following. Write a program that will continuously ask the user for positive integers (until the
user enters a negative integer at which the program will be terminated). Every
time the user inputs a positive integer the program will print out this integer in
reverse. Your program should have a function that accepts and integer and returns
an integer in reverse. To convert the integer to its reverse, your program will call
this function. at the end of each output i keep getting 0. please explain why. also if i use void main with the function i get garbage. please explain why. thanks in advance
this is my code....
#include<iostream>
#include<cstdlib>
using namespace std;
int reverseNum(int num){
for(int j=num; j>0; j--)
cout<<j<<" ";
cout<<endl;
return false;
}
int main(){
double enternum = 0;
do{
cout<<"Enter a positive number > 0, to begin countdown ";
cin >>enternum;
cout<<reverseNum(enternum);
cout<<endl;
}
while(enternum>0);
if(enternum<=0)
cout<<"Invalid entry, good bye.";
cout<<endl;
return 0;
}
because of this: return false; - I'll leave it to you to figure out the rest..
The function is supposed to reverse the integer and then return the result. For example, if the input is 123, then the function returns 321.
Your function outputs a count-down and returns 0 (=false).
To reverse a number, you can a) convert it to string, reverse the string, convert it back to integer; b) do it on integers directly with mathematical division / multiplication / addition / modulo operations.
In C++, you don't use void main().
A 0 because when you return false, the result of type bool is implicitly converted to an int and gets printed at the line cout<<reverseNum(enternum);
Also, In this line, double enternum = 0; you want an integer int.
From your text I thought the program was working as intended, but from reading the code I suppose it just counts down from the number. Was this what you wanted?
I'd have implemented it like this (and here the function returning an integer makes sense too):
int reverseNum(int num)
{
int reverse = 0;
[...] // Do the actual reversing
return reverse;
}
Your program should have a function that accepts and integer and returns an integer in reverse
your reverseNum function should return the reversed integer, not false. and it shouldn't print the number as well, it's the caller which supposed to print it.
if one does:
i = reverseNum(1234);
then i should contain 4321 as an integer (NOT string).
the reason you keep getting 0 is because false is equivalent to 0 as an integer.
You should read the C++ FAQ in its entirety. You should especially read this. You should also learn how to debug your code. If you stepped through your code in a debugger then all the answers that you have been given here will be obvious.
For good fun, I attempted a generic implementation that supports any integral or floating point type supported by your compiler.
Be warned, there are a number of issues:
reversing a floating point number is not well defined semantically (how to position the decimal separator? How do we handle exponential notation?)
floating point types are frequently inexact (at least common IEEE formats are) and hence scaling the input will introduce artificial fractional digits. I have not taken much effort to do proper rounding, so some numbers will reverse into strange things (e.g. 123.0 could reverse into 992.1 instead of 321.0 (untested for this input, try some yourself))
the implementation is laughably template-happy. Think of it as the instructional part of this playful answer.
Oh, uncomment the DEBUGTRACE definition to ... get debug tracing :)
See it live here [click]TM
#include <cmath>
#include <limits>
#include <iostream>
#define MAX_DECIMAL_FRACTION 5
#define DEBUGTRACE(x) // do { std::cerr << x; } while (false)
template <typename T, bool is_integer> struct reverse_impl;
template <typename T>
struct reverse_impl<T, true>
{
static T reverse(T input)
{
T output;
for (output = 0; input; input/=10)
output = (output * 10) + input % 10;
return output;
}
};
template <typename T>
struct reverse_impl<T, false>
{
static T reverse(T input)
{
if (std::abs(input) <= std::numeric_limits<T>::epsilon())
return T(0);
// scale input
int log10 = (int) (std::log(input)/std::log(T(10)));
input *= std::pow(10, MAX_DECIMAL_FRACTION);
input = std::floor(input);
input /= std::pow(10, log10+MAX_DECIMAL_FRACTION);
DEBUGTRACE("debug: scaled " << input << " digits: ");
int iteration = std::max(log10+MAX_DECIMAL_FRACTION, MAX_DECIMAL_FRACTION);
if (std::floor(input) < 1)
{
input *= 10;
iteration--;
}
T output;
for (output = T(0);
iteration-- && std::floor(input) >= 1;
input-=std::floor(input), input*=T(10))
{
output = (output / T(10)) + std::floor(input);
DEBUGTRACE(std::floor(input));
}
DEBUGTRACE(std::endl);
return output * std::pow(10, log10);
}
};
template <typename T>
T reverse(T input)
{
return reverse_impl<T, std::numeric_limits<T>::is_integer>::reverse(input);
}
int main()
{
std::cout << reverse(-123l) << std::endl;
std::cout << reverse(123ul) << std::endl;
std::cout << reverse(123456.0) << std::endl;
std::cout << reverse(0.027f) << std::endl;
return 0;
}
***//here is the simple solution to find reverse of a function***
#include<iostream.h>
#include<conio.h>
void main()
{
int n,a,c,d,b;
clrscr();
cout<<"enter five integers";
cin>>n;
a=n/10000;
n=n%10000;
b=n/1000;
n=n%1000;
c=n/100;
n=n%100;
d=n/10;
n=n%10;
cout<<"number in reverse order is"<<n<<d<<c<<b<<a;
getch();
}