Commit 7fe0a893 authored by Mathieu Valois's avatar Mathieu Valois
Browse files

implements closest neighbor among k random words

parent b5b6513f
Loading
Loading
Loading
Loading
+43 −6
Original line number Diff line number Diff line
@@ -2,7 +2,7 @@

import sys
import time
import random as rand
import random
import Levenshtein as leven

class Robustness:
@@ -19,6 +19,9 @@ class Robustness:
		self.k = len(self.l)
		self.algo = self.rperm

	def swap(self, i, j):
		self.l[i], self.l[j] = self.l[j], self.l[i]

	def rperm(self):
		"""
		generator for a random permutation of the list self.l using
@@ -26,8 +29,37 @@ class Robustness:
		"""
		d = len(self.l)
		for i in range(d):
			r = rand.randint(i, d-1)
			self.l[i], self.l[r] = self.l[r], self.l[i]
			r = random.randint(i, d-1)
			self.swap(i, r)
			yield self.l[i]

	def closest_among_m_permutation(self, m=10):
		"""
		generates a permutation where w_0 is randomly choosen and w_n+1
		is the closest neighbor of w_n among m randomly choosen words.
		Uses the Fisher-Yates algorithm to browse the list.
		"""
		# select the first word w0
		d = len(self.l)
		i0 = random.randint(0, d-1)
		w0 = self.l[i0]
		self.swap(0, i0)
		yield w0
		# select all the remaining ones
		for i in range(1, d):
			# pick the closest one among m random ones
			i_n = random.randint(i, d-1)
			w_n = self.l[i_n]
			lowest_distance = self.distance(w0, w_n)
			lowest_index = i_n
			for j in range(m-1):
				i_n = random.randint(1, d-1)
				w_n = self.l[i_n]
				dist = self.distance(w0, w_n)
				if dist < lowest_distance:
					lowest_distance = dist
					lowest_index = i_n
			self.swap(i, lowest_index)
			yield self.l[i]

	def cost_rate(self):
@@ -52,9 +84,15 @@ class Robustness:
		"""
		runs n excursions and returns the lowest cost rate found among them.
		"""
		before = time.time()
		min_c = self.cost_rate()
		after = time.time()
		print(after-before)
		for i in range(n-1):
			before = time.time()
			min_c = min(min_c, self.cost_rate())
			after = time.time()
			print(after-before)
		return min_c

	def all_distances(self):
@@ -70,7 +108,6 @@ class Robustness:

if __name__ == '__main__':
	R = Robustness(sys.argv[1])
	R.all_distances()
	exit()
	R.k = int(len(R.l)/5)
	R.algo = R.closest_among_m_permutation
	R.k = int(len(R.l)/20)
	print(R.min_rperm(n=10))
 No newline at end of file