Esempio n. 1
0
#!/usr/bin/python

from Solution import Solution

obj = Solution()

A = 500
B = [1, 2, 5]
out = obj.change(A, B)
print(out)
Esempio n. 2
0
from Solution import Solution

s = Solution()

data = [123, -123, 120]

for d in data:
    res = s.reverse(d)
    # break point goes here
    pass
Esempio n. 3
0
 def test_size(self):
     sol = Solution()
     self.assertEqual(7, sol.getSize(1012101))
Esempio n. 4
0
#!/usr/bin/python

from Solution import Solution

A = [1, 1, 4, 2, 3]
B = 5
obj = Solution()
print(obj.minOperations(A, B))
Esempio n. 5
0
def findSolution(n, matrix):
	field = Field()
	field.createField(matrix)
	field.printField()

	solutions = Queue()

	minSolution = None
	cache = ComboCache()
	preAnsweredCache = {}
	
	for j in range(1,n+1):
		preAnsweredCache[j]= []

	for i in range(1,n+1):
		cache.clear()

		if (i-2 in preAnsweredCache):
			for sol in preAnsweredCache[i-2]:
				newSolution = Solution(field)
				newSolution.setState(solution)
				newSolution.maxGreenhouses = i
				solutions.put(newSolution)
		else:
			firstSolution = Solution(field)
			firstSolution.maxGreenhouses = i
			solutions.put(firstSolution)
		
		while (not solutions.empty()):
			solution = solutions.get()
			if (minSolution == None or solution.computeCost() < minSolution.computeCost()):
				if (solution.getNumberOfGreenhouses() == (solution.maxGreenhouses-1)):
					## find the leftmost, topmost, rightmost, bottommost 
					## uncovered points. They form your final greenhouse.
					## if left < right and top < bottom (or right > right and bottom > bottom,
					## it overlaps, and no solution using this is possible.
					if (solution.placeFinalGreenhouse()):
						cost = solution.computeCost()
						if (minSolution == None or cost < minSolution.computeCost()):
							minSolution = solution
				else:
					## iterate through the remaining uncovereds, both for start
					## and end. reject overlaps!

					for corner1 in solution.getRemaining():
						for corner2 in solution.getRemaining():				
							newSolution = Solution(field)
							newSolution.setState(solution)
							if (newSolution.placeGreenhouse(corner1.x, corner2.x, corner1.y, corner2.y)):
								if (not cache.isPresent(newSolution)):
									solutions.put(newSolution)
									preAnsweredCache[newSolution.getNumberOfGreenhouses()].append(newSolution)
									cache.insert(newSolution)
						
	minSolution.printSolution()
Esempio n. 6
0
from Solution import Solution

s = Solution()
print s.findMedianSortedArrays(nums1=[2,3,4],nums2=[3,5,6])
Esempio n. 7
0
from Solution import Solution

s = Solution()
print s.longestPalindrome(s="aabbbbb")
Esempio n. 8
0
    def cross_population_PMX(self, index, second_index, rand_two_vertex):
        p_path = self.population[index].get_path()
        q_path = self.population[second_index].get_path()

        r_path = [-1 for i in range(len(p_path))]
        s_path = [-1 for i in range(len(p_path))]

        list_of_mappings = []
        for i in range(rand_two_vertex[0], rand_two_vertex[1] + 1):
            r_path[i] = q_path[i]
            s_path[i] = p_path[i]
            mapping = [q_path[i], p_path[i]]
            list_of_mappings.append(mapping)

        ################################################################################################################

        if rand_two_vertex[0] == 0 and rand_two_vertex[1] == 16:
            return

        ################################################################################################################

        for i in range(0, len(p_path)):
            if i not in range(rand_two_vertex[0], rand_two_vertex[1] + 1):
                if p_path[i] not in r_path:
                    # add cities without conflicts
                    r_path[i] = p_path[i]
                else:
                    # add cities from mapping list
                    try_find_city = p_path[i]
                    find_city = False
                    while True:
                        for mapp in list_of_mappings:
                            if mapp[0] == try_find_city:
                                try_find_city = mapp[1]
                                if try_find_city not in r_path:
                                    r_path[i] = try_find_city
                                    find_city = True
                                    break
                                else:
                                    break
                        if find_city:
                            break

                if q_path[i] not in s_path:
                    s_path[i] = q_path[i]
                else:
                    try_find_city = q_path[i]
                    find_city = False
                    while True:
                        for mapp in list_of_mappings:
                            if mapp[1] == try_find_city:
                                try_find_city = mapp[0]
                                if try_find_city not in s_path:
                                    s_path[i] = try_find_city
                                    find_city = True
                                    break
                                else:
                                    break
                        if find_city:
                            break

        ################################################################################################################

        new_solution = Solution(len(r_path), create_new=False)
        new_solution.set_path(r_path)
        new_solution.set_calculated_weight(self.matrix)
        self.population.append(new_solution)

        new_solution = Solution(len(s_path), create_new=False)
        new_solution.set_path(s_path)
        new_solution.set_calculated_weight(self.matrix)
        self.population.append(new_solution)
