StackOverflow after 27 runs - stack-overflow

When running my Sudoku Generator, after 27 times getting stack overflow.
void start(int todel){
int number;
for (int x=0; x<9; x++) {
for (int y=0; y<9; y++) {
number = GenN(x, y);
osudoku[x][y]=number;
}
}
replace(todel);
output();
}
int GenZ(int x, int y){
int number;
bool duplication = true;
Randomize();
number = Random(9)+1;
duplication = check(number,x,y);
if (duplication==true){
return GenZ(x,y);
}
else if (duplication==false) {
return number;
}
}
I think its something with this code.
It generates things like:
758 431 629
913 267 485
642 985 317
Stack Overflow
So I get 1/3 Sudoku.

You need to add backtracking to your solution.
Consider this scenario: (which may occur at some point in your algorithm)
1 2 3 | 4 5 6 | 7 8 9
4 5 6 | 1 2 3 | ? _ _
...
Your program will just keep trying to find a value that fits at the ?, but no such value exists.
Instead, your program needs to see that no values fits, and try a different value for 3, which also won't work, then 2, then 1 in which case it should eventually put 7, 8 and 9 in the second block like:
1 2 3 | 4 5 6 | 7 8 9
4 5 6 | 7 8 9 | ? _ _
...
in which case it can continue successfully.
And this:
zahl = Random(9)+1;
won't really work as you may keep on getting values that don't fit (as in the above example). You won't know when to backtrack. It's better to loop through all 9 values. After you've looped through all 9 values, you'll know that no value fits and you'll know you must backtrack.

if duplication==true in GenZ it will call it again with the same x,y , which will again produce duplication==true? especially since I cant see you modifying "number" , so it might be at it's initialized value like 0.

if (duplication==true){
return GenZ(x,y);
}
I am not sure if that is a viable way to create a sudoku, brute-forcing might take a while no matter how you implement it, but you can probably get rid off the stackoverflow error by not using recursion and having a loop.
while (duplication){

Related

How can I improve my Countdown Numbers Solver algorithm to find more solutions?

As my school Project, I need to build a solver for Countdown Numbers & Letters rounds. I wanted to develop a structure which I can use to build both solvers, and I first developed a Numbers solver. However, before using this solution for Letters, I need to improve my current algorithm. I think I'm wrong somewhere, because I don't get the same results with other tools I am using to compare my program. Here is program for my solver;
/// numbers_game_solver.dart
import 'dart:collection';
import 'package:trotter/trotter.dart';
/* Import statements was package-based, I turned them into relative paths for question. */
import 'number_generator.dart';
import 'operation.dart';
import 'solution.dart';
import 'solutions.dart';
/* Will try to combine numbers with operations, as shown below;
* List<List<Operation>> operations = <Operations>[a, ,b, ,c, ,d, ,e, ,f
* + - + * / ]
* Then if last operations result is equal to target, will result it.
* If not will show closest result.
*/
const List<String> kOperators = const <String>[kOpAdd, kOpDiv, kOpMul, kOpSub];
class NumbersGameSolver {
NumbersGameSolver()
: this.solutions = Solutions(_expectedResult);
/* TODO: Do tests with smaller numbers and targets. */
final List<int> _numbers = const <int>[1, 2, 3, 4]; // NumberGenerator.numbers;
static final int _expectedResult = 15; //NumberGenerator.expectedResult;
final Solutions solutions;
void solve() {
/* All permutations of operators with replacement, which will be inserted between numbers. */
final Set<List<String>> amalgamsOperators = Amalgams<String>(_numbers.length - 1, kOperators)().toSet();
/* There may duplicates occur in numbers list, because of this, numbers will be mapped
using permutations of indices. */
final List<int> indices = List<int>.generate(_numbers.length, (int index) => index);
final Iterable<List<int>> permutationsIndices = Permutations<int>(indices.length, indices)();
final Set<List<int>>
permutationsNumbers = permutationsIndices.map(
(List<int> listPerm) => listPerm.map(
(int index) => _numbers[index]
).toList()
).toSet();
for (final List<int> numbers in permutationsNumbers) {
for (final List<String> operators in amalgamsOperators) {
Queue<int> stackNums = Queue<int>.from(numbers);
Queue<String> stackOprts = Queue<String>.from(operators);
Solution tempSolution = Solution(_expectedResult);
do {
int left = stackNums.removeFirst(), right = stackNums.removeFirst();
Operation tempOperation = Operation(stackOprts.removeFirst(), left, right);
/* Record solutions current state. */
SolutionState solutionState = tempSolution.addOperation(tempOperation);
if (solutionState == SolutionState.currentlyValid) {
/* If valid, add result to the current numbers stack. */
stackNums.addFirst(tempOperation.result);
} else if (solutionState == SolutionState.lastOperationRedundant) {
/* If operation is redundant, dispose it and continue. */
continue;
} else if (solutionState == SolutionState.lastResultInvalid) {
/* If results is invalid at any stage, dispose whole solution. */
break;
}
if (solutions.addSolution(tempSolution) == true) break;
} while (stackNums.length > 1);
}
}
/* Will show only accurate solutions.
* If there is no accurate solutions, will show solutions which results
* are closest to the expected result.
*/
solutions.showSolutions();
}
}
There are 5 classes, to shorten the question I added them in this Gist.
My algorithm is as follows;
Rules for this Project are; program must randomly generate 5 single digit number and 1 two digit number where twoDigitNumber % 10 == 0 and a three digit number as target.
I get permutations of 4 operators and numbers that will be used in operations (Using trotter package.)
For each permutation of numbers, I apply each permutation of operators; using Operation class and add them into a Solution instance for each permutation.
I pass some redundant operations in each iteration, and if there is an invalid result at any stage, I dispose that solution and continue. (I'm taking this DataGenetics blog about this topic as a reference.)
To test my algorithm I used numbers 1, 2, 3, 4 and set target as 15. The results from dcode.fr Solver are as is;
15 (2 op.)
4 + 1 = 5
5 x 3 = 15
15 (3 op.)
4 + 3 = 7
7 x 2 = 14
14 + 1 = 15
15 (3 op.)
4 x 3 = 12
12 + 2 = 14
14 + 1 = 15
15 (3 op.)
4 x 3 = 12
2 + 1 = 3
12 + 3 = 15
15 (3 op.)
3 + 2 = 5
4 - 1 = 3
5 x 3 = 15
15 (3 op.)
4 x 3 = 12
12 + 1 = 13
13 + 2 = 15
15 (3 op.)
4 - 1 = 3
3 + 2 = 5
5 x 3 = 15
15 (3 op.)
4 + 2 = 6
6 - 1 = 5
5 x 3 = 15
15 (3 op.)
2 + 1 = 3
4 x 3 = 12
12 + 3 = 15
15 (3 op.)
2 - 1 = 1
4 + 1 = 5
5 x 3 = 15
(A total of 10 solutions.)
and the solutions my program found are as is;
> SOLUTION 1 ~
4 - 1 = 3
3 + 2 = 5
5 x 3 = 15
> SOLUTION 2 ~
4 + 1 = 5
5 x 3 = 15
(A total of 2 solutions.)
Can you tell me what am I thinking wrongly; Why can't I find all solutions? What are alternative approaches I can take to solve this problem? Is there anything I'm missing?
TY for taking time.

How to sort a vector of structure belonging to same category/set in c++

While solving a competitive coding problem I got stuck with the the following sorting scenario.
I have a vector of following structure
struct Data{
int p;
int val;
int ll;
};
Defined as :
vector<Data> a(N);
Now p field in the structure tells the set number to which val belong.
e.g if values are 1 2 3 4 5 6 7 8 9
(1,4,7) belong to group/set 3 i.e p is 3 , (2,5,8) belong to group/set 4 i.e p is 4 and (3,6,9) belong to group/set 5 i.e p is 5
i have p and val field in structure as
p as 3 4 5 3 4 5 3 4 5
val as 1 2 3 4 5 6 7 8 9
Now the problem is I have to sort the vector set wise in descending order
i.e 7 8 9 4 5 6 1 2 3
here 1 4 and 7 belong to set 3 so they are sorted in their respective places.
I tried with the selection sort as below which worked fine but it gave Time limit exceeded because of O(N^2) complexity.
for(int i=0;i<N;i++)
{
int mi=i;
Data max=a[i];
for(int j=i+1;j<N;j++)
{
if((a[i].p==a[j].p)&&(a[j].val>max.val))
{
max=a[j];
mi=j;
}
}
a[mi]=a[i];
a[i]=max;
}
Please help me find the best (time complexity) way to sort this scenario (if possible using STL sort).
Thanks in advance.
Modifying http://www.cplusplus.com/reference/algorithm/sort/, the key bit is:
#include <algorithm>
...
bool mycomparison (Data i, Data j) {
if (i.p != j.p)
return j.p < i.p;
else
return j.val < i.val;
}
...
// Sort vector a
a.std::sort( a.begin(), a.end(), mycomparison );
...
Note that reversing i and j in the return lines causes things to be in descending order.

How does recursion of Quick sort work?

The functions below are an implementation of Quick sort. Here we take the last element as a pivot.
I understood the partition function(where the pivot comes to its sorted position) but I can't understand the recursive function qs. The function qs calls itself recursively to solve the left side by qs(a,start,pi-1) and the right of the partition by qs(a,pi+1,end).
Does it the solve the left and then the (left of the left) then (the left of(the left of the left), etc, and then left, left...right, etc. Or does it alternate by solving the left side and then right side.
PS: I want to know whats happening inside the computer, the mechanism of this recursion of quick sort. The program is working but I want to know how it works.
int partition(int *a, int start, int end)
{
int pivot=a[end];
int pi=start;
for(int i=start; i<end; i++)
{
if(a[i]<=pivot)
{
swap(a[i],a[pi]);
pi++;
}
}
swap(a[pi], a[end]);
return pi;
}
void qs(int*a, int start, int end)
{
if(start<end)
{
int pi=partition(a,start,end);
qs(a,start,pi-1);
qs(a,pi+1,end);
}
}
Example of the order of operations for Lomuto partition scheme, where pivot = array[high].
quicksort(array, low, pivot-1), quicksort(array, pivot+1, high).
A vertical bar used to show left sub-array, pivot, right sub-array.
11 13 14 12 10 8 9 5 6 4 2 0 1 3 7
5 6 4 2 0 1 3 11 13 14 12 10 8 9 7
5 6 4 2 0 1 3| 7|13 14 12 10 8 9 11
2 0 1 5 6 4 3
2 0 1| 3| 6 4 5
0 2 1
0| 1| 2
4 6 5
4| 5| 6
10 8 9 13 14 12 11
10 8 9|11|14 12 13
8 10 9
8| 9|10
12 14 13
12|13|14
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
The best way for understanding the order in which things are happening that I can suggest you, is by printing some debugging info in your qs method. To achieve that, I would add an additional argument by ref, in which I would count the number of times the qs function is called, and print that info next to the bounds of the partition being solved. e.g.
void qs(int*a, int start, int end, int &stepCount)
{
if(start<end)
{
int currentStep = stepCount++;
cout << "Solving step " << currentStep << " partition from " << start << " to " << end << endl;
int pi=partition(a,start,end);
qs(a,start,pi-1,stepCount);
qs(a,pi+1,end,stepCount);
cout << "Finished solving step " << currentStep << endl;
}
}
Don't understand your PS question. It's very broad. You mean specifically in the partitioning? In how recursion is handled? How the bits move around in memory?

Generating number within range with equal probability with dice

I've been thinking about this but can't seem to figure it out. I need to pick a random integer between 1 to 50 (inclusive) in such a way that each of the integer in it would be equally likely. I will have to do this using a 8 sided dice and a 15 sided dice.
I've read somewhat similar questions related to random number generators with dices but I am still confused. I think it is somewhere along the line of partitioning the numbers into sets. Then, I would roll a die, and then, depending on the outcome, decide which die to roll again.
Can someone help me with this?
As a simple - not necessarily "optimal" solution, roll the 8 sided die, then the 15 sided:
8 sided 15 sided 1..50 result
1 or 2 1..15 1..15
3 or 4 1..15 16..30 (add 15 to 15-sided roll)
5 or 6 1..15 31..45 (add 30 to 15-sided roll)
7 or 8 1..5 46..50 (add 45 to 15-sided roll)
7 or 8 6..15 start again / reroll both dice
lets say you have two functions: d8(), which returns a number from 0 to 7, and d15(), which returns a number from 0 to 14. You want to write a d50() that returns a number from 0 to 49.
Of all the simple ways, this one is probably the most efficient in terms of how many dice you have to roll, and something like this will work for all combinations of dice you have and dice you want:
int d50()
{
int result;
do
{
result = d8()*8+d8(); //random from 0 to 63
} while(result >=50);
return result;
}
If you want really constant time, you can do this:
int d50()
{
int result = d15();
int result = result*15+d15(); //0 to 225
int result = result*8+d8(); //0 to 1799
return result/36; //integer division rounds down
}
This way combines dice until the number of possibilities (1800) is evenly divisible by 50, so the same number of possibilities correspond to each result. This works OK in this case, but doesn't work if the prime factors of the dice you have (2, 3, and 5 in this case), don't cover the factors of the dice you want (2, 5)
I think that you can consider each dice result as a subdivision of a bigger interval. So throwing one 8 sided dice you choose one out the 8 major interval that divide your range of value. Throwing a 15 sided dice means selecting one out the 15 sub-interval and so on.
Considering that 15 = 3*5, 8 = 2*2*2 and 50 = 2*5*5 you can choose 36 = 3*3*2*2 as an handy multiple of 50 so that:
15*15*8 = 50*36 = 1800
You can even think of expressing the numbers from 0 to 1799 in base 15 and choose ramdomly the three digits:
choice = [0-7]*15^2 + [0-14]*15^1 + [0-14]*15^0
So my proposal, with a test of the distribution, is (in the c++ language):
#include <iostream>
#include <random>
#include <map>
int main() {
std::map<int, int> hist;
int result;
std::random_device rd;
std::mt19937 gen(rd()); // initialiaze the random generator
std::uniform_int_distribution<> d8(0, 7); // istantiate the dices
std::uniform_int_distribution<> d15(0, 14);
for (int i = 0; i < 20000; ++i) { // make a lot of throws...
result = d8(gen) * 225;
result += d15(gen) * 15; // add to result
result += d15(gen);
++hist[ result / 36 + 1]; // count each result
}
for (auto p : hist) { // show the occurences of each result
std::cout << p.first << " : " << p.second << '\n';
}
return 0;
}
The output should be something like this:
1 : 387
2 : 360
3 : 377
4 : 393
5 : 402
...
48 : 379
49 : 378
50 : 420

Accessing pixel pointer

Can you explain to me how the accessing pixel has been done in this double loop ? how do they change rows and cols and pixel's value?
for(int i=0;i<cv_ptr->image.rows;i++)
{
float* ptr_img_A = cv_ptr->image.ptr<float>(i);
for(int j=0;j<cv_ptr->image.cols;j++)
{
*ptr_img_B=255*(*ptr_img_A)/3.5;
ptr_img_A++;
}
}
Thank you.
First of, is this the complete code or is ptr_img_B actually ptr_img_A in the first row of the inner loop?
Secondly I would recommend naming your variables by the content it has.
for(int i=0;i<cv_ptr->image.rows;i++)
{
float* row_ptr = cv_ptr->image.ptr<float>(i);
for(int j=0;j<cv_ptr->image.cols;j++)
{
*row_ptr=255*(*row_ptr)/3.5;
row_ptr++;
}
}
So basically it scales every pixel in the image with the factor of 255/3.5
Regarding the access of the pixel, it is stored in memory like this
COL
ROW 1 2 3 4
1 0 1 2 3
2 4 5 6 7
3 8 9 10 11
4 12 13 14 15
Then in order to access, for example pixel on row 3, col 2
float* row_ptr = cv_ptr->image.ptr<float>(row-1);
float value = row_ptr[col-1];
Finally I hope you will enjoy your time with openCV, it is a really nice framework :)

Resources