x(,/{@[x;y;]'(!10)^x*|/p[;y]=p,:,3/:-3!p:!9 9}')/&~*x
Written in K language.
Has a regex feel to it, for me.