Esempio n. 9
0
def solve(bvp_problem,
          solution_guess,
          initial_mesh = None,
          parameter_guess = None,
          max_subintervals = 300,
          singular_term = None,
          tolerance = 1.0e-6,
          method = 4,
          trace = 0,
          error_on_fail = True):
    """Attempts to solve the supplied boundary value problem starting from the user supplied guess for the solution using BVP_SOLVER.

    Parameters
    ----------
    bvp_problem : :class:`ProblemDefinition`
        Defines the boundary value problem to be solved.
    solution_guess : :class:`Solution`, constant, array of values or function
        A guess for the solution.
    initial_mesh : castable to floating point ndarray
        Points on the x-axis to use for the supplied solution guess, default is 10 evenly spaced points. Must not be supplied if solution_guess is a :class:`Solution` object.
    parameter_guess : castable to floating point ndarray, shape (num_parameters)
        Guesses for the unknown parameters. Must not be supplied if solution_guess is a :class:`Solution` object.
    max_subintervals : int
        Maximum number of points on the mesh before an error is returned.
    singular_term : castable to floating point ndarray, shape(num_ODE, num_ODE)
        Matrix that defines the singular term for the problem if one exist.
    tolerance : positive float
        Tolerance for size of defect of approximate solution.
    method : {2, 4, 6}
        Order of Runge-Kutta to use.
    trace : {0, 1, 2}
        Indicates verbosity of output. 0 for no output, 1 for some output, 2 for full output.
    error_on_fail : logical
        Indicates whether an exception should be raised if solving fails.

    Returns
    -------
    sol : :class:`Solution`
        Approximate problem solution.

    Raises
    ------
    ValueError
        If bvp_problem failed validation in some way.
    ValueError
        If solving fails.
    """

    init_solution = 0

    if isinstance(solution_guess, Solution):
        if not (initial_mesh == None and
                parameter_guess == None):
            raise ValueError("values for initial mesh and parameter_guess must not be given if solution_guess is a Solution object")
        init_solution = solution_guess
    else:

        if initial_mesh == None:
            initial_mesh = numpy.linspace(bvp_problem.boundary_points[0],bvp_problem.boundary_points[1] , 10)

        # here we call one of the BVP_GUESS_i routines that make up BVP_INIT to set up the solution
        if ( not callable(solution_guess)):   # in this case the initial solution passed was not a function

            #try to cast the solution to an array
            solution_guess = numpy.array(solution_guess)

            # if the solution_guess is just an array the size of ODE
            if solution_guess.shape == (bvp_problem.num_ODE,) or (solution_guess.shape == () and bvp_problem.num_ODE == 1):

                bvp_solverf.bvp.guess_1_wrap(nparam_in = bvp_problem.num_parameters,
                                           leftbc_in = bvp_problem.num_left_boundary_conditions,
                                           x_in = tools.farg(initial_mesh),
                                           y_in = tools.farg(solution_guess),
                                           parameters_in = tools.farg(parameter_guess),
                                           mxnsub_in = max_subintervals,
                                           node_in = bvp_problem.num_ODE)

                init_solution = Solution.from_arg_list(bvp_solverf.bvp)

            else:

                tools.argShapeTest(solution_guess, (bvp_problem.num_ODE,initial_mesh.shape[0]), "solution guess")

                bvp_solverf.bvp.guess_2_wrap(nparam_in = bvp_problem.num_parameters,
                                             leftbc_in = bvp_problem.num_left_boundary_conditions,
                                             x_in = tools.farg(initial_mesh),
                                             y_in = tools.farg(solution_guess),
                                             parameters_in = tools.farg(parameter_guess),
                                             mxnsub_in = max_subintervals,
                                             node_in = bvp_problem.num_ODE)
                init_solution = Solution.from_arg_list(bvp_solverf.bvp)

        else:

            bvp_solverf.bvp.guess_3_wrap(node_in = bvp_problem.num_ODE,
                                           nparam_in = bvp_problem.num_parameters,
                                           leftbc_in = bvp_problem.num_left_boundary_conditions,
                                           x_in= tools.farg(initial_mesh),
                                           fcn = solution_guess,
                                           parameters_in = tools.farg(parameter_guess),
                                           mxnsub_in = max_subintervals)

            init_solution = Solution.from_arg_list(bvp_solverf.bvp)


    if not (method == 2 or method == 4 or method == 6 ):
        raise ValueError ("method must be either 2, 4 or 6 but got " + str(method) )

    if (tolerance < 0):
        raise ValueError("tolerance must be nonnegative")

    singular = not (singular_term is None)

    # check to see if the singular term is of the right size
    singular_term = tools.preparg(singular_term)
    if singular and not (singular_term.shape == (bvp_problem.num_ODE, bvp_problem.num_ODE)):
        raise ValueError("singular_term has the wrong shape/size. Expected: " +
                         (bvp_problem.num_ODE, bvp_problem.num_ODE)+
                         " but got :" +
                          singular_term.shape)

    # test the problem specifications with the initial solution
    bvp_problem.test(init_solution)
                                    
                                
                    
    bvp_solverf.bvp.bvp_solver_wrap(node_in = bvp_problem.num_ODE,
                                    npar_in = bvp_problem.num_parameters,
                                    leftbc_in = bvp_problem.num_left_boundary_conditions,
                                    npts_in = len(init_solution.mesh),
                                    info_in = init_solution.successIndicator,
                                    mxnsub_in = max_subintervals,
                                    x_in = tools.farg(init_solution.mesh),
                                    y_in = tools.farg(init_solution.solution),
                                    parameters_in = tools.farg(init_solution.parameters),
                                    work_in = tools.farg(init_solution.work),
                                    iwork_in = tools.farg(init_solution.iwork),
                                    fsub = bvp_problem._function,
                                    fsubp = bvp_problem._functionp,
                                    bcsub = bvp_problem._boundary_conditions,
                                    bcsubp = bvp_problem._boundary_conditionsp,

                                    singular = singular,

                                    hasdfdy = bvp_problem.has_function_derivative,
                                    dfdy = bvp_problem._function_derivative,
                                    dfdyp = bvp_problem._function_derivativep,

                                    hasdbcdy = bvp_problem.has_boundary_conditions_derivative,
                                    dbcdy = bvp_problem._boundary_conditions_derivative,
                                    dbcdyp = bvp_problem._boundary_conditions_derivativep,
                                    #optional arguments
                                    method = method,
                                    tol = tolerance,

                                    trace = trace,
                                    # we never want the actual program to shut down from the fortran side, we should throw an error
                                    stop_on_fail = False,

                                    singularterm = tools.farg(singular_term))

    calculatedSolution = Solution.from_arg_list(bvp_solverf.bvp)

    # check to see if there was a problem with the solution
    if error_on_fail and calculatedSolution._successIndicator == -1:
        raise ValueError("Boundary value problem solving failed. Run with trace = 1 or 2 for more information.")

    return calculatedSolution
Esempio n. 10
0
from Solution import Solution

s = Solution()
print s.reverse(x=321)
Esempio n. 11
0
from Solution import Solution

s = Solution()
print s.addTwoNumbers(l1=[2,4],l2=[5,6,4])
Esempio n. 12
0
def findSolution(n, matrix):
	field = Field()
	field.createField(matrix)
	print(n)
	field.printField()

	solutions = Queue()

	minSolution = None
	solution = Solution(field)
	
	greenhouses = []
	for i in range(len(field.getCoords())):
		corner1 = field.getCoords()[i]
		for j in range(i,len(field.getCoords())):
			corner2 = field.getCoords()[j]
			greenhouse = Greenhouse(corner1.x,corner2.x,corner1.y,corner2.y)
			for coord in field.getCoords():
				if greenhouse.containsCoord(coord.x, coord.y):
					greenhouse.addContainedCoordinate(coord)
			if (greenhouse.getWastedCoordinates() < 10):
				greenhouses.append(greenhouse)
			# if (corner1.y==6 and corner1.x==2 and 
				# greenhouse.getNumberOfContainedCoordinates() == 10 and
				# greenhouse.getWastedCoordinates() == 0):
				# solution = []
				# solution.append(greenhouse)
				# newSolution = Solution(field)
				# newSolution.setGreenhouses(solution)
				# print(len(greenhouses))
				# newSolution.printSolution()			
								
	sorted(greenhouses, key=Greenhouse.getWastedCoordinates, reverse=True)
	nextQueue = Queue()
			
	for i in range(1,n+1):
		print(i)
		if (not nextQueue.empty()):
			solutions = nextQueue
		else:
			solutions.put((0,[]))
		
		while(not solutions.empty()):
			# print(solutions.qsize())
			sol = solutions.get()
			index = sol[0]
			solution = sol[1]
			
			if (len(solution) == i-1):
				# nextQueue.put((0,list(solution)))
				left = None
				right = None
				top = None
				bottom = None
				for coord in field.getCoords():
					inGreenhouse = False
					for greenhouse in solution:
						inGreenhouse = inGreenhouse or greenhouse.containsCoord(coord.x,coord.y)
					if (not inGreenhouse):
						if (left == None or coord.x < left):
							left = coord.x
						if (right == None or coord.x > right):
							right = coord.x
							top = coord.y
						if (top == None or coord.y < top):
						if (bottom == None or coord.y > bottom):
							bottom = coord.y
				
				if (not left == None):
					greenhouse = Greenhouse(left,right,top,bottom)
								
					overlaps = False
					for setGreenhouse in solution:
						if (setGreenhouse.overlaps(greenhouse)):
							overlaps = True
							break
					
					if (not overlaps):
						solution.append(greenhouse)
						newSolution = Solution(field)
						newSolution.setGreenhouses(solution)
						if (minSolution == None or newSolution.computeCost() < minSolution.computeCost()):
							minSolution = newSolution
				
			else:
				for ind in range(len(greenhouses)):
					overlaps = False
					greenhouse = greenhouses[ind]
					for setGreenhouse in solution:
						if (setGreenhouse.overlaps(greenhouse)):
							overlaps = True
							break
					
					if (not overlaps):
						newSolution = list(solution)
						newSolution.append(greenhouse)
						solutions.put((ind,newSolution))
						
	minSolution.printSolution()

f = open('rectangles.txt')
wholeFile = f.read()
tasks = wholeFile.split("\n\n")
task = tasks[2]
lines = task.split("\n")
n = int(lines[0])
matrix = "\n".join(lines[1:])
findSolution(n,matrix)
Esempio n. 13
0
args = parser.parse_args()

