Artificial intelligence: assuming an infinite amount of computing resources, would the minmax algorithm always win in chess?

The minmax algorithm is a popular strategy used to design chess engines. In general, given that the chess state space is huge, we choose a fixed depth and evaluate the game tree up to that level, and select the best sequence of movements so far.

Let's suppose that we eliminate this limit and look for the whole tree. Would this technique always win? If the answer is no, would you ever lose? (Then, would you only win + draw, or would you also lose?)

A good answer would include the theoretical foundations of why or why not, this would work, both from the theoretical aspects of the game of chess and from the properties of the minmax algorithm.

Computational geometry: algorithm to decompose a complex polygon (auto-intersection) in simple polygons

I've been trying to write a Bentley-Ottmann Sweepline algorithm to transform an auto-intersection (complex) into a set of simple polygons.

There are some instructions on this page (see the heading titled "Decompose into simple pieces"), however, my current implementation is falling short (see img below).

Current result

While I can find all auto-intersection points, I can not build the desired outputs when there are multiple auto-intersections in a single segment.

I am struggling to find any other article that describes the process or data structures required in more detail. The blog post makes reference to a linked list that could mean a list of Doubly Connected's Edge although I'm not 100% sure, the other challenge is that I do not think there is an adequate implementation of that data structure.

Any advice on how you could reconstruct the desired result would be appreciated.

Algorithm to select seedbox to put torrent in

Which algorithm would be best to decide which seed box should each torrent continue? It should be able to fit the torrents into the minimum number of seedboxes, but also maximize the free space in each seedbox and match the number of torrents per seedbox. There may be other requirements for this application that I do not have fucking thought of yet

My current data set is 8.9TB on 154 torrents, but both numbers will grow. My current seedboxes may contain 455GB, but this will probably change in the future. 8.9TB / 455GB = 20 minimum seedboxes and 154/20 = about 8 torrents per box, for my current dataset and seedboxes.

My first attempt was to go through the list of torrents from highest to lowest. If the current torrent would fit in the current seedbox, put it there and remove it from the list, then move on to the next torrent. Once the full list of torrents was walked, move on to the next seed box, starting the list of remaining torrents from the largest remaining.

This resulted in 20 seeds (the optimal solution), but I found two different problems:

  1. I underestimated the overhead in each seed box. Since I put as many torrents as I could in each one, box 1 ran out of space. I solved this by moving a 4GB torrent to box 19, but it would be nice if the new algorithm did a better job of propagating free space.

  2. I ended up with three torrents in frame 0 (and eventually frame 1), and 51 torrents (eventually 52) in frame 19. The CPU / memory utilization in a seedbox is proportional to the number of torrents, regardless of the size of each torrent This means that box 19 is doing 17 times more work than box 0. It would be nice if the new algorithm kept the amount of torrents per box of seeds relatively constant.

My subsequent attempts REALLY are not worth discussing.

A CPAN module that is already implementing the algorithm would be incredible (yes, to the right). If you want to play with live data, you can find a list of the current torrent sizes at https://freerainbowtables.com/torrents.txt

Thank you.

logarithms: What is the smallest value of n, so that an algorithm running at 100 * n ^ 2 works faster than 2 ^ n? [How to figure out without brute force]

Well, then I needed to find the smallest value of n, so that the algorithm 100 * n ^ 2 is faster than 2 ^ n.

[what I have tried]

Then, I instantly thought & # 39; 0 & # 39 ;. But then I realized that it can not be 0, 0 implies that you are not entering digits in the algorithm, it also implies that the program does not run or end.

I wrote 2 ^ 32 and got a number of more than 4 billion. Well, this is good, I'm finding numbers that have 100 * n ^ 2 being faster than 2 ^ n.

I reduced by half that, n = 20.

I continued inserting values ​​in the countdown until I reached n = 15.

I also counted from n = 10, the answer is definitely n = 15, but I have a problem. . . I solved this using brute force and that is not good. What if they gave me a larger number and a greater number of numbers?

[What I need]

I need a way to find the value instantaneously just doing the calculations, I tried to use logarithms, but my answer was incorrect, my knowledge of the records is a bit rusty and I need a little help.

