Avicenna

joined 1 month ago
[–] Avicenna@programming.dev 5 points 2 weeks ago

Once you become a monopoly on such global scale, you can start screwing your customers for much higher profits and keep going like this for a decade. Your chokehold on the business ensures compatitors can't arise very quickly.

[–] Avicenna@programming.dev 1 points 2 weeks ago

Money also doesn't help if you surround your self with idiots, look at how Steve Jobs went even after stealing a liver from someone after having wrecked his by rejecting treatment for his curable cancer.

[–] Avicenna@programming.dev 4 points 2 weeks ago (1 children)

This is the only one that actually looks like a vampire:

Most others look like sexual fantasies with a hint of vampirism

[–] Avicenna@programming.dev 6 points 2 weeks ago

They should have brought Putin's blanket of shame

[–] Avicenna@programming.dev 13 points 2 weeks ago

someone is overly excited for a million dollar company

[–] Avicenna@programming.dev 2 points 2 weeks ago* (last edited 2 weeks ago) (3 children)

Yes I used a polygon library so what... I did eyeball the shape and guessed what the result should have been like but still more pleasing to write something that applies generally. Although I did put an area threshold (eyeballed) which subsets the corners to test, it only reduces run time to about 1/2 (from ~10s to ~5s) so that is not necessarily very critical. If I hadn't used this library, I would probably do sth along the lines of defining my own rectangle classes with unions, intersections etc so wouldn't be a more clever approach but much more time consuming.

from pathlib import Path

import numpy as np
import shapely

cwd = Path(__file__).parent

def parse_input(file_path):
  with file_path.open("r") as fp:
    data = list(map(lambda x: list(map(int,x.split(','))), fp.readlines()))

  return np.array(data)


def construct_shapes(coordinates, threshold):

  Itriu = np.triu_indices(coordinates.shape[0], k=2)
  squares = []

  for i0,i1 in zip(*Itriu):

    c0 = tuple(coordinates[i0,:])
    c1 = tuple(coordinates[i1,:])
    area = np.prod(abs(np.array(c0) - np.array(c1)) + np.array([1,1]))

    if area>threshold:
      c2 = (c0[0],c1[1])
      c3 = (c1[0],c0[1])
      squares.append(shapely.Polygon((c0,c3,c1,c2)))

  polygon = shapely.Polygon(coordinates)

  return polygon, squares


def solve_problem(file_name, redgreen=False, threshold=0):

  coordinates = parse_input(Path(cwd, file_name))

  if not redgreen:
    areas = np.prod(abs(coordinates[None,:] - coordinates[:,None]) +\
                    np.array([1,1])[None,None,:], axis=-1)
    max_area = np.max(areas)

  else:
    polygon, squares = construct_shapes(coordinates, threshold)
    max_area = -np.inf

    for inds,square in enumerate(squares):
      if square.area==0:
        continue

      if polygon.contains(square):
        c = np.array(list(zip(*square.exterior.coords.xy)))
        if (a:=np.prod(abs(c[0] - c[2]) + np.array([1,1])))>max_area:
          max_area = a

  return int(max_area)



if __name__ == "__main__":

  assert solve_problem("test_input") == 50
  assert solve_problem("input") == 4763509452
  assert solve_problem("test_input", True, 1) == 24
  assert solve_problem("input", True, 15000*80000) == 1516897893 # threshold by eyeballing the shape
[–] Avicenna@programming.dev 3 points 2 weeks ago* (last edited 2 weeks ago)

I went here for graphs (to find connected components) and binary search (for efficiency)

#!/usr/bin/env python3
from pathlib import Path

import numpy as np
import networkx as nx

cwd = Path(__file__).parent.resolve()


def parse_input(file_path):
  with file_path.open("r") as fp:
    coords = list(map(lambda x: list(map(int, x.split(','))), fp.readlines()))

  return np.array(coords)


def binary_search(G, dist):

  Itriu = np.triu_indices(dist.shape[0], k=1)
  dist = dist[Itriu]

  components = list(nx.connected_components(G))
  Isort = [(Itriu[0][i], Itriu[1][i]) for i in np.argsort(dist)]

  icurrent =  0
  ihist = []
  nhist =  []

  while len(ihist)<2 or ihist[-1]!=ihist[-2]:

    ihist.append(icurrent)
    G.add_edges_from(Isort[:icurrent])
    components = list(nx.connected_components(G))
    nhist.append(len(components))

    G.remove_edges_from(Isort[:icurrent])

    if len(components)>1:
      # if >1 component, go between this and closest next index with 1 component
      I = [ind for ind,n in enumerate(nhist) if n==1]

      if len(I)==0:
        inext = len(Isort)
      else:
        inext = min(np.array(ihist)[I])

      icurrent = icurrent + int(np.ceil((inext-icurrent)/2))

    else: 
      # if 1 component, go between nearest previous >1 components and this index
      I = [ind for ind,n in enumerate(nhist) if n>1]

      if len(I)==0:
        iprev = 0
      else:
        iprev = max(np.array(ihist)[I])

      icurrent = iprev + int(np.ceil((icurrent-iprev)/2))

  return Isort[icurrent-1]