#Initialize
req = RequestsGraph()
successLoadData = req.loadFromFileORLibrary(args.data, firstDestiny=True, dataset=args.format)
if not successLoadData:
    print('Error loading data. Exiting...')
    sys.exit(0)

R = req.numOfRequests
B = req.numOfVehicles
Solution.requestGraph = req
Solution.totalRequests = R
Solution.totalBuses = B
Solution.maxCapacity = req.capacity
Solution.initializeClass()

# Estimate superior limit for the Utility function
Solution.determineWorstCost()

# Load JSON data
evolutionLog = None
with open(args.solution, 'r') as solutionFile:
    evolutionLog = json.load(solutionFile)

# Visualize Evolution
if evolutionLog is not None:
    plt.figure()
    data = evolutionLog['log']['best']
    plt.xlabel('Iteration')
    plt.ylabel('The all best')
Esempio n. 14
0
 def randomize(self):
     for i in range(ProblemData.POPULATION_SIZE):
         self.population.append(Solution())
Esempio n. 15
0
from Solution import Solution
from Solution import ListNode
from unittest import TestCase

sol = Solution()
tc = TestCase()

head = ListNode(1,
                ListNode(2,
                         ListNode(2,
                                  ListNode(1)
                                  )
                         )
                )

tc.assertEqual(
    first=sol.isPalindrome(head=head),
    second=True,
    msg='Not Equal => Except value and Actual value'
)

head = ListNode(1,
                ListNode(2)
                )

tc.assertEqual(
    first=sol.isPalindrome(head=head),
    second=False,
    msg='Not Equal => Except value and Actual value'
)
Esempio n. 16
0
    def cross_population_OX(self, index, second_index, rand_two_vertex):
        p_path = self.population[index].get_path()
        q_path = self.population[second_index].get_path()

        r_path = [-1 for i in range(len(p_path))]
        s_path = [-1 for i in range(len(p_path))]

        for i in range(rand_two_vertex[0], rand_two_vertex[1] + 1):
            r_path[i] = q_path[i]
            s_path[i] = p_path[i]

        ################################################################################################################

        next_s_index = rand_two_vertex[1] + 1
        next_q_index = rand_two_vertex[1] + 1
        next_r_index = rand_two_vertex[1] + 1
        next_p_index = rand_two_vertex[1] + 1

        if (next_s_index == len(s_path)):
            if(rand_two_vertex[0] > 0):
                next_s_index = 0
                next_r_index = 0
                rand_two_vertex[1] = rand_two_vertex[0]
            else:
                # retarded XD
                return

        ################################################################################################################

        # fill s path from data from q path
        for i in range(next_q_index, len(s_path)):
            value = q_path[i]
            if value not in s_path:
                s_path[next_s_index] = value
                next_s_index = next_s_index + 1
                if (next_s_index == len(s_path)):
                    next_s_index = 0

        next_q_index = 0

        for i in range(next_q_index, len(s_path)):
            value = q_path[i]
            if value not in s_path:
                s_path[next_s_index] = value
                next_s_index = next_s_index + 1
                if (next_s_index == len(s_path)):
                    if (rand_two_vertex[0] > 0):
                        next_s_index = 0
                    else:
                        break

        ################################################################################################################

        # fill r path from data from p path
        for i in range(next_p_index, len(r_path)):
            value = p_path[i]
            if value not in r_path:
                r_path[next_r_index] = value
                next_r_index = next_r_index + 1
                if (next_r_index == len(r_path)):
                    next_r_index = 0

        next_p_index = 0

        for i in range(next_p_index, len(r_path)):
            value = p_path[i]
            if value not in r_path:
                r_path[next_r_index] = value
                next_r_index = next_r_index + 1
                if (next_r_index == len(r_path)):
                    if (rand_two_vertex[0] > 0):
                        next_r_index = 0
                    else:
                        break

        ################################################################################################################

        new_solution = Solution(len(r_path), create_new=False)
        new_solution.set_path(r_path)
        new_solution.set_calculated_weight(self.matrix)
        self.population.append(new_solution)

        new_solution = Solution(len(s_path), create_new=False)
        new_solution.set_path(s_path)
        new_solution.set_calculated_weight(self.matrix)
        self.population.append(new_solution)
Esempio n. 17
0
def psoVSmanual(manual_sol, best_pso_sol):
    best_solutions = []
    best_pso = Solution()
    best_pso.setValues(best_pso_sol)
    best_pso.setEval(167)
    manual = Solution()
    manual.setValues(manual_sol)
    manual.setEval(450)
    best_solutions.append(manual)
    best_solutions.append(best_pso)

    return best_solutions
Esempio n. 18
0
#! /usr/bin/env python
import sys
from Instance import Instance
from ScheduleMaker import ScheduleMaker
from Routing import Routing
from ClarkeWright import ClarkeWright
from Solution import Solution
from TwoOpt import TwoOpt


def algorithm(instance):
    valid = False
    while not valid:
        initSchedule = ScheduleMaker(instance)
        routing = Routing(instance)
        for day, scheduleDay in initSchedule.schedule.scheduleDays.items():
            cw = ClarkeWright(instance, scheduleDay)
            routing.addRoutingDay(day, cw.routingDay)
        valid = routing.isValid()
    return TwoOpt(instance, routing).routing


