Skip to content

Commit

Permalink
did added more scripts
Browse files Browse the repository at this point in the history
  • Loading branch information
hearues-zueke-github committed Aug 13, 2018
1 parent 0687143 commit 89f6fcc
Show file tree
Hide file tree
Showing 6 changed files with 405 additions and 40 deletions.
56 changes: 34 additions & 22 deletions c_programs/own_big_integer/own_big_integer.c
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,9 @@ void convert_a_to_base_2(BigNum a, BigNum** result) {
new_num->last_significant_byte = i;

*result = new_num;

printf("result: ");
print_big_num(*new_num);
}

void calc_a_plus_b(BigNum a, BigNum b, BigNum** result) {
Expand Down Expand Up @@ -188,10 +191,10 @@ void calc_a_mult_b(BigNum a, BigNum b, BigNum** result) {
int size_b = b.size;
int base = a.base;

printf("a: ");
print_big_num(a);
printf("b: ");
print_big_num(b);
// printf("a: ");
// print_big_num(a);
// printf("b: ");
// print_big_num(b);

int max_size = size_a+size_b+1;
uint8_t* arr = calloc(sizeof(uint8_t), max_size);
Expand Down Expand Up @@ -229,8 +232,8 @@ void calc_a_mult_b(BigNum a, BigNum b, BigNum** result) {

*result = res;

printf("res: ");
print_big_num(*res);
// printf("res: ");
// print_big_num(*res);
}

void calc_a_div_b(BigNum a, BigNum b, BigNum** result, BigNum** rest) {
Expand Down Expand Up @@ -441,10 +444,11 @@ void calc_a_pow_b(BigNum a, BigNum b, BigNum** result) {
int size = b_base2->size-1;
int i;
for (i = 0; ; i++) {
if (1 || b_base2->arr[i]) {
printf("i: %d\n", i);
if (b_base2->arr[i]) {
BigNum* temp3;
printf("temp: %p\n", temp);
printf("p: %p\n", p);
printf("temp: %p, p: %p\n", temp, p);
// printf("p: %p\n", p);
calc_a_mult_b(*temp, *p, &temp3);
delete_big_num(p);
p = temp3;
Expand All @@ -457,8 +461,8 @@ void calc_a_pow_b(BigNum a, BigNum b, BigNum** result) {
BigNum* temp2;
printf("temp: %p\n", temp);
calc_a_mult_b(*temp, *temp, &temp2);
// delete_big_num(temp);
// temp = temp2;
delete_big_num(temp);
temp = temp2;
}

delete_big_num(b_base2);
Expand All @@ -475,17 +479,25 @@ void print_big_num(BigNum bignum) {
// int last_significant_byte = bignum.last_significant_byte;

int num_size = (base <= 10 ? 1 : base <= 100 ? 2 : 3);
char* buffer = malloc(sizeof(char)*((num_size+2)*size));
char* buffer = malloc(sizeof(char)*((num_size+2)*size+2));
char format[6] = {0};
sprintf(format, "%%%dd, ", num_size);
int i = 0;
buffer[0] = '(';
for (i = 0; i < size; i++) {
sprintf(buffer+i*(num_size+2), format, arr[i]);
sprintf(buffer+i*(num_size+2)+1, format, arr[i]);
}
// sprintf(buffer+size*(num_size+2)-2, "\0");
*(buffer+size*(num_size+2)-2) = 0;
buffer[size*(num_size+2)-1] = ')';
buffer[size*(num_size+2)] = 0;

printf("%s; size: %d; base: %d\n", buffer, bignum.size, bignum.base);

printf("%s; size: %d\n", buffer, bignum.size);
int j;
for (i = size-1, j = 0; i > -1; i--, j++) {
buffer[i] = '0'+arr[j];
}
buffer[j] = 0;
printf("full number: %s\n", buffer);

free(buffer);
}
Expand All @@ -499,17 +511,17 @@ int main(int argc, char* argv[]) {

BigNum bignum_a;
bignum_a.base = base;
uint8_t arr_a[3] = {2, 3, 9};
uint8_t arr_a[1] = {7};
bignum_a.arr = arr_a;
bignum_a.size = 3;
bignum_a.last_significant_byte = 2;
bignum_a.size = 1;
bignum_a.last_significant_byte = 0;

BigNum bignum_b;
bignum_b.base = base;
uint8_t arr_b[4] = {8, 5, 2, 4};
uint8_t arr_b[6] = {0, 0, 0, 0, 0, 1};
bignum_b.arr = arr_b;
bignum_b.size = 4;
bignum_b.last_significant_byte = 3;
bignum_b.size = 6;
bignum_b.last_significant_byte = 5;

BigNum* bignum_result;
BigNum* bignum_result_mult;
Expand Down
81 changes: 63 additions & 18 deletions encryption/create_s_box_from_powers.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,26 +17,71 @@

import Utils

if __name__ == "__main__":
sbox_amount = 256
# sbox_byte_counter = np.zeros((256, ), dtype=np.int)
sbox_byte_counter = np.zeros((256*256, ), dtype=np.int)
sboxes = [[] for _ in range(0, sbox_amount)]
class SBox(Exception):
def __init__(self, sbox, bits=8):
assert bits == 8 or bits == 16
self.sbox = np.array(sbox)
self.bits = bits
self.length = self.sbox.shape[0]
if bits == 8:
self.check_sbox_8bit()
elif bits == 16:
self.check_sbox_16bit()

def check_sbox_8bit(self):
sbox = self.sbox
if sbox.shape[0] != 256:
self.sbox_ok = False
return

if np.any(sbox == np.arange(0, 256)):
self.sbox_ok = False
return

self.sbox_ok = True

def check_sbox_16bit(self):
pass

class SBoxes(Exception):
def __init__(self, number, sbox_amount, bits=8):
self.number = number
self.sbox_amount = sbox_amount
self.bits = bits

self.sboxes = self.calculate_sboxes(number, sbox_amount, bits)

arr_str = np.array(list((lambda s: s[2:(lambda n: n-n%2)(len(s))])(hex(5**7000000)))).reshape((-1, 2)).T
arr_hex_str = (lambda arr: np.core.defchararray.add("0x", np.core.defchararray.add(arr[0], arr[1])))(arr_str)
arr = np.vectorize(lambda x: int(x, 16))(arr_hex_str)
def calculate_sboxes(self, number, sbox_amount, bits=8):
assert bits == 8 or bits == 16
# sbox_amount = 256
sboxes = [[] for _ in range(0, sbox_amount)]

arr = arr[:-1]*256+arr[1:]
arr_str = np.array(list((lambda s: s[2:(lambda n: n-n%2)(len(s))])(hex(number)))).reshape((-1, 2)).T
arr_hex_str = (lambda arr: np.core.defchararray.add("0x", np.core.defchararray.add(arr[0], arr[1])))(arr_str)
arr = np.vectorize(lambda x: int(x, 16))(arr_hex_str)

print("arr:\n{}".format(arr))
sbox_byte_counter = np.zeros((256, ), dtype=np.int)
if bits == 16:
sbox_byte_counter = np.zeros((256*256, ), dtype=np.int)
arr = arr[:-1]*256+arr[1:]

for i in arr:
if sbox_byte_counter[i] < sbox_amount:
sboxes[sbox_byte_counter[i]].append(i)
sbox_byte_counter[i] += 1
print("arr:\n{}".format(arr))

for idx, sbox in enumerate(sboxes):
print("idx: {}, len(sbox): {}".format(idx, len(sbox)))
# Utils.pretty_block_printer(sbox, 8, len(sbox))
print("")
for i in arr:
if sbox_byte_counter[i] < sbox_amount:
sboxes[sbox_byte_counter[i]].append(i)
sbox_byte_counter[i] += 1

for idx, sbox in enumerate(sboxes):
print("idx: {}, len(sbox): {}".format(idx, len(sbox)))
# Utils.pretty_block_printer(sbox, 8, len(sbox))
print("")

return [SBox(np.array(sbox)) for sbox in sboxes]

def get_only_ok_sboxes(self):
return np.array([sbox for sbox in self.sboxes if sbox.sbox_ok])


if __name__ == "__main__":
sboxes = SBoxes(3**300000, 200)
126 changes: 126 additions & 0 deletions light_off_game/analysis.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
#! /usr/bin/python3.5

# -*- coding: utf-8 -*-

import sys

import numpy as np

modulo = 2

def generate_field_position_crosses(n):
positions = np.zeros((n+2, n+2), dtype=object)

for y in range(1, n+1):
for x in range(1, n+1):
positions[y, x] = np.array([[y, x], [y, x+1], [y, x-1], [y+1, x], [y-1, x]], dtype=np.int8)

positions = positions[1:n+1, 1:n+1]-1

# now calc -1 and eliminate everything which contains 0 or n as a value
y_x_coords = \
[(y, 0) for y in range(0, n)] + \
[(y, n-1) for y in range(0, n)] + \
[(0, x) for x in range(1, n-1)] + \
[(n-1, x) for x in range(1, n-1)]

for y, x in y_x_coords:
coordinates = positions[y, x]
remove_idx = np.where(np.logical_or.reduce((coordinates==-1) | (coordinates==n), axis=1))[0]
positions[y, x] = np.delete(coordinates, remove_idx, axis=0)

for y in range(0, n):
for x in range(0, n):
positions[y, x] = list(map(tuple, positions[y, x].T.tolist()))

return positions

def apply_on_field(field, positions, y_x_coords):
for y, x in y_x_coords:
coordinates = positions[y, x]
field[coordinates] = (field[coordinates]+1) % modulo

def apply_on_field_once(field, positions, y, x):
coordinates = positions[y, x]
field[coordinates] = (field[coordinates]+1) % modulo

def mix_field(field, positions):
n = field.shape[0]

mix_field_arr = np.random.randint(0, 2, (n, n))
print("mix_field_arr:\n{}".format(mix_field_arr))
y_x_coords = np.array(np.where(mix_field_arr == 1)).T
apply_on_field(field, positions, y_x_coords)

def solve_field(field, positions):
n = field.shape[0]
field_orig = field.copy()

# first do something on the first row
# second solve from the frist until the n-1 row
# third check if the last row n is solved, if now, repeat from fist step
# until it is done

tries = 1
is_not_solved = True
while is_not_solved:
# print("tries: {}".format(tries))
field = field_orig.copy()
moves_done = np.zeros((n, n), dtype=np.int8)

# print("before solving:")
# print("field:\n{}".format(field))

random_moves = np.random.randint(0, 2, (n, )) # for the last row (n-th row)
for i in np.where(random_moves == 1)[0]:
apply_on_field_once(field, positions, n-1, i)

moves_done[-1] = random_moves

# print("after last row finish")
# print("field:\n{}".format(field))

for y in range(n-2, -1, -1):
for x in range(0, n):
if field[y+1, x] == 1:
apply_on_field_once(field, positions, y, x)
moves_done[y, x] = 1

# print("after row #: {}".format(y))
# print("field:\n{}".format(field))

if np.sum(field[0]) == 0:
is_not_solved = False

# sys.exit(0)

tries += 1

print("last try at tries: {}".format(tries))

# print("moves_done:\n{}".format(moves_done))

return moves_done

if __name__ == "__main__":
n = 5

field = np.zeros((n, n), dtype=np.uint8)

positions = generate_field_position_crosses(n)

print("\nbefore mixing:")
print("field:\n{}".format(field))

mix_field(field, positions)

print("\nafter mixing:")
print("field:\n{}".format(field))

moves_done = solve_field(field, positions)
print("\nmoves_done:\n{}".format(moves_done))

apply_on_field(field, positions, np.array(np.where(moves_done == 1)).T)

print("\nafter moving:")
print("field:\n{}".format(field))
62 changes: 62 additions & 0 deletions math_numbers/find_patterns_in_special_numbers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
#! /usr/bin/python3.5

import decimal
import math

import numpy as np

import matplotlib.pyplot as plt

from decimal import Decimal as D
from functools import reduce

decimal.getcontext().prec = 2000

# TODO: maybe interesting for Numberphile?!

def remove_leading_zeros(l):
l = np.array(l).copy()
i = 0
while l[i] == 0:
i += 1
l = l[i:]
return l

def find_pattern(l):
l = remove_leading_zeros(l)

length = l.shape[0]

max_idx = length//2
n = l[0]
start_idx = 1
while n == l[start_idx]:
start_idx += 1
if start_idx >= max_idx:
return np.array([n])

for i in range(start_idx, max_idx):
if np.sum(l[:i] != l[i:i*2]) == 0:
return l[:i]

return np.array([])

if __name__ == "__main__":
# print("Hello World!")
print("Calculating numbers")
num = 9
p = 1
nums = []
max_power = 7000
for i in range(1000, max_power):
p *= num
nums.append(list(map(int, str(p))))

print("Getting them into the matrix")
matrix = np.zeros((len(nums), len(nums[-1])), dtype=np.int)
for i in range(0, len(nums)):
l = nums[i]
matrix[i, :len(l)] = l[::-1]

print("Finding the pattern")
patterns = [(lambda x: (i, len(x), x))(find_pattern(l)) for i, l in enumerate(matrix.T[:int(np.sqrt(max_power))])]
Loading

0 comments on commit 89f6fcc

Please sign in to comment.