Basically, as the title says, I try to create a code in C++ that can guess a 4 digit number based on input. Everytime it gets the right digit in the right position, the input should be 1, 2, 3 respectively 4 for the correct guessing of the number. Let’s say the number is 7130 and the number provided by the code is 7300, the input to help it guess should be the number 2, because 7 and 0 are in the right positions. I’ve thought about using a lot of if’s for inputs like 2 and 3, then rearranging/changing numbers until it could figure out which numbers are in the correct positions. Should it be recursive? I thought about using Divide Et Impera too, but not sure how to implement it.
I need help at least with the algorithm, how should it be done, but if the solution is recursive I will need some code too, thank you in advance!
I tried using characteristic vectors, thought about using a function for each input like 1, 2 or 3, but it seems to get recursive and I’m lost.
This is the code I got stuck at, nowhere near completion, but I just don’t know how to do it. The function “change2” should return if the 2 numbers provided as parameters are in the right position or not.
#include <iostream>
using namespace std;
int nr[4] = {-1, -1, -1, -1}, x[4], aux[4];
unsigned numbers[10] = {7, 3, 5, 9, 0, 1, 4, 2, 8, 6};
int freq[5][11] = {-1};
int change2(int i, int j)
{
int k = 1, cnt = 0;
for(int i = 0; i <= 9; i++)
if(freq[i][numbers[i]] != 1)
{
freq[i][numbers[i]] = 1;
aux[i] = numbers[i];
break;
}
for(int i = 0; i <= 9; i++)
if(freq[j][numbers[i]] != 1)
{
freq[j][numbers[i]] = 1;
aux[j] = numbers[i];
break;
}
while(k <= 4)
if(x[k++] == aux[k])
cnt++;
if(cnt == 2)
return 2;
}
int main()
{
bool ok = 1;
int cnt, k, d;
cin >> d;
k = 4;
while(d)
{
x[k--] = d % 10;
d /= 10;
}
do
{
cnt = 0;
if(nr[1] == -1)
for(int i = 0; i <= 9; i++)
if(freq[1][numbers[i]] != 1)
{
freq[1][numbers[i]] = 1;
aux[1] = numbers[i];
break;
}
cout << aux[1];
if(nr[2] == -1)
for(int i = 0; i <= 9; i++)
if(freq[2][numbers[i]] != 1)
{
freq[2][numbers[i]] = 1;
aux[2] = numbers[i];
break;
}
cout << aux[2];
if(nr[3] == -1)
for(int i = 0; i <= 9; i++)
if(freq[3][numbers[i]] != 1)
{
freq[3][numbers[i]] = 1;
aux[3] = numbers[i];
break;
}
cout << aux[3];
if(nr[4] == -1)
for(int i = 0; i <= 9; i++)
if(freq[4][numbers[i]] != 1)
{
freq[4][numbers[i]] = 1;
aux[4] = numbers[i];
break;
}
cout << aux[4];
k = 1;
while(k <= 4)
if(x[k++] == aux[k])
cnt++;
if(cnt == 2)
{
if(change2(1, 2) == 2)
{
nr[3] = aux[3];
nr[4] = aux[4];
}
else if(change2(1, 3) == 2)
{
nr[2] = aux[2];
nr[4] = aux[4];
}
else if(change2(1, 4) == 2)
{
nr[2] = aux[2];
nr[3] = aux[3];
}
else if(change2(2, 3) == 2)
{
nr[1] = aux[1];
nr[4] = aux[4];
}
else if(change2(2, 4) == 2)
{
nr[1] = aux[1];
nr[3] = aux[3];
}
else if(change2(3, 4) == 2)
{
nr[1] = aux[1];
nr[2] = aux[2];
}
cout << "nr1=" << nr[1] << "n" << "nr2=" << nr[2] << "n" << "nr3=" << nr[3] << "n" << "nr4=" << nr[4] << "n";
ok = 0;
break;}
}
while(ok);
return 0;
}