How many $6$ digit numbers there are, where first and last digits and also consecutive digits are not equal? We have a 6 digit number
$a_1a_2a_3a_4a_5a_6$ and $a_1 \neq 0$
also $a_1 \neq a_2, a_2 \neq a_3, a_3 \neq a_4, a_4 \neq a_5, a_5 \neq a_6, a_6 \neq a_1$
All of numbers where $a_1 \neq a_2, a_2 \neq a_3, a_3 \neq a_4, a_4 \neq a_5, a_5 \neq a_6$ are $9^6$
I'm having troubles with the last case.I know that this is generalization of $a_1a_2a_3$ for which there are $8*9^2$ numbers but cannot figure out how they are related
and this is the source file which counts all those digits.
bool foo(int num)
{
    char str[15] = {};
    int i=0;
    while(num)
    {
        str[i]=num%10;
        num/=10;
        i++;
    }
    str[i]=str[0];
     for(int j=0;j<i;j++)
            if(str[j]==str[j+1])
                return false;
    return true;
}

int main()
{
    int sum=0;
    for(int i=100000;i<=999999;i++)
        if(foo(i))
            sum++;
    cout<<sum;
    return 0;
}

Please note that this program produces answer: 478305, which is correct
Also note that the answer 8*9^5 misses some cases

Here's another approach.  We will do cases based on the digits in positions $1$, $3$, and $5$.
Case 1: 
$a$, ___ , $a$, ____, $a$, ____.  
There are $9$ ways to select the digit $a$, and $9$ ways to fill each blank. So  $9^4$ numbers of interest in this case.
Case 2.1, 2.2, 2.3:  
$a$, ___ , $a$, ____, $b$, ____ 
and $a$, ___ , $b$, ____, $b$, ____ 
and $b$, ___ , $a$, ____, $a$, ____
For each of three subcases, there are $9\cdot 9$ ways to choose $a$ and $b$, and $9\cdot 8\cdot 8$ ways to fill the blanks.  So there are a total of $3\cdot 9^3\cdot 8^2$ numbers of interest in these three subcases combined.
Case 3:  
$a$, ___ , $b$, ____, $c$, ____.  
There are $9\cdot 9\cdot 8$ ways to choose $a, b,c$, and $8$ ways to fill each blank.  So there are a total of $9^2\cdot 8^4$ numbers of interest in this case.
Grand total: $9^4+3\cdot 9^3\cdot 8^2+9^2\cdot8^4=478305$ numbers of interest.