Think of it as a student trying to solve a question on a SAT or having a timer for a test.

Algorithm of transfer from Java to Python

I have ported Stempel stemmer in Java (Apache Lucene) to Python. I come from the Java world, so I'm afraid my translation might not be "python" enough.

I would like to hear your comments on a fairly representative part of the code, the translation of Difference class that applies the derivation command (dif) to a chain (destination).

    @classmethod
def apply (cls, dest, diff):
""
Apply the patch string difference given to the given destination string.
: param dest: target string
: param diff: Patch string
:he came back:
""
if diff is None:
he came back
If it is not isinstance (dest, MutableString):
raise ValueError
if it is not dest
he came back

pos = len (dest) - 1
try:
for i in range (int (len (diff) / 2)):
cmd = diff[2 * i]
            param = diff[2 * i + 1]
            par_num = ord (param) - ord (& # 39; a & # 39;) + 1
yes cmd == & # 39; - & # 39 ;:
pos - = (par_num - 1)
elif cmd == & # 39; R & # 39 ;:
cls .__ check_index (dest, pos)
destination[pos] = param
elif cmd == & # 39; D & # 39 ;:
o = pos
pos - = (par_num - 1)
cls .__ check_index (dest, pos)
destination[pos:o + 1] = & # 39; & # 39;
elif cmd == & # 39; I & # 39 ;:
pos + = 1
cls .__ check_offset (dest, pos)
dest.insert (pos, param)
pos - = 1
except IndexError:
# swallow, the same happens in the original version of Java
happen

@classmethod
def __check_index (cls, s, index):
if the index < 0 or index >= len (s):
raise IndexError

@classmethod
def __check_offset (cls, s, offset):
yes compensated < 0 or offset > lens):
raise IndexError

Some justifications for the decisions I made:

  • The original implementation uses. StringBuffer to manipulate the characters in a string. From Python str The type is immutable. I used my own class. MutableString that behaves like a python list.

  • In addition, the original logic was based on the capture IndexOutOfBoundsException. Unlike Java, Python allows negative indexes in a list and list ranges. Therefore, I have introduced guards as __check_X.

  • The Java implementation uses the switch / case / default clause. I translated it to the if / elif / else clause in Python.

Python integer multiplication algorithm of Karatsuba

This code is not passing all the test cases, can anyone help? I just pass the direct test and then lose precision.

import mathematics
import unittest


IntegerMultiplier class:

def multiplies (yo, x, y):
if x <10 o and <10:
returns x * y

x = str (x)
y = str (y)

