|
| 1 | +#from fpylll import * |
| 2 | +import random,math,operator,time |
| 3 | +from operator import itemgetter |
| 4 | +import numpy as np |
| 5 | +#from __future__ import division |
| 6 | +from numpy import matrix |
| 7 | +from numpy import linalg as LA |
| 8 | +from numpy import matlib |
| 9 | + |
| 10 | +def rand_bin_array(K, N): |
| 11 | + arr = np.array([0] * K + [1] * (N - K)) |
| 12 | + np.random.shuffle(arr) |
| 13 | + return arr |
| 14 | + |
| 15 | +def find_random(n, d, hamming): |
| 16 | + a = [random.randint(1, np.floor(2**((2-d)*n))) for _ in range(n)] |
| 17 | + density = float(len(a) / math.log(max(a),2)) |
| 18 | + solution = rand_bin_array(n-hamming,n) |
| 19 | + a0 = np.dot(solution, a) |
| 20 | + #return a, a0, density, sum(solution), len(solution), solution |
| 21 | + return a,0,sum(solution) |
| 22 | + |
| 23 | +def fp2mat(A): |
| 24 | + L = np.zeros(shape=(A.nrows,A.ncols)) |
| 25 | + for i in range(A.nrows): |
| 26 | + for j in range(A.ncols): |
| 27 | + L[i,j] = A[i,j] |
| 28 | + L = np.array(L) |
| 29 | + return L |
| 30 | + |
| 31 | +def mat2fp(A): |
| 32 | + L = matrix([A.shape[0],A.shape[1]]) |
| 33 | + for i in range(A.shape[0]): |
| 34 | + for j in range(A.shape[1]): |
| 35 | + L[i,j] = int(A[i,j]) |
| 36 | + return L |
| 37 | + |
| 38 | +def checking(b,n): |
| 39 | + i=0 |
| 40 | + x=np.array([0 for _ in range(n)]) |
| 41 | + check=(int(abs(b[n+1]))==1) |
| 42 | + while (check==True)&(i<n): |
| 43 | + check=(int(abs(b[i]))==1) |
| 44 | + i=i+1 |
| 45 | + if (i==n) & (check==True) & (b[n]==0) & (b[n+2]==0): |
| 46 | + for j in range(n): |
| 47 | + x[j]=abs(b[j]-b[n+1])/2 |
| 48 | + return 'Solution found!',x |
| 49 | + else: |
| 50 | + return "There's no solution" |
| 51 | + |
| 52 | +def knapsack_matrix(a,a0,hamming): |
| 53 | + density=float(len(a)/math.log(max(a),2)) |
| 54 | + n = len(a) |
| 55 | + N=int(np.sqrt(n))+2 |
| 56 | + L=matrix([[N*int(a[i]) for i in range(0, n)],[0 for i in range(0, n)],[N for i in range(0, n)]]) |
| 57 | + L=L.T |
| 58 | + M1 = np.matlib.identity(n) |
| 59 | + M1 = 2*M1; Mb = np.bmat([M1,L]) |
| 60 | + zerom = matrix([1 for i in range(0, n)]) |
| 61 | + zerom1 = np.bmat([zerom,matrix(N*int(a0)),matrix(1),matrix(int(hamming*N))]) |
| 62 | + B = np.vstack([Mb,zerom1]) |
| 63 | + B=mat2fp(B) |
| 64 | + return B |
0 commit comments