如何找到同一条直线上的最大点数

时间:2018-11-06 12:15:10

标签: javascript

我想实现一个函数,该函数需要一个点数组并返回一行上的最大点数。

示例。

@app.route('/downloadxlsx', methods=['POST'])
def downloadOrderToExcel():
  try:
    data = request.get_json()
    productsBought = data.pop('products')
    data['datetime'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')

    output = io.BytesIO()
    wb = xlsxwriter.Workbook(output, {'in_memory': True})
    ws = wb.add_worksheet(data['fullname'])
    row = col = 0
    for columnName in excelColumnNames():
      ws.write(row, col, columnName)
      col += 1
    col = 0
    row = 1
    for cellValue in data:
      ws.write(row, col, data[cellValue])
      col += 1
    for product in productsBought:
      result = queryForProducts(product)
      for r in result:
        ws.write(row, col, r['categoryname'] + " pack of " + r['pack'])
        row += 1

    output.seek(0)
    wb.close()
    return send_file(output, as_attachment=True, attachment_filename='order.xlsx')
  except Exception as ex:
    print(str(ex))
    return 'False'

1 个答案:

答案 0 :(得分:0)

您可以采用蛮力方法收集成对的点及其斜率/截距。

然后获得所收集集合的最大大小。

这种方法是二次方的,而不是以前的三次方。

function getAB([x1, y1], [x2, y2]) { // slope/intercept of y = ax + b
    var a;
    return x1 === x2
        ? [Infinity, x1]
        : [a = (y2 - y1) / (x2 - x1), y1 - a * x1];
}

var points = [[1, 1], [3, 2], [5, 3], [4, 1], [2, 3], [1, 4]],
    collection = {},
    usedPoints = new Set;

points.forEach((p1, i, a) => {
    if (usedPoints.has(p1.toString())) return;
    a.slice(i + 1).forEach((p2, j, b) => {
        if (usedPoints.has(p2.toString())) return;
        var key = JSON.stringify(getAB(p1, p2));
        collection[key] = collection[key] || new Set;
        collection[key].add(p1);
        collection[key].add(p2);
        usedPoints.add(p1.toString());
    });
});

console.log(Math.max(...Object.values(collection).map(s => s.size)));

console.log(Object.entries(collection).map(([k, v]) => [k, [...v].map(w => w.join(' '))]));
.as-console-wrapper { max-height: 100% !important; top: 0; }

相关问题