m_max = min (len (x), len (y))
x = x.rjust (m_max, & # 39; 0 & # 39;)
y = y.rjust (m_max, & # 39; 0 & # 39;)

m = math.floor (m_max / 2)

x_high = int (x[:m])
x_low = int (x[m:])

y_high = int (and[:m])
y_low = int (and[m:])

z1 = self.multiply (x_high, y_high)
z2 = self.multiply (x_low, y_low)
z3 = self.multiply ((x_low + x_high), (y_low + y_high))
z4 = z3 - z1 - z2

returns z1 * (10 ** m_max) + z4 * (10 ** m) + z2


TestIntegerMultiplier class (unittest.TestCase):

def test_normal_cases (self):
intergerMultiplier = IntegerMultiplier ()

case1 = intergerMultiplier.multiply (1234, 5678)
self.assertEqual (case1, 7006652)

yes __name__ == & # 39; __ main __ & # 39;
unittest.main ()
`` `

Machine learning: what is the official name of a specific type of combination algorithm?

Let's say I have the following set of variables:

[A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z]

The values ​​represent a list of variables in a data set. Each variable has a certain level of correlation with the objective variable. $. The correlation increases or decreases depending on the type of combination you use against your goal $. For example, BCJX could have a greater correlation with $ what OQTVW. I will test every possible combination with the training algorithm and show it all, with its precision score, in a concise CSV file. But I do not know the name of the algorithm that could combine these variables in all possible ways.

In other words, I want to find the combination with the highest correlation value and the smallest dimension.

How to express the data structure in the pesudocode of your algorithm

If I stored the output of my algorithm as a data structure as an array of cells. How can I express that when I'm writing the pseudocode for my algorithm?

For example, I have a set of $ n $ values ​​like {2,4,6} and for each value, I run the algorithm and print an array.

I want to express in the pseudocode of my algorithm how I stored the matrix for each value and produce these values ​​and the corresponding matrices.

Performance – Triangle of numbers Maximum path – Greedy algorithm Python

A road number triangle maximized using a greedy algorithm. It is not the most efficient way, since I am a beginner, this is the best I can do.
I need your comments on how to improve it in terms of maximizing the total. It works in a way that chooses the highest value of the adjacent numbers in the next row. Without brute force (could take an eternity with large numbers). I also included many functions that do different things (check the documentation strings), how to make a size triangle, read a triangle from a file … I want your comments on how to improve things in terms of optimization / style ….

from the time of import
import randomly


def make_row (n, not_str = False):
"" "Makes a row of size n; not_str = True to return integers.
Returns a list containing the row, if not_str = True, a list of strings (numbers) is returned. "" "
temp = []
    for i in the range (n):
yes no_str:
temp.append ((random.randint (10, 99)))
plus:
temp.append (str (random.randint (10, 99)))
return temperature


def make_triangle (n, not_str = False):
"" "Make a triangle of numbers of size n.
Returns triangle, a list of lists (rows); if not_str = True, a list of strings is returned otherwise: integer. "" "
triangle = []
    for i in rank (1, n + 1):
yes no_str:
temp = make_row (i, not_str)
triangle.append (temp)
plus:
temp = make_row (i)
triangle.append (temp)
return triangle


def save_triangle (n, file name):
"" "Assumes that the file name is a string (name of the file) and n the size of the triangle to be made.
Type triangle in & # 39; file name & # 39; "" "
triangle = make_triangle (n)
triangle_file = open (file name, & # 39; a + & # 39;)
for the row in triangle:
row = & # 39; & # 39 ;. join (row)
triangle_file.writelines (row + & # 39;  n & # 39;)
triangle_file.close ()


def triangle_to_list (triangle, p = False):
"" "Assumes that the triangle is a list or a string and p = True to print the triangle.
Returns a list of lists (rows) that contain integers. "" "
# If the triangle is not a list (for example, a .txt file or string, clean new lines and spaces).
If it is not an instance (triangle, list):
rows = triangle.split (& # 39;  n & # 39;)
# If p, print the triangle of numbers and size.
Yep:
print (f & # 39; Triangle size {len (rows)} & # 39;)
Print()
for rw in rows:
print (& # 39; & # 39; join (rw))
# Clean spaces
while & # 39; & # 39; in rows:
rows.remove (& # 39; & # 39;)
row_nums = [x.split(' ') for x in rows]
        all_rows = []
        # Convert strings to integers.
for the row in row_nums:
temp = []
            for num in row:
temp.append (int (num))
all_rows.append (temp)
# Returns a list of integers.
back all_rows
# If the triangle is produced using make_triangle, it is a list.
If it is an instance (triangle, list):
rows = triangle
# If p, print the triangle of numbers and size.
Yep:
print (f & # 39; Triangle size {len (rows)} & # 39;)
Print()
# Convert from integers to strings to print using .join ().
list_of_strings_to_print = []
            for row in rows:
temp = []
                for the number in the row:
temp.append (str (number))
list_of_strings_to_print.append (temp)
for the row in list_of_strings_to_print:
print (& # 39; & # 39; .join (row))
Print()
# Returns a list of integers.
return rows


def triangle_file_list (file name, p = False):
"" "Assumes that & # 39; file name & # 39; contains a triangle of numbers (strings), p = True to print. Returns a list of lists (rows) containing integers." ""
with open (file name, & # 39; r & # 39;) as tri:
triangle_file = tri.read ()
#
Yep:
print (triangle_file)
raw_triangle = & # 39; & # 39; .join (triangle_file)
return triangle_to_list (raw_triangle)


def maxim_path (rows, p = False):
"" "Assumes that the rows are a list of lists that contain all the rows and p = True to print the route.
Returns the total of the maximum route.
""
start = 0
total = 0
# This list contains the number, the index in the row (to avoid calculation errors in the case of row duplicates), the next number).
Choice combinations = []
    while I start < len(rows) - 1:
        for index, number in enumerate(rows[start]):
            next_max = (max(rows[start + 1][index], rows[start + 1][index + 1]))
            if next_max == rows[start + 1][index]:
                choice_combinations.append((number, index, next_max))
            if next_max == rows[start + 1][index + 1]:
                choice_combinations.append((number, index + 1, next_max))
        start += 1
    final_choices = [choice_combinations[0]]
    for number, index, next_number in choice_combinations[1:]:
        # Performing 2 checks: check by number and check by index.
        if number == final_choices[-1][-1] and any((index == final_choices[-1][1], final_choices[-1][1] == index - 1)):
            final_choices.append((number, index, next_number))
    for item in final_choices:
        total += item[0]
    total += final_choices[-1][-1]
    # If p, print the maximum path, sum.
    if p:
        print('Maximum path:')
        for item in final_choices:
            print(f'{item[0]} --> & # 39 ;, end = & # 39; & # 39;)
print (final_choices[-1][-1])
Print()
print (f & # 39; Maximum sum: {total} & # 39;)
total return


def test_triangles (n, one = False):
"" "Assumes that n is the maximum size of the triangles to print, prints n triangles, n routes, n sums, n times.
If one = True, print only one triangle of size n. "" "
time_all = time ()
Yes one:
time1 = time ()
tr = make_triangle (n, True)
rws = triangle_to_list (tr, True)
Maximize the route (rws, True)
Print()
print (f & # 39; Total time: {time () - time_all} seconds. & # 39;)
plus:
for i in range (2, n + 1):
time1 = time ()
tr = make_triangle (i, True)
rws = triangle_to_list (tr, True)
Maximize the route (rws, True)
Print()
print (f & # 39; Time taken: {time () - time1} seconds. & # 39;)
Print()
print (f & # 39; Total time: {time () - time_all} seconds & # 39;)


yes __name__ == & # 39; __ main __ & # 39;
test_triangles (20, True)

python – Kruskals MST Algorithm

This code calculates the minimum spanning tree of a given graph using the Kruskals algorithm.

It works correctly and I have provided test cases within the code.

I would like to receive comments on the efficiency of the code (Choice of ds and functions / size of the function) and anything else to improve the code (Apart from compliance with pep 8, that's something I'll work on to fix it soon)

Thank you

Class graphic:

def __init __ (self):

self.graph = []
    self.edges = []
    self.parents = {}
self.size = {}

def addnode (self, key1, key2, edge = 0):

if key1 is not in self.graph:
self.graph.append (key1)
if key2 is not in self.graph:
self.graph.append (key2)

self.edges.append ([key1, key2, edge])

def getparent (self, vertex):

while the parents[vertex] ! = -1:
vertex = self.parents[vertex]

    return vertex


definitive union (I, vertex, neighbor):

x_par = self.getparent (vertex)
y_par = self.getparent (neighbor)
yes auto size[x_par] <= self.size[y_par]:
own parents[x_par] = y_par
own size[y_par] + = own size[x_par]
    plus:
own parents[y_par] = x_par
own size[x_par] + = own size[y_par]

  def kruskal (self):

mst = []
    total = 0

for the key in self.graph:
own parents[key] = -1
own size[key] = 1

self.edges.sort (key = lambda x: x[2])

by the edge in itself.
vertex, neighbor, weight_edge = edge
x_par = self.getparent (vertex)
y_par = self.getparent (neighbor)
yes x_par! = y_par:
self.union (x_par, y_par)
mst.append (border)
total + = weight_edge

print (mst)
Printing (& must; Weight: & # 39 ;, total)

yes __name__ == & # 39; __ main __ & # 39;
g = Graphic ()
g.addnode (0, 1, 10)
g.addnode (0, 2, 6)
g.addnode (0, 3, 5)
g.addnode (1, 3, 15)
g.addnode (2, 3, 4)
g.kruskal ()