def solve_problem(file_name, nconnect):

  coordinates = parse_input(Path(cwd, file_name))
  G = nx.Graph()
  G.add_nodes_from(range(coordinates.shape[0]))

  dist = np.sqrt(np.sum((coordinates[None,:] - coordinates[:,None])**2,
                        axis=-1))

  if nconnect != -1: # part 1
    Itriu = np.triu_indices(dist.shape[0], k=1)
    dist = dist[Itriu]
    Isort = [(Itriu[0][i], Itriu[1][i]) for i in np.argsort(dist)[:nconnect]]

    G.add_edges_from(Isort)
    components = sorted(list(nx.connected_components(G)), key=len)[::-1]

    return np.prod(list(map(len, components[:3])))
  else: # part 2
    indices = binary_search(G, dist)
    return np.prod(coordinates[indices,:],axis=0)[0]


if __name__ == "__main__":

  assert solve_problem("test_input", 10) == 40
  assert solve_problem("input", 1000) == 115885
  assert solve_problem("test_input", -1) == 25272
  assert solve_problem("input", -1) == 274150525

[–] Avicenna@programming.dev 2 points 3 weeks ago

I went for recursion (and a simple graph node class) but my favourite solution is transfer matrices one that I have seen some people do


from pathlib import Path
import numpy as np
import itertools as it

cwd = Path(__file__).parent


def parse_input(file_path):
  with file_path.open("r") as fp:
    data = list(map(str.strip, fp.readlines()))

  return np.array([list(row) for row in data], dtype=object)


class Node:

  def __init__(self, symbol, row, col):
    self.symbol = symbol
    self.loc = tuple([row, col])
    self.parents = []
    self.npaths_to_start = -1

  @property
  def is_connected(self):
    return self.symbol=='S' or len(self.parents)>0

  def connect(self, node_dict, s0, s1):

    if self.loc[0]==0:
      return

    top = node_dict[self.loc[0]-1, self.loc[1]]

    if top.symbol in ['.','S'] and top.is_connected:
      self.parents.append(top)

    if self.symbol=='^' and top.is_connected:
      left =  node_dict[self.loc[0], self.loc[1]-1]
      right =  node_dict[self.loc[0], self.loc[1]+1]

      left.parents.append(self)
      right.parents.append(self)


def count_paths_to_start(node0, node1):
  '''
  node0 should always be the start node else
  result is meaningless
  '''

  if node0 in node1.parents:
    return 1
  else:
    npaths = 0
    for p in node1.parents:
      if p.npaths_to_start != -1:
        npaths += p.npaths_to_start
      else:
        p.npaths_to_start = count_paths_to_start(node0, p)
        npaths += p.npaths_to_start

    return npaths


def solve_problem(file_name, quantum=False):

  grid = parse_input(Path(cwd, file_name))
  s0,s1 = grid.shape

  node_dict = {(i,j):Node(grid[i,j], i, j) for i,j in
               it.product(range(s0), range(s1))}
  [node.connect(node_dict, s0, s1) for node in node_dict.values()]

  if not quantum:
    return len([x for x in node_dict.values() if x.symbol == '^' and
                x.is_connected>0])
  else:
    start_ind = [(0, j) for j in range(s1) if node_dict[0,j].symbol=='S'][0]

    return\
      sum([count_paths_to_start(node_dict[start_ind], node_dict[s0-1, j]) for
           j in range(s1) if node_dict[s0-1,j].is_connected])



if __name__ == "__main__":

  assert solve_problem("test_input") == 21
  assert solve_problem("input") == 1633
  assert solve_problem("test_input", True) == 40
  assert solve_problem("input", True) == 34339203133559
[–] Avicenna@programming.dev 2 points 3 weeks ago

thanks in that case yea bad luck, glad he was in a cage

[–] Avicenna@programming.dev 1 points 3 weeks ago* (last edited 3 weeks ago) (2 children)

I was more like why is the guy there. Because I don't know the answer can't make a definitive judgement on the case. If it was just to watch a bear struggle with a cage yea fuck that. If it was to document something that is undocumentable in any other way, that is more respectable.

[–] Avicenna@programming.dev 5 points 3 weeks ago (4 children)

I don't know, that bear just wasted quite a bit of energy in an environment where it really matters.

view more: ‹ prev next ›