Created
August 15, 2024 05:39
-
-
Save akpoff/14749fd4ee1d175090353cecfbc5322b to your computer and use it in GitHub Desktop.
Duff's Device in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def duffs_device(frm, count): | |
""" | |
Implement Duff's Device for copying frm in a loop-unrolled fashion. | |
:param frm: List or array-like object to copy frm | |
:param count: Number of elements to copy | |
""" | |
# Ensure we have at least one element to copy | |
if count <= 0: | |
return | |
# Number of integral groups of 8 to copy | |
n = (count + 7) // 8 | |
remainder = count % 8 | |
while n > 0: | |
# First pass through will be remainder elements | |
# Pop 0th element to mimic reading from source | |
# Uses print() as the destination | |
if remainder == 0: | |
print(frm.pop(0), "", end='') | |
if remainder >= 1 or remainder == 0: | |
print(frm.pop(0), "", end='') | |
if remainder >= 2 or remainder == 0: | |
print(frm.pop(0), "", end='') | |
if remainder >= 3 or remainder == 0: | |
print(frm.pop(0), "", end='') | |
if remainder >= 4 or remainder == 0: | |
print(frm.pop(0), "", end='') | |
if remainder >= 5 or remainder == 0: | |
print(frm.pop(0), "", end='') | |
if remainder >= 6 or remainder == 0: | |
print(frm.pop(0), "", end='') | |
if remainder == 7 or remainder == 0: | |
print(frm.pop(0), "", end='') | |
print() | |
# remainder handled, reset to 0 | |
remainder = 0 | |
n -= 1 | |
# Example usage: | |
frm = list(range(1000)) # A list of numbers frm 0 to 999 | |
duffs_device(frm, 300) # Copy out n elements to sink |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I wrote this as an example in response to a post I made on X as a contrast to code from Grok. Yes, it's a nutty idea. See the original post.
https://x.com/akpoff/status/1823958893292130430