The Weekly Challenge 070

Character Swapping and Gray Code Sequence

Solutions on GitHub

Task 1: Character Swapping

Given a string $S of size $N, swap count $C, and offset $O, perform character swapping for $i = 1 .. $C at positions $i % $N and ($i + $O) % $N.

Example Output

Input: $S = 'perlandraku' $C = 3 $O = 4 Output: pndraerlaku

Logic

Iterate from 1 to $C, compute the swap indices modulo $N, and swap the characters at those positions.

Perl Solution

ch-1.pl

my $S = 'perlandraku'; my $C = 3; my $O = 4; my $N = length($S); for my $i ( 1 .. $C ) { my $x = $i % $N; my $y = ( $i + $O ) % $N; substr( $S, $x, 1, substr( $S, $y, 1, substr( $S, $x, 1 ) ) ); } print "$S\n";

Python Solution

ch-1.py

S = "perlandraku" C = 3 O = 4 N = len(S) S = list(S) for i in range(1, C + 1): x = i % N y = (i + O) % N S[x], S[y] = S[y], S[x] S = "".join(S) print(S)

Task 2: Gray Code Sequence

Generate an $N-bit Gray code sequence, represented as decimal integers.

Example Output

Input: $N = 4 Output: 0, 1, 3, 2, 6, 7, 5, 4, 12, 13, 15, 14, 10, 11, 9, 8

Logic

Construct the sequence iteratively: take the previous sequence, prefix original elements with '0', prefix the reversed sequence with '1', and concatenate. Finally, convert binary strings to decimal.

Perl Solution

ch-2.pl

my $N = 4; my @gray_code = ( 0, 1 ); for my $i ( 2 .. $N ) { my @rev_gray_code = reverse @gray_code; @gray_code = map { "0$_" } @gray_code; @rev_gray_code = map { "1$_" } @rev_gray_code; push @gray_code, @rev_gray_code; } @gray_code = map { oct("0b$_") } @gray_code; print join( ", ", @gray_code ), "\n";

Python Solution

ch-2.py

N = 4 gray_code = ["0", "1"] for i in range(2, N + 1): rev_gray_code = gray_code[::-1] gray_code = ["0" + x for x in gray_code] rev_gray_code = ["1" + x for x in rev_gray_code] gray_code += rev_gray_code gray_code = [int(x, 2) for x in gray_code] print(gray_code)