I'm trying to solve the below problem for a number:
Enter a number and if it has all unique digits print unique number else non-unique number.
Eg:
Input=123; Output=unique number
Input=112; Output=Non-unique number
The thing i tried is splitting the number into digits by using % operator and storing it in a array and i'm facing problems while using 2 for loops to traverse the array elements and compared with each other.
for ( i=0; i<=array_length; i++){
for( j=i+1; j<=array_length; j++){
if ( a == a[j] ){
printf("unique");
}
else{
printf("Non-unique");
}
I know that i'm wrong, can someone help with any idea to solve.
for single input
echo "9284762" | awk '{t=$0; for(i=1; i<=length; i++) {if(a[t%10]++ > 0) {print $0 " has non-unique"; next}; t=sprintf("%d", t/10)}; print $0 " has uniques"}'
or if you want to pass multiple inputs through file
awk '{t=$0; for(i=1; i<=length; i++) {if(a[t%10]++ > 0) {print $0 " has non-unique"; next}; t=sprintf("%d", t/10)}; print $0 " has uniques"}' file
If the digits are on the same line, you can use grep
if echo 123 | grep '\(.\).*\1' >/dev/null; then echo "Non-unique"; else echo "unique"; fi
if echo 112 | grep '\(.\).*\1' >/dev/null; then echo "Non-unique"; else echo "unique"; fi
\(.\)
matches one character and saves a reference #1, .*
means zero or more characters, \1
means that #1 re-occurs.
1 Like