Guest User

Exact 3 Cover Heuristic 2

a guest
Apr 23rd, 2024
254
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 8.43 KB | Science | 0 0
  1. import sys
  2. import gmpy2
  3. import copy
  4. import os
  5. import math
  6. import scipy.sparse as sp
  7. import numpy as np
  8. import random
  9. import pyaudio
  10.  
  11. # This function generates data to seed the PRNG
  12. def generate_trng(num_samples):
  13.     CHUNK = 1024  # Number of frames per buffer
  14.     RATE = 44100  # Sample rate (samples per second)
  15.  
  16.     p = pyaudio.PyAudio()
  17.  
  18.     stream = p.open(format=pyaudio.paInt16,
  19.                     channels=1,
  20.                     rate=RATE,
  21.                     input=True,
  22.                     frames_per_buffer=CHUNK)
  23.  
  24.     print("Recording audio...")
  25.     audio_data = []
  26.     for _ in range(num_samples):
  27.         data = stream.read(CHUNK)
  28.         audio_data.append(np.frombuffer(data, dtype=np.int16))
  29.  
  30.     stream.stop_stream()
  31.     stream.close()
  32.     p.terminate()
  33.  
  34.     # Extract randomness from audio samples
  35.     random_numbers = []
  36.     for sample in audio_data:
  37.         # Calculate the sum of absolute differences between consecutive samples
  38.         diff_sum = np.sum(np.abs(np.diff(sample)))
  39.         random_numbers.append(diff_sum)
  40.  
  41.     return random_numbers
  42.  
  43. # Generate 10 True Random Numbers (TRNGs)
  44. random_numbers = generate_trng(10)
  45. k = random_numbers[2]
  46. random.seed(int(k))
  47. sys.set_int_max_str_digits(100000000)
  48. # Set precision for gmpy2 (optional)
  49. gmpy2.get_context().precision = 1000
  50.  
  51. def exact_3_cover():
  52.     # Exact 3 Cover, We're using 3-lists treated as sets
  53.     S = [1, 2, 3]
  54.     C = [[1, 2, 3], [4, 5, 6], [2, 3, 4]]
  55.  
  56.     #########################################################################
  57.     # Making sure 3-lists follow the rules of combinations
  58.     # And thus treated as sets
  59.     # Sort 3-lists and remove duplicates
  60.     C = [sorted(sublist) for sublist in C]
  61.     # remove duplicates of 3lists
  62.     removed_duplicates = []
  63.     for J in C:
  64.         if J not in removed_duplicates:
  65.             removed_duplicates.append(J)
  66.     C = removed_duplicates
  67.     # Remove 3lists with duplicate elements
  68.     C = [sublist for sublist in C if len(sublist) == len(set(sublist))]
  69.     # remove 3-lists that have elements not in S
  70.     C = [sublist for sublist in C if all(element in S for element in sublist)]
  71.     # Making a hard copy for reduction reference
  72.     C_copy = copy.deepcopy(C)
  73.  
  74.     #########################################################################
  75.     def is_prime(n):
  76.         if n <= 1:
  77.             return False
  78.         elif n <= 3:
  79.             return True
  80.         elif n % 2 == 0 or n % 3 == 0:
  81.             return False
  82.         i = 5
  83.         while i * i <= n:
  84.             if n % i == 0 or n % (i + 2) == 0:
  85.                 return False
  86.             i += 6
  87.         return True
  88.  
  89.     # Get the first N distinct odd primes
  90.     def get_primes_up_to_N(N):
  91.         primes = []
  92.         num = 3
  93.         while len(primes) < N:
  94.             if is_prime(num):
  95.                 primes.append(num)
  96.             num += 1
  97.         return primes
  98.     #########################################################################
  99.  
  100.     # Experimental Randomized Reduction of Exact-3-Cover into Subset Sum
  101.     # Get 10x the size of S primes for randomized reduction
  102.     primes = get_primes_up_to_N(len(S) * 10)
  103.     # Set R to three exponents to randomly assign
  104.     R = [5,6,7]
  105.     # create list of random distinct primes
  106.     random_primes = []
  107.     while len(random_primes) != len(S):
  108.         p = random.choice(primes)
  109.         if p not in random_primes:
  110.             random_primes.append(p)
  111.     new_S = [gmpy2.mpz(prime) ** random.choice(R) for prime in random_primes]
  112.     #########################################################################
  113.  
  114.     # Mapping new C
  115.     # Create a dictionary to map elements in S to their indices in new_S
  116.     index_mapping = {element: new_S[index] for index, element in enumerate(S)}
  117.  
  118.     # Mapping new C
  119.     for sublist in C:
  120.         for j in range(len(sublist)):
  121.             # Use the dictionary to map the elem to its corresponding value in new_S
  122.             sublist[j] = index_mapping[sublist[j]]
  123.  
  124.  
  125.     #########################################################################
  126.  
  127.     # Define N for Subset Sum dynamic solution
  128.     N = sum(new_S)
  129.     # Here we get the sums of the 3lists
  130.     get_the_sums = []
  131.     for i in C:
  132.         get_the_sums.append(sum(i))
  133.  
  134.     #########################################################################
  135.  
  136.     # Function to write a list to a file on the flash drive
  137.     def write_list_to_file(filename, data):
  138.         with open(filename, 'wb') as f:  # Open the file in binary mode
  139.             for row in data:
  140.                 # Convert boolean values to bytes before writing to file
  141.                 row_bytes = bytearray([1 if cell else 0 for cell in row])
  142.                 f.write(row_bytes)
  143.                 f.write(b'\n')  # Add newline separator
  144.  
  145.     #############################################################################################
  146.  
  147.     # Function to read a list from a file on the flash drive
  148.     def read_list_from_file(filename):
  149.         with open(filename, 'rb') as f:  # Open the file in binary mode
  150.             return [[byte != 0 for byte in line.strip()] for line in f]
  151.  
  152.     #########################################################################
  153.  
  154.     def isSubsetSumFlashDrive(arr, n, target, filename):
  155.         # Initialize a set to store the indices of subset sums that are possible
  156.         subset_indices = set()
  157.         subset_indices.add(0)  # 0 is always possible
  158.          
  159.         # Perform dynamic programming and write intermediate results to the flash drive
  160.         with open(filename, 'wb') as f:  # Open the file in binary write mode
  161.             for i in range(1, n + 1):
  162.                 new_indices = set()
  163.                 for j in subset_indices:
  164.                     new_indices.add(j + arr[i - 1])
  165.                      
  166.                 subset_indices.update(new_indices)
  167.                  
  168.                 # Convert boolean values to bytes and write them to the file
  169.                 for j in range(target + 1):
  170.                     f.write(np.uint8(int(j in subset_indices)).tobytes())
  171.  
  172.         # Backtrack to find the solution
  173.         # backtracking does not explore all possible subsets exhaustively.
  174.         # Instead, it prunes the search space
  175.         # This pruning is based on the information stored in the subset table.
  176.         solution = []
  177.         j = target
  178.         for i in range(n, 0, -1):
  179.             if j - arr[i - 1] in subset_indices:
  180.                 solution.append(arr[i - 1])
  181.                 j -= arr[i - 1]
  182.  
  183.         return target in subset_indices, solution[::-1]  # Return whether solution exists and the solution itself
  184.  
  185.     #########################################################################        
  186.  
  187.     # You must put the path here for the flash drive. Flash drive should be dedicated to this algorithm.
  188.     # Otherwise, the algorithm will throw a hissy fit
  189.     # You have to physically write out the file name on your flash drive, case sensitive
  190.  
  191.     subset_table_file = 'F:\\New folder\\subset_table.txt '
  192.     # Function to reset the subset table file before using the code.
  193.     def reset_subset_table(filename):
  194.         with open(filename, 'w') as f:
  195.             pass  # Simply open the file in write mode, which clears its contents
  196.     reset_subset_table(subset_table_file)
  197.  
  198.     #########################################################################      
  199.  
  200.     n = len(get_the_sums)
  201.     # Call isSubsetSumFlashDrive function with flash drive file path
  202.     solution = isSubsetSumFlashDrive(get_the_sums, n, N, subset_table_file)
  203.     cover = []
  204.     if solution[0] == True:
  205.         get_i = solution[1]
  206.         for i in get_i:
  207.             get_index = get_the_sums.index(i)
  208.             reverse_map = C_copy[get_index]
  209.             cover.append(reverse_map)
  210.     return cover
  211.  
  212. max_attempts = 10  # Define the maximum number of attempts
  213. cover = None  # Initialize cover
  214.  
  215. for attempt in range(max_attempts):
  216.     cover = exact_3_cover()
  217.     if cover and len(cover) == len(S)//3:
  218.         break
  219.     else:
  220.         reset_subset_table(subset_table_file)  # Reset the subset table
  221.         # Rerun the process to generate a new solution
  222.  
  223. if cover is None:
  224.     print("Maximum number of attempts reached. Solution not found.")
  225. else:
  226.     print(cover)
Advertisement
Add Comment
Please, Sign In to add comment