Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import sys
- import gmpy2
- import copy
- import os
- import math
- import scipy.sparse as sp
- import numpy as np
- import random
- import pyaudio
- # This function generates data to seed the PRNG
- def generate_trng(num_samples):
- CHUNK = 1024 # Number of frames per buffer
- RATE = 44100 # Sample rate (samples per second)
- p = pyaudio.PyAudio()
- stream = p.open(format=pyaudio.paInt16,
- channels=1,
- rate=RATE,
- input=True,
- frames_per_buffer=CHUNK)
- print("Recording audio...")
- audio_data = []
- for _ in range(num_samples):
- data = stream.read(CHUNK)
- audio_data.append(np.frombuffer(data, dtype=np.int16))
- stream.stop_stream()
- stream.close()
- p.terminate()
- # Extract randomness from audio samples
- random_numbers = []
- for sample in audio_data:
- # Calculate the sum of absolute differences between consecutive samples
- diff_sum = np.sum(np.abs(np.diff(sample)))
- random_numbers.append(diff_sum)
- return random_numbers
- # Generate 10 True Random Numbers (TRNGs)
- random_numbers = generate_trng(10)
- k = random_numbers[2]
- random.seed(int(k))
- sys.set_int_max_str_digits(100000000)
- # Set precision for gmpy2 (optional)
- gmpy2.get_context().precision = 1000
- def exact_3_cover():
- # Exact 3 Cover, We're using 3-lists treated as sets
- S = [1, 2, 3]
- C = [[1, 2, 3], [4, 5, 6], [2, 3, 4]]
- #########################################################################
- # Making sure 3-lists follow the rules of combinations
- # And thus treated as sets
- # Sort 3-lists and remove duplicates
- C = [sorted(sublist) for sublist in C]
- # remove duplicates of 3lists
- removed_duplicates = []
- for J in C:
- if J not in removed_duplicates:
- removed_duplicates.append(J)
- C = removed_duplicates
- # Remove 3lists with duplicate elements
- C = [sublist for sublist in C if len(sublist) == len(set(sublist))]
- # remove 3-lists that have elements not in S
- C = [sublist for sublist in C if all(element in S for element in sublist)]
- # Making a hard copy for reduction reference
- C_copy = copy.deepcopy(C)
- #########################################################################
- def is_prime(n):
- if n <= 1:
- return False
- elif n <= 3:
- return True
- elif n % 2 == 0 or n % 3 == 0:
- return False
- i = 5
- while i * i <= n:
- if n % i == 0 or n % (i + 2) == 0:
- return False
- i += 6
- return True
- # Get the first N distinct odd primes
- def get_primes_up_to_N(N):
- primes = []
- num = 3
- while len(primes) < N:
- if is_prime(num):
- primes.append(num)
- num += 1
- return primes
- #########################################################################
- # Experimental Randomized Reduction of Exact-3-Cover into Subset Sum
- # Get 10x the size of S primes for randomized reduction
- primes = get_primes_up_to_N(len(S) * 10)
- # Set R to three exponents to randomly assign
- R = [5,6,7]
- # create list of random distinct primes
- random_primes = []
- while len(random_primes) != len(S):
- p = random.choice(primes)
- if p not in random_primes:
- random_primes.append(p)
- new_S = [gmpy2.mpz(prime) ** random.choice(R) for prime in random_primes]
- #########################################################################
- # Mapping new C
- # Create a dictionary to map elements in S to their indices in new_S
- index_mapping = {element: new_S[index] for index, element in enumerate(S)}
- # Mapping new C
- for sublist in C:
- for j in range(len(sublist)):
- # Use the dictionary to map the elem to its corresponding value in new_S
- sublist[j] = index_mapping[sublist[j]]
- #########################################################################
- # Define N for Subset Sum dynamic solution
- N = sum(new_S)
- # Here we get the sums of the 3lists
- get_the_sums = []
- for i in C:
- get_the_sums.append(sum(i))
- #########################################################################
- # Function to write a list to a file on the flash drive
- def write_list_to_file(filename, data):
- with open(filename, 'wb') as f: # Open the file in binary mode
- for row in data:
- # Convert boolean values to bytes before writing to file
- row_bytes = bytearray([1 if cell else 0 for cell in row])
- f.write(row_bytes)
- f.write(b'\n') # Add newline separator
- #############################################################################################
- # Function to read a list from a file on the flash drive
- def read_list_from_file(filename):
- with open(filename, 'rb') as f: # Open the file in binary mode
- return [[byte != 0 for byte in line.strip()] for line in f]
- #########################################################################
- def isSubsetSumFlashDrive(arr, n, target, filename):
- # Initialize a set to store the indices of subset sums that are possible
- subset_indices = set()
- subset_indices.add(0) # 0 is always possible
- # Perform dynamic programming and write intermediate results to the flash drive
- with open(filename, 'wb') as f: # Open the file in binary write mode
- for i in range(1, n + 1):
- new_indices = set()
- for j in subset_indices:
- new_indices.add(j + arr[i - 1])
- subset_indices.update(new_indices)
- # Convert boolean values to bytes and write them to the file
- for j in range(target + 1):
- f.write(np.uint8(int(j in subset_indices)).tobytes())
- # Backtrack to find the solution
- # backtracking does not explore all possible subsets exhaustively.
- # Instead, it prunes the search space
- # This pruning is based on the information stored in the subset table.
- solution = []
- j = target
- for i in range(n, 0, -1):
- if j - arr[i - 1] in subset_indices:
- solution.append(arr[i - 1])
- j -= arr[i - 1]
- return target in subset_indices, solution[::-1] # Return whether solution exists and the solution itself
- #########################################################################
- # You must put the path here for the flash drive. Flash drive should be dedicated to this algorithm.
- # Otherwise, the algorithm will throw a hissy fit
- # You have to physically write out the file name on your flash drive, case sensitive
- subset_table_file = 'F:\\New folder\\subset_table.txt '
- # Function to reset the subset table file before using the code.
- def reset_subset_table(filename):
- with open(filename, 'w') as f:
- pass # Simply open the file in write mode, which clears its contents
- reset_subset_table(subset_table_file)
- #########################################################################
- n = len(get_the_sums)
- # Call isSubsetSumFlashDrive function with flash drive file path
- solution = isSubsetSumFlashDrive(get_the_sums, n, N, subset_table_file)
- cover = []
- if solution[0] == True:
- get_i = solution[1]
- for i in get_i:
- get_index = get_the_sums.index(i)
- reverse_map = C_copy[get_index]
- cover.append(reverse_map)
- return cover
- max_attempts = 10 # Define the maximum number of attempts
- cover = None # Initialize cover
- for attempt in range(max_attempts):
- cover = exact_3_cover()
- if cover and len(cover) == len(S)//3:
- break
- else:
- reset_subset_table(subset_table_file) # Reset the subset table
- # Rerun the process to generate a new solution
- if cover is None:
- print("Maximum number of attempts reached. Solution not found.")
- else:
- print(cover)
Advertisement
Add Comment
Please, Sign In to add comment