Skip to content

Instantly share code, notes, and snippets.

@kierendavies
Created October 23, 2020 15:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kierendavies/6f6e1b792f664a04b66ce4c193edc907 to your computer and use it in GitHub Desktop.
Save kierendavies/6f6e1b792f664a04b66ce4c193edc907 to your computer and use it in GitHub Desktop.
#!/usr/bin/env perl
use strict;
use warnings;
sub find_pair {
my ($elems, $target) = @_;
my @sums = map { eval } glob join "+", map "{$_}", map join(",", @$_), $elems, $elems;
while (my ($i, $s) = each @sums) {
next unless $s == $target;
return (int($i / ($#$elems + 1)), $i % ($#$elems + 1));
}
}
my ($i, $j) = find_pair [1, 2, 3, 5], 8;
print "$i $j\n";
#!/usr/bin/env python3
import hashlib
import logging
import secrets
import struct
import time
log = logging.getLogger(__name__)
zero_bytes = b'\x00' * 32
def has_zero_prefix(data_bytes, prefix_length):
for b in data_bytes:
if prefix_length <= 8:
return b >> (8 - prefix_length) == 0
if b != 0:
return False
prefix_length -= 8
return False
def hash_block(block):
h = hashlib.sha3_256()
h.update(block["parent"])
h.update(struct.pack("q", block["payload"]))
h.update(block["nonce"])
return h.digest()
def mine_block(block, difficulty=20):
start_time = time.perf_counter()
while not has_zero_prefix(hash_block(block), difficulty):
block["nonce"] = secrets.token_bytes(32)
end_time = time.perf_counter()
log.info("block mined in %.3fs", end_time - start_time)
def reverse_list_with_blockchain(l):
block_store = {}
last_block_hash = zero_bytes
for elem in l:
block = {
"parent": last_block_hash,
"payload": elem,
"nonce": zero_bytes,
}
mine_block(block)
last_block_hash = hash_block(block)
block_store[last_block_hash] = block
rev = []
next_block_hash = last_block_hash
while next_block_hash != zero_bytes:
rev.append(block_store[next_block_hash]["payload"])
next_block_hash = block_store[next_block_hash]["parent"]
return rev
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO)
print(reverse_list_with_blockchain([1, 3, 7, 5]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment