S1Q3 · Four Digit Shuffle¶
⚡ Quick Reference
Function: shuffle_digits(num: int) -> int
Core idea: extract the 4 digits, rearrange in order [d1, d3, d0, d2] (0-indexed), reassemble.
Shuffle rule (0-indexed): positions 0,1,2,3 → output order 1,3,0,2
| Output pos | Taken from input pos |
|---|---|
| 1st | 2nd (index 1) |
| 2nd | 4th (index 3) |
| 3rd | 1st (index 0) |
| 4th | 3rd (index 2) |
Problem Statement¶
Problem
Write a function shuffle_digits(num) that takes a 4-digit integer and rearranges its digits in the order: 2nd, 4th, 1st, 3rd (1-indexed).
Examples:
1234
2413
2413
4321
4321
3142
Understanding the problem¶
The shuffle rule in 1-indexed terms: 2nd → 1st, 4th → 2nd, 1st → 3rd, 3rd → 4th
Converting to 0-indexed string positions:
For 1234:
It's a permutation cycle
The examples show that applying the shuffle 4 times returns to the original: 1234 → 2413 → 4321 → 3142 → 1234. This is a 4-cycle permutation -a good way to verify your implementation is correct.
Tracing all examples¶
| Input | d[0] | d[1] | d[2] | d[3] | Output = d[1]d[3]d[0]d[2] |
|---|---|---|---|---|---|
| 1234 | 1 | 2 | 3 | 4 | 2413 |
| 2413 | 2 | 4 | 1 | 3 | 4321 |
| 4321 | 4 | 3 | 2 | 1 | 3142 |
| 3142 | 3 | 1 | 4 | 2 | 1234 |
Solution approaches¶
Convert to string, pick digits by index, reassemble.
def shuffle_digits(num: int) -> int:
s = str(num)
d0, d1, d2, d3 = s[0], s[1], s[2], s[3]
return int(d1 + d3 + d0 + d2)
Name each digit explicitly -makes the shuffle rule immediately readable.
def shuffle_digits(num: int) -> int:
d0 = num // 1000 # thousands
d1 = (num // 100) % 10 # hundreds
d2 = (num // 10) % 10 # tens
d3 = num % 10 # units
return d1 * 1000 + d3 * 100 + d0 * 10 + d2
Extract digits with integer division and modulo, then reassemble using place values. No string conversion at all.
Key takeaways¶
str → rearrange → int
The standard pattern for digit rearrangement: convert to string for easy indexing, reorder the characters, convert back to int. Works for any digit permutation.
Encode the permutation as a list
order = [1, 3, 0, 2] makes the shuffle rule data rather than hardcoded logic. Change the list to change the shuffle -no rewriting the function body.
Verify with the cycle property
Applying the same shuffle 4 times returns the original number. Run shuffle_digits(shuffle_digits(shuffle_digits(shuffle_digits(1234)))) -if you get 1234, the implementation is correct.