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

You need to examine each position - whether it is the same as $a_1$, or not. Although this is slow in general, it's OK with a few cases, like here for n=6. So here we go, I denote different choices with different letters:
1. $a_1 = A$ - 9 choices. | A | _ | _ | _ | _ | _ |
2. $a_2 = B$ - 9 choices. | A | B | _ | _ | _ | _ |
3.A. $a_3 = a_1 = A$ - 1 choice. Then $a_4 = D$ - 9 choices. | A | B | A | D | _ | _ |


*

*3.A.4.A. $a_5 = a_1 = A$ - 1 choice, then $a_6$ - 9 choices - in total $\fbox{$9^4$}$ | A | B | A | D | A | F |

*3.A.4.B $a_5 = E \ne a_1$ - 8 choices, then $a_6$ has 8 choices
- in total $\fbox{$9^3.8^2$}$ | A | B | A | D | E | F |

3.B. $a_3 = C \ne a_1$ - 8 choices | A | B | C | _ | _ | _ |


*

*3.B.4.A. $a_4 = A$ - 1 choice => $a_5 = E\ne A$ - 9 choices => $a_6 = F$ - 8 choices
- in total $\fbox{$9^3.8^2$}$ | A | B | C | A | E | F |



*

*3.B.4.B. $a_4 = D\ne a_1$ - 8 choices | A | B | C | D | _ | _ |


*

*3.B.4.B.5.A. $a_5 = a_1 = A$ - 1 choice => $a_6 = F$ - 9 choices
- in total $\fbox{$9^3.8^2$}$ | A | B | C | D | A | F |

*3.B.4.B.5.B $a_5 = E\ne a_1$ - 8 choices => $a_6 = F$ - 8 choices
- in total $\fbox{$9^2.8^4$}$ | A | B | C | D | E | F |

And now, just sum up the results: $3.9^3.8^2+9^4+9^2.8^4 = $478305, exactly what we needed.
Tad's response is also great and timely!