if __name__ == "__main__":
    args = sys.argv
    instance = Instance(args[1])
    solutionRouting = algorithm(instance)
    solution = Solution(instance, solutionRouting)
    solution.writeSolution(args[2])
Esempio n. 19
0
#!/usr/bin/python

from Solution import Solution

obj = Solution()
Esempio n. 20
0
class Case:

    def __init__(self):
        self.solution = Solution()
        return

    def case_1(self):
        city_list = []
        city_list.append(A)
        city_list.append(B)
        city_list.append(C)
        self.solution.get_route_distance(city_list)
        return self.solution.route_distance

    def case_2(self):
        city_list = []
        city_list.append(A)
        city_list.append(D)
        self.solution.get_route_distance(city_list)
        return self.solution.route_distance

    def case_3(self):
        city_list = []
        city_list.append(A)
        city_list.append(D)
        city_list.append(C)
        self.solution.get_route_distance(city_list)
        return self.solution.route_distance

    def case_4(self):
        city_list = []
        city_list.append(A)
        city_list.append(E)
        city_list.append(B)
        city_list.append(C)
        city_list.append(D)
        self.solution.get_route_distance(city_list)
        return self.solution.route_distance

    def case_5(self):
        city_list = []
        city_list.append(A)
        city_list.append(E)
        city_list.append(D)
        self.solution.get_route_distance(city_list)
        return self.solution.route_distance

    def case_6(self):
        self.solution.city_route = []
        self.solution.city_route_tmp = []
        self.solution.route_max_cnt = 3
        self.solution.get_routecnt_within_maxcnt(C, C, 3)
        return self.solution.city_route.__len__()

    def case_7(self):
        self.solution.city_route = []
        self.solution.city_route_tmp = []
        self.solution.route_max_cnt = 4
        self.solution.get_routecnt_eq_cnt(A, C, 4)
        return self.solution.city_route.__len__()

    def case_8(self):
        self.solution.get_shortest_route_btw_city(A, self.solution.city_dict)
        return self.solution.distance[C - 1]
        #get the shortest path
        # city_route_tmp = []
        # city_route_tmp.append(CITY_DIC[C])
        # pre = self.solution.pre_node[C - 1]
        # while (not pre == 0) and (not pre == A):
        #     city_route_tmp.append(CITY_DIC[pre])
        #     pre = self.solution.pre_node[pre - 1]
        # city_route_tmp.append(CITY_DIC[A])
        # # reversed the city_route_tmp to get the route
        # city_route_tmp.reverse()
        # str_route = ''
        # for i in range(0, city_route_tmp.__len__(), 1):
        #     str_route += city_route_tmp[i]
        # # print str_route

    def case_9(self):
        self.solution.get_shortest_route_btw_city(B, self.solution.city_dict)
        return self.solution.distance[B - 1]
        #get the shortest path
        # city_route_tmp = []
        # city_route_tmp.append(CITY_DIC[B])
        # pre = self.solution.pre_node[B - 1]
        # while (not pre == 0) and (not pre == B):
        #     city_route_tmp.append(CITY_DIC[pre])
        #     pre = self.solution.pre_node[pre - 1]
        # city_route_tmp.append(CITY_DIC[B])
        # # reversed the city_route_tmp to get the route
        # city_route_tmp.reverse()
        # str_route = ''
        # for i in range(0, city_route_tmp.__len__(), 1):
        #     str_route += city_route_tmp[i]
        # # print str_route

    def case_10(self):
        # init
        self.solution.city_route = []
        self.solution.city_route_tmp = []
        self.solution.route_max_distance = 30
        self.solution.get_routecnt_within_distance(C, C, 30)
        return self.solution.city_route.__len__()
Esempio n. 21
0
from Solution import Solution
from Solution import ListNode
from unittest import TestCase

sol = Solution()
tc = TestCase()

head = ListNode(1, ListNode(2, ListNode(3, ListNode(4, ListNode(5)))))

tc.assertEqual(first=str(sol.oddEvenList(head=head)),
               second=str(
                   ListNode(1,
                            ListNode(3, ListNode(5, ListNode(2,
                                                             ListNode(4)))))),
               msg='Not Equal => Except value and Actual value')

head = ListNode(
    2,
    ListNode(1, ListNode(3, ListNode(5, ListNode(6, ListNode(4,
                                                             ListNode(7)))))))

