tsounakis

Algorithms #1 ver. Doom

Mar 16th, 2022 (edited)
882
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.61 KB | None | 0 0
  1. from cmath import inf
  2. import random
  3. from timeit import default_timer as timer
  4.  
  5.  
  6. def main():
  7.     cases = [10, 100, 500]
  8.     Algorithms = []
  9.  
  10.     benchmark = Benchmark()
  11.  
  12.     for case in cases:
  13.         for Algorithm in [BruteForce, ImprovedApproach, DivideAndConquer, Linear]:
  14.             Algorithms.append(Algorithm(benchmark.createList(1072771, case)))
  15.  
  16.     print("{:<10} {:<30} {:<30} {:<30} {:<30} {:<30}".format('Length', 'Algorithm',
  17.           'Elapsed Time (s)', 'Maximum Sum', 'Subarray Position', 'Time Complexity'))
  18.     print("{:<10} {:<30} {:<30} {:<30} {:<30} {:<30}".format('--------', '--------',
  19.           '--------', '--------', '--------', '--------'))
  20.  
  21.     benchmark.set(Algorithms)
  22.     benchmark.run()
  23.  
  24.  
  25. class Algorithm():
  26.     def __init__(self, numbers):
  27.         self.numbers = numbers
  28.         self.bounds = None
  29.         self.maximum = None
  30.         self.linear = []
  31.  
  32.  
  33. class BruteForce(Algorithm):
  34.     def __init__(self, numbers):
  35.         self.complexity = 'O(n^3)'
  36.         self.name = 'Brute Force'
  37.         super().__init__(numbers)
  38.  
  39.     def run(self):
  40.         '''O(n^3) complexity, a brute force approach'''
  41.         n = len(self.numbers)
  42.         m = 0
  43.         for i in range(n):
  44.             for j in range(i, n):
  45.                 s = 0
  46.                 for k in range(i, j + 1):
  47.                     s += self.numbers[k]
  48.                 if m < s:
  49.                     self.bounds = (i, j)
  50.                     m = max(m, s)
  51.         self.maximum = m
  52.         return None
  53.  
  54.  
  55. class ImprovedApproach(Algorithm):
  56.     def __init__(self, numbers):
  57.         self.complexity = 'O(n^2)'
  58.         self.name = 'Improved Approach'
  59.         super().__init__(numbers)
  60.  
  61.     def run(self):
  62.         '''O(n^2) complexity'''
  63.         n = len(self.numbers)
  64.         s = [0]*(n+1)
  65.         for i in range(n):
  66.             s[i+1] = s[i]+self.numbers[i]
  67.         m = 0
  68.         for i in range(n):
  69.             for j in range(i, n):
  70.                 if m < s[j+1] - s[i]:
  71.                     self.bounds = (i, j)
  72.                 m = max(m, s[j+1] - s[i])
  73.         self.maximum = m
  74.         return None
  75.  
  76.  
  77. class DivideAndConquer(Algorithm):
  78.     def __init__(self, numbers):
  79.         self.complexity = 'O(nlogn)'
  80.         self.name = 'Divide And Conquer'
  81.         super().__init__(numbers)
  82.  
  83.     def run(self, lower=0, upper=None):
  84.         if upper is None:
  85.             upper = len(self.numbers) - 1
  86.  
  87.         def maxCrossing(array, lower, mid, upper):
  88.             sum_left = -inf
  89.             sum_temp = 0
  90.             cross_lower = mid
  91.             for i in range(mid - 1, lower - 1, -1):
  92.                 sum_temp = sum_temp + array[i]
  93.                 if sum_temp > sum_left:
  94.                     sum_left = sum_temp
  95.                     cross_lower = i
  96.  
  97.             right = -inf
  98.             sum_temp = 0
  99.             cross_upper = mid + 1
  100.             for i in range(mid, upper):
  101.                 sum_temp = sum_temp + array[i]
  102.                 if sum_temp > right:
  103.                     right = sum_temp
  104.                     cross_upper = i + 1
  105.             return cross_lower, cross_upper, sum_left + right
  106.  
  107.         if lower == upper - 1:
  108.             return lower, upper, self.numbers[lower]
  109.         else:
  110.             mid = (lower + upper)//2
  111.             left_lower, left_upper, left_max = self.run(lower, mid)
  112.             right_lower, right_upper, right_max = self.run(mid, upper)
  113.             cross_lower, cross_upper, cross_max = maxCrossing(
  114.                 self.numbers, lower, mid, upper)
  115.             if (left_max > right_max and left_max > cross_max):
  116.                 self.bounds = (left_lower, left_upper-1)
  117.                 return left_lower, left_upper, left_max
  118.             elif (right_max > left_max and right_max > cross_max):
  119.                 self.bounds = (right_lower, right_upper-1)
  120.                 return right_lower, right_upper, right_max
  121.             else:
  122.                 self.bounds = (cross_lower, cross_upper-1)
  123.                 return cross_lower, cross_upper, cross_max
  124.  
  125.  
  126. class Linear(Algorithm):
  127.     def __init__(self, numbers):
  128.         self.complexity = 'O(n)'
  129.         self.name = 'Kadane\'s Approach'
  130.         super().__init__(numbers)
  131.  
  132.     def run(self):
  133.         '''O(n) complexity'''
  134.         lower = 0
  135.         upper = 0
  136.         m = [self.numbers[0], 0]  # m[0] is the max, m[1] is a temp dummy max
  137.         for i in range(0, len(self.numbers)):
  138.             upper = i
  139.             m[1] = m[1] + self.numbers[i]
  140.             if m[1] <= 0:
  141.                 m[1] = 0
  142.                 lower = upper + 1
  143.             elif (m[0] < m[1]):
  144.                 m[0] = m[1]
  145.                 self.bounds = (lower, upper)
  146.  
  147.         self.maximum = m[0]
  148.         return None
  149.  
  150.  
  151. class Benchmark():
  152.     def __init__(self):
  153.         pass
  154.  
  155.     def set(self, algorithms):
  156.         self.algorithms = algorithms
  157.  
  158.     def createList(self, seed, case):
  159.         _ = random.seed(seed)
  160.         return [random.randint(-100, 100) for _ in range(case)]
  161.  
  162.     def run(self):
  163.         for algorithm in self.algorithms:
  164.             self.runAlgorithm(algorithm, len(algorithm.numbers))
  165.  
  166.     def runAlgorithm(self, algorithm, case):
  167.         start = timer()
  168.         maximum = algorithm.run()
  169.         end = timer()
  170.         realMaximum = maximum[2] if not maximum == None else algorithm.maximum
  171.         algorithm.linear.append([case, -start+end])
  172.         print("{:<10} {:<30} {:<30} {:<30} {:<30} {:<30}".format(case, algorithm.name, '{0:.8f}'.format(-start+end),
  173.                                                                  realMaximum, ', '.join(map(str, algorithm.bounds)), algorithm.complexity))
  174.  
  175.  
  176. if __name__ == '__main__':
  177.     main()
  178.  
Add Comment
Please, Sign In to add comment