sed Character match and replace

Hello All

I am struck in the issue which I want to share with all of you.
What I am trying to do is For every line in a file I have to replace a particular character from the given character in a file
For Example

Suppose the data is

1111x2222
1111x2222
2222y3333
1111x2222

I will pass three argument to shell script
./script 5 x y
It mean for Evey 5th character in line if it found x it should replace by y and if it found y it should replace with x

So output should be

1111y2222
1111y2222
2222x3333
1111y2222

---------- Post updated at 03:46 AM ---------- Previous update was at 03:45 AM ----------

So far what I wrote in shell script is

pos=$1
ppos=`expr $pos - 1`
pat1=$2
pat2=$3

sed "/^.\{$ppos\}$pat1/s/./$pat2/$pos" mdat

But it is doing at one way

Have you attempted anything to solve this ?

pos=$1
ch=$2
sub=$3
awk -v p=$pos -v c=$ch -v s=$sub '{if(substr($0,p,1)==c) {print substr($0,1,p-1) s substr($0,p+2)}}' mdat

No its not working
./mscr 5 x y
When I tried with data

1111x2222
1111x2222
2222y3333
1111x2222
2 22y3333
1111x2222
22 2y3333
2222y3333
 111x2222
2222y3333
1111x2222
2222y3333

it does not give expected result

Sorry, I had omitted the else part. Corrected it as below

pos=$1
ch=$2
sub=$3
awk -v p=$pos -v c=$ch -v s=$sub '{if(substr($0,p,1)==c) {print substr($0,1,p-1) s substr($0,p+2)} else {print substr($0,1,p-1) c substr($0,p+2)}}' mdat