tc.assertEqual(first=str(sol.oddEvenList(head=head)),
               second=str(
                   ListNode(
                       2,
                       ListNode(
                           3,
                           ListNode(
                               6,
                               ListNode(7,
                                        ListNode(1,
Esempio n. 22
0
from Solution import Solution

s = Solution()
print s.convert(s="ab", numRows = 1)
Esempio n. 23
0
#!/usr/bin/python

from Solution import Solution
obj = Solution()

#A = [[1,2,2,3,5],[3,2,3,4,4],[2,4,5,3,1],[6,7,1,4,5],[5,1,1,2,4]]
A = [[1, 2], [4, 3]]
out = obj.pacificAtlantic(A)
print(out)
Esempio n. 24
0
 def test_solution(self):
     sol = Solution()
     self.assertEqual(True, sol.isPalindrome(121))
     self.assertEqual(False, sol.isPalindrome(-121))
     self.assertEqual(False, sol.isPalindrome(10))
     self.assertEqual(False, sol.isPalindrome(1000021))
Esempio n. 25
0
# b) 3SAT

import sys
import numpy as np
from Instance import Instance
from Solution import Solution

if __name__ == '__main__':
    # Reading args
    file = sys.argv[1]

    # Reading file
    instance = Instance()
    instance.read_file(file)
    print("Ejemplar del problema a tratar de resolver:\n", str(instance))

    # Generating random solution
    solution = Solution(instance.num_vars)
    print("Candidato a solución:\n", str(solution))

    eval = solution.eval(instance)
    if eval < instance.num_clauses:
        print("El candidato no resuelve el problema, {} de {} cláusulas son válidas.".format(eval, instance.num_clauses))
    else:
        print("El candidato resuelve el problema, todas las cláusulas son válidas")
Esempio n. 26
0
#!/usr/bin/python

from Solution import Solution

obj = Solution()

#A = '12'
#A = '226'
#A = '06'
A = '230'
out = obj.numDecodings(A)
print(out)
Esempio n. 27
0
from Solution import Solution
sol = Solution()

arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

assert (sol.spiralOrder(arr) == [1, 2, 3, 6, 9, 8, 7, 4, 5])
Esempio n. 28
0
times = [3, 5, 10, 15, 30, 60]
filenumbers = [7]
instances = [2]
Final_results = np.zeros((6, 7))
for t, T in enumerate(times):

    for f, FN in enumerate(filenumbers):

        VU = []

        for PN in instances:

            Data = Input(FN, PN)
            #Data.RandomData(40)
            MaxRunTime = T
            start, Best_Sol = GA(Data)
            Chromo.reset()

        VU.append(Best_Sol.VU)
        Final_results[t, f] = np.mean(VU)

Runtime = time.time() - start
print('Volume Utilization = %f ' % Best_Sol.VU)
print('Wieght distrbution measure= %f' % Best_Sol.WCG)
print('Distance from back measure= %f where the maximum is %f' %
      (Best_Sol.DFF, Solution.max_DFF()))
print('Run Time = %f sec' % Runtime)
print('Total number of loaded boxes = %f' % Best_Sol.Total_Box_Number(Data))
print('Total Box volume = %f Container volume = %f' % (sum(
    Data.boxes[:, 7] * Data.boxes[:, 6]), reduce(operator.mul, Data.contdim)))
Write2Excel(Best_Sol.Loading_Results)
Esempio n. 29
0
from Solution import Solution

solution = Solution()
nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]

result = solution.maxSubArray(nums)
print(result)
Esempio n. 30
0
                "black_tea": {
                    "hot_water": 300,
                    "ginger_syrup": 30,
                    "sugar_syrup": 50,
                    "tea_leaves_syrup": 30
                },
                "green_tea": {
                    "hot_water": 100,
                    "ginger_syrup": 30,
                    "sugar_syrup": 50,
                    "green_mixture": 30
                },
            }
        }
    }
    
    refill = {
        "hot_water": 500,
        "hot_milk": 500,
        "ginger_syrup": 100,
        "sugar_syrup": 100,
        "tea_leaves_syrup": 100
        }

    #create solution object
    object1 = Solution(json)
    #parse the json and provide solution
    object1.create_objects_from_json()
    #below method can be used to refill the container's ingredients
    object1.refill_beverage_machine_quantity(refill)
    
Esempio n. 31
0
#!/usr/bin/python

from Solution import Solution
obj = Solution()

#A = [[1,1,1,1,1],[1,0,0,0,1],[1,0,1,0,1],[1,0,0,0,1],[1,1,1,1,1]]
A = [[0, 1, 0], [0, 0, 0], [0, 0, 1]]
out = obj.shortestBridge(A)
print(out)
Esempio n. 32
0
 def test(self):
     self.assertTrue(Solution().isPalindrome(123321))
     self.assertTrue(Solution().isPalindrome(12321))
     self.assertTrue(Solution().isPalindrome(1))
     self.assertFalse(Solution().isPalindrome(10))
     self.assertFalse(Solution().isPalindrome(-121))
Esempio n. 33
0
from Solution import Solution


# Definition for singly-linked list.
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None


# 这个使用from Solution import Solution引入
# main方法
if __name__ == '__main__':
    slt = Solution()
    listnode1 = ListNode(2)
    listnode1.next = ListNode(4)
    listnode1.next.next = ListNode(3)
    listnode2 = ListNode(5)
    listnode2.next = ListNode(6)
    listnode2.next.next = ListNode(4)
    temp = slt.addTwoNumbers(listnode1, listnode2)
    print(temp.val, temp.next.val, temp.next.next.val)  # 7 0 8
Esempio n. 34
0
 def generate_start_population(self):
     for i in range(self.population_size):
         solution = Solution(self.matrix.get_size())
         solution.rand_path_without_duplicate()
         solution.set_calculated_weight(self.matrix)
         self.population.append(solution)
Esempio n. 35
0
#!/usr/bin/python

from Solution import Solution
obj = Solution()

out = obj.knightProbability(8, 30, 6, 4)
print(out)
Esempio n. 36
0
from Solution import Solution

trips = [[2,1,5],[3,3,7]]
capacity = 4
sol = Solution().carPooling(trips, capacity)
print(sol)
Esempio n. 37
0
    def run(self, selection="directional"):

        start_time = time()
        sol_counter = 1
        last_counter = 1
        last_timepoint = time()
        accepted = 1
        initial_dist = 0

        master = Solution(sol_id=self.dbconnection.seedId,
                          sequence=self.dbconnection.seedSequence,
                          design=self.designMethod)
        self.configureSolution(master)
        self.validateSolution(master)
        solution = master

        if not master.valid:
            raise Exception("Seed inserted is not a valid sequence!")

        self.dbconnection.DBInsertSolution(master)
        self.solutionsHash[master.solid] = master

        all_combinations_found = False

        while not all_combinations_found and sol_counter <= self.max_sol_counter:
            iteration = 0

            if time() - last_timepoint >= 60:  #Print statistics every 1 minute
                print "time elapsed: %.2f (s) \t solutions generated: %d \t rate (last min.): %0.2f sol/s  \t rate (overall): %0.2f sol/s" % (
                    (time() - start_time), sol_counter,
                    (sol_counter - last_counter) /
                    (time() - last_timepoint), sol_counter /
                    (time() - start_time))
                last_counter = sol_counter
                last_timepoint = time()

            # Retrieve some desired solution (i.e. a particular combination of features that was not yet found)
            desired_solution = self.dbconnection.DBGetDesiredSolution()

            if desired_solution == None:  #There are no more desired solutions

                if self.designMethod.listDesigns != []:  #All desired combinations were found
                    all_combinations_found = True
                    break
            else:
                initial_dist = self.distanceBetweenSolutions(
                    master, desired_solution)
                print "looking for combination: ", desired_solution[
                    'des_solution_id']
                desired_solution_id = desired_solution['des_solution_id']
            """
            parent = master
            solution = parent
            """

            #Choose stochastically a close solution to the desired one
            if choice([True, True, True, True, True, True, True, False]):
                closestSolution = self.dbconnection.DBGetClosestSolution(
                    desired_solution)
            else:
                closestSolution = self.dbconnection.DBGetClosestSolution(None)

            if closestSolution != None:
                #print "SolutionIterator: Found close sequence, starting from here..."
                if self.solutionsHash.has_key(
                        closestSolution['generated_solution_id']):
                    parent = self.solutionsHash[
                        closestSolution['generated_solution_id']]
                else:
                    parent = Solution(
                        sol_id=closestSolution['generated_solution_id'],
                        sequence=closestSolution['sequence'],
                        design=self.designMethod)
                    self.configureSolution(parent)
                    self.validateSolution(parent)

                solution = parent
            else:
                #print "SolutionIterator: Starting from master sequence"
                parent = master
                solution = parent

            found = False
            old_solution = solution

            # Sequence evolution cycle
            while not solution.checkSolution(
                    desired_solution
            ) and solution.valid and iteration != self.max_iterations and not found and not all_combinations_found:

                if solution != parent:
                    self.dbconnection.DBInsertSolution(solution)
                    self.solutionsHash[
                        solution.solid] = solution  ### Cache for rapid access
                    sol_counter += 1

                #generate next solution
                if selection == "neutral":
                    solution = choice([parent, solution])
                elif selection == "directional":
                    if self.designMethod.listDesigns != []:
                        dist_old = self.distanceBetweenSolutions(
                            old_solution, desired_solution)
                        dist_cur = self.distanceBetweenSolutions(
                            solution, desired_solution)

                        if dist_old < dist_cur:
                            solution = old_solution
                    pass
                elif selection == "temperature":
                    if self.designMethod.listDesigns != []:
                        dist_old = self.distanceBetweenSolutions(
                            old_solution, desired_solution)
                        dist_cur = self.distanceBetweenSolutions(
                            solution, desired_solution)

                        delta = dist_cur - dist_old

                        try:
                            prob = min([
                                exp(-delta /
                                    (self.temp_init *
                                     (self.temp_schedule**iteration))), 1
                            ])
                        except OverflowError:
                            prob = 0 if delta > 0 else 1

                        solution = pick_random_tuple([(old_solution, 1 - prob),
                                                      (solution, prob)])

                        if solution != old_solution and delta > 0:
                            accepted = accepted + 1

                    pass
                else:
                    #use current solution as parent for next round of mutations
                    sys.stderr.write(
                        "Selection option selected is not available, using 'directional' instead...\n"
                    )
                    selection = 'directional'
                    pass

                self.additionalConfigurationPreMutation(solution)

                old_solution = solution
                solution = solution.mutate(desired_solution)

                # No solution found
                if solution == None or solution.sequence == None:
                    solution = None
                    break

                self.configureSolution(solution)
                self.validateSolution(solution)

                self.additionalConfigurationPostMutation(solution)

                #go to next iteration
                iteration += 1

                #check if my desired solution was already found
                if self.designMethod.listDesigns != [] and iteration % (
                        self.max_iterations / 2) == 0:
                    found = self.dbconnection.DBCheckDesign(
                        desired_solution_id)

                if self.designMethod.listDesigns == []:
                    #Stops when number generated solutions is equal to the desired sample size
                    if sol_counter >= self.designMethod.nDesigns:
                        all_combinations_found = True
                        print "RandomSampling: %s solutions generated." % (
                            sol_counter)

            #insert solution in the DB
            if solution != None and solution.checkSolution(
                    desired_solution
            ) and solution != parent and solution.valid:
                print "Solution found... inserting into DB..."
                self.dbconnection.DBInsertSolution(solution,
                                                   desired_solution_id)
                self.solutionsHash[solution.solid] = solution
                sol_counter += 1
            elif found == True:
                print "Solution already found by other worker"
            else:
                if self.designMethod.listDesigns != [] and not all_combinations_found:
                    print "No solution could be found..."
                    self.dbconnection.DBChangeStatusDesiredSolution(
                        desired_solution_id, 'WAITING')

        #set worker as finished
        self.dbconnection.DBCloseConnection()

        if len(self.designMethod.listDesigns) == 1:
            print "\n###########################"
            print "# Optimized solution:"
            print "# ID: ", solution.solid
            print "# Sequence: ", solution.sequence
            print "# Scores: ", [
                feat + ": " + str(solution.scores[feat])
                for feat in self.designMethod.featuresList
            ]
            print "# Levels: ", [
                feat + "Level: " + str(solution.levels[feat + "Level"])
                for feat in self.designMethod.featuresList
            ]
            print "# Number of generated solutions: ", sol_counter
            print "# Distance to seed: ", hammingDistance(
                master.sequence, solution.sequence)
            print "###########################\n"

        print "Program finished, all combinations were found..."
        return (sol_counter, hammingDistance(master.sequence,
                                             solution.sequence), initial_dist)
Esempio n. 38
0
#req.loadFromFile("../../Data/datasets-2015-11-06-aot-tuberlin/15.2-2015-11-06.csv")
#req.loadFromFileORLibrary("../../Data/pr01-reduced", firstDestiny=True)
#req.loadFromFileORLibrary("../../Data/chairedistributique/data/darp/tabu/pr01", firstDestiny=True)
successLoadData = req.loadFromFileORLibrary(args.data, firstDestiny=True, dataset=args.format)
if not successLoadData:
    print('Error loading data. Exiting...')
    sys.exit(0)

# Attributes
R = req.numOfRequests
B = req.numOfVehicles
Solution.requestGraph = req
Solution.totalRequests = R
Solution.totalBuses = B
Solution.maxCapacity = req.capacity
Solution.initializeClass()

# Estimate superior limit for the Utility function
Solution.determineWorstCost()

# out = 0
# suc = 0
# suc2= 0
# suc3= 0
# for i in range(50):
#     Solution.prin = False
#     sol = Solution().randomize()
#     #sol = Solution(numpy.array([3343, 62164504818601, 29576]))
#     #sol = Solution(numpy.array([10228233, 1445216875758163566, 160803576754056]))
#     print(sol.getVectorRep())
#     # pdb.set_trace()
Esempio n. 39
0
from Solution import Solution
sol = Solution()

assert (sol.maxSubArray([-2, 1, -3, 4, -1, 2, 1, -5, 4]) == 6)
Esempio n. 40
0
from pygments.lexers import get_lexer_for_filename
from pygments.lexers import JavascriptLexer
from pygments.formatters import HtmlFormatter
import cStringIO


#@TODO: unhardcode input filename

inputStream = (open(sys.argv[1]) if len(sys.argv) > 1
               else open('p:/keep/projects/brickslayer.tbx'))

HTMLformat = HtmlFormatter(cssclass="source")
# print HTMLformat.get_style_defs() # dump css rules


trail = Solution()

loadBlaze = "@="
showBlaze = "@+"
hideBlaze = "@-"
snapBlaze = "@!"


def wipeout(dir):
    os.system("rm -rf %s" % dir)
    os.mkdir(dir)


mainDir = "/Users/michal/sites/javascriptgamer.com/brickslayer"
codeDir = mainDir + "/code"
Esempio n. 41
0
from Solution import Solution

s = Solution()

list = ['-91283472332', '42', '   -42', '4193 with words', 'words and 987', '-91283472332']

for d in list:
	res = s.myAtoi(d)
	pass
Esempio n. 42
0
 def __init__(self):
     self.solution = Solution()
     return
Esempio n. 43
0
 def test_solution2(self):
     sol = Solution()
     self.assertEqual(True, sol.isPalindrome(1012101))
Esempio n. 44
0
from Solution import Solution

s = Solution()
print s.myAtoi(str="  -12a42")
Esempio n. 45
0
from Genes import Genes
from Selection import Selection
from Solution import Solution
import config


genes=Genes(chromosome_character_nr=config.CHROMOSOMES['CHARACTER_NR'],
              chromosome_character_bits_nr=config.CHROMOSOMES['CHARACTER_BITS']
            )
selection=Selection(genes, 
              target=config.PROBLEM['TARGET'],
              population_nr=config.GENES['POPULATION_NR'], 
              crossover_probability=config.GENES['CROSSOVER_PROBABILITY'], 
              mutation_probability=config.GENES['MUTATION_PROBABILITY']
            )

solution=Solution(config.PROBLEM,
                  genes, 
                  selection, 
                  nr_of_generations=config.GENERATIONS['NUMBER']
                  )
solution.compute()
solution.save()


print '-------------'
print 'Done'
print 'BEST GENERATION TOTAL FITNESS SCORE : %s '  % str(solution.best_fitness_score)
print '-------------'