I am trying my hands on Ambiguous Permutation problem listed under Easy problems in Practice Section. I have employed logic that if I make a number out of provided combination and again create a number based on its inverse permutation, if both numbers are same, it would be an ambiguous permutation. Consider the first test input
1 4 3 2
According to logic, I take an integer initial that would take hold number made out of given permutation and final would hold up number made out of its inverse permutation.
So, here is calculation of initial, initially initial and final are 0.
powr() is a function here, It gives out 10^n. And till holds number of numbers in test case, so,
till=4 and limit holds copy of till.
initial = initial10 + numberpowr(till-1);
till–;
so, For First,
initial = 0 + 1*10^(4-1);
initial = 1000;
initial = 1000 + 4*10^(3-1);
initial = 1000 + 400;
initial = 1400;
initial = 1400 + 3*10(2-1)
initial = 1400 + 30
initial = 1430
initial = 1430 + 2*10(1-1)
initial = 1432;
And for final computation
final= final + currIndex*10^(limit-num);
final = 0 + 1*10^(4-1)
final = 0 + 1000
final = 1000
final = 1000 + 2*10^(4-4)
final = 1000 + 2
final = 1002
final = 1002 + 3*10^(4-3)
final = 1002 + 30
final = 1032
final = 1032 + 4*10^(4-2)
final = 1032 + 400
final = 1432
Both numbers are same. But I am getting wrong answer for my solution.
I don’t wish to copy other’s solution.
I want to know error of my way.
By the way, logic works for numbers >10.
I have checked.
Here is code.
# include <stdio.h>
# define BUFFER 32678
# define true 1
# define false 0
static char input[BUFFER];
static char store[100001];
int powr(int);
int main()
{
int ret, byteRead=0, cont, till=0, initial=0, final=0, firstIndex=0, currIndex=0, passedFirst=0, limit, num=0;
cont = 4;
ret = fread(input, sizeof(char), BUFFER, stdin);
while(cont)
{
while(byteRead < ret && input[byteRead] >= '0')
{
till = till*10 + (input[byteRead]-'0');
limit= till;
byteRead++;
}
if(till==0)
{
cont=false;
continue;
}
while(byteRead < ret && input[byteRead] <'0')
{
byteRead++;
}
while(byteRead < ret && input[byteRead] !='\n')
{
if(byteRead==BUFFER)
{
ret = fread(input, sizeof(char), BUFFER, stdin);
byteRead=-1;
}
else if(input[byteRead]!=' ' && input[byteRead]!='\n')
{
num = num*10 + (input[byteRead]-'0');
}
else if(input[byteRead]==' ')
{
initial = initial + (num * powr(till-1));
if(passedFirst == false)
{
currIndex=1;
passedFirst = true;
}
final = final + currIndex*powr(limit-num);
currIndex++;
num =0;
till--;
}
byteRead++;
}
passedFirst=false;
initial = initial + (num * powr(till-1));
final = final + currIndex*powr(limit-num);
if(final == initial)
{
printf("ambiguous\n");
}
else
printf("not ambiguous\n");
till= final = initial =0;
byteRead++;
num=0;
currIndex=1;
}
return 0;
}
int powr(int n)
int mul=1,i;
for(i=1;i<=n;i++)
{
mul = mul*10;
}
return mul;
}