目录
两点能创建一条直线,多个点能创建几条直线
#include<iostream>
#include<map>
#include<set>
struct point {
int x, y;
point(int a, int b)
{
x = a;
y = b;
}
point() { x = 0; y = 0; }
};
void test_point2line(int xrange, int yrange)
{
// 存储点
std::vector<point> p;
for (int i = 0; i < xrange; i++)
{
for (int j = 0; j < yrange; j++)
{
p.push_back({ i,j });
}
}
// 直线存储
std::set<std::pair<double, double>> lines;
// 每2个点创建直线
for (int i = 0; i < p.size(); ++i)
{
for (int j = 0; j < p.size(); ++j)
{
if (p[i].x != p[j].x && p[i].y != p[j].y)
{
// k = (y2-y1)/(x2-x1)
double k = (double)(p[j].y - p[i].y) / (p[j].x - p[i].x);
// b = y - kx = y - x(y2-y1)/(x2-x1)
double b = (p[j].y * (p[j].x - p[i].x) - (p[j].y - p[i].y) * p[j].x) * 1.0 / (p[j].x - p[i].x);
// y=kx+b:斜率k和常熟b就表示一条直线
lines.insert(std::pair(k, b));
}
}
}
// 加上 (y = b), kx = 0 , 这些线(k=0,k=1)时的情况
std::cout << lines.size() + xrange + yrange << std::endl;
}
set支持std::pair<>类型的对象的去重
std::set<std::pair<double,double>>
// 检查直线是否重复
int removeRepeated(std::multimap<double, double>& lines)
{
std::set<std::pair<double, double>> newSet;
//std::multimap<double, double> newMap;
for (auto it:lines)
{
// 使用set去重,没想到能支持piar<key,value>的对象,key和value都能去重
newSet.insert(std::make_pair(it.first,it.second));
//newMap.insert(std::make_pair(it.first,it.second));
}
return newSet.size();
}
结果:
std::multimap按value排序
例如: std::multimap<double,double>排序
// multimap按value值排序,但是很耗空间
void SortMap(std::multimap<double, double>& lines)
{
std::multimap<double, double> newMap;
for (auto it : lines)
{
// key和value反着插入到新map中,得出根据value排序的结果
newMap.insert(std::make_pair(it.second, it.first));
}
std::multimap<double, double>().swap(lines);//清空
for (auto it2:newMap)
{
// key和value插回
lines.insert(std::make_pair(it2.second,it2.first));
}
}
int/int时*1.0 或 (double)int/int 来保证结果正确
double k = (double)(6 - 2) / (4 - 1);
double k1 = 1.0 * (6 - 2) / (4 - 1);
double k2 = (6 - 2) / (4 - 1);