我必须阅读包含以下内容的文件:people.txt
class Person {
String name;
String sex;
}
我想拆分此文件的内容并将其保存到人员列表(// compute X/ai sum
long long summarize(long long ar[], long long n, long long X)
{
long long sum = 0;
for (long long i = 0; i < n; i++)
{
sum += X/ar[i];
}
return sum;
}
bool get_range(long long ar[], int n, int m, pair<long long, long long>& range)
{
long long sum = 0;
long long x;
// reduce range
while (range.first < range.second)
{
x = (range.first + range.second) / 2;
sum = summarize(ar, n, x);
if (sum < m)
{
range.first = x + 1;
}
else if (sum > m)
{
range.second = x;
}
else if (x == range.first)
{
return true; // single element
}
else
{
break;
}
}
if (sum != m)
{
return false;
}
// check surroundings for lower / upper bound.
sum = summarize(ar, n, range.first);
if (sum != m)
{
auto r1 = make_pair(range.first + 1, x);
if (get_range(ar, n, m, r1))
{
range.first = r1.first;
}
else
{
range.first = x;
}
}
sum = summarize(ar, n, range.second - 1);
if (sum != m)
{
auto r2 = make_pair(x + 1, range.second - 1);
if (get_range(ar, n, m, r2))
{
range.second = r2.second;
}
else
{
range.second = x + 1;
}
}
return true;
}
int main()
{
int n, m;
cin >> n >> m;
long long *ar = new long long[n];
long long ar_min = LLONG_MAX;
for(long long i = 0; i < n; i++)
{
cin >> ar[i];
ar_min = min(ar[i], ar_min);
}
// initial range of possible X values
auto range = make_pair(m / (ar_min * n), m * ar_min);
if (get_range(ar, n, m, range))
{
cout << (range.second - range.first) << endl;
}
else
{
cout << 0 << endl;
}
}
),其中只需要设置名称和性别字段。
get_range
如何使用Java 8实现这一目标?
答案 0 :(得分:3)
Files.lines(Paths.get("/your/path/here"))
.map(line -> line.split("\\s*\\|\\s*"))
.map(array -> new Person(array[0], array[2]))
.collect(Collectors.toList);
我没有编译过这个,但应该完成这项工作。
答案 1 :(得分:3)
假设每个人都在新的一行:
Files.lines(Paths.get("people.txt"))
.skip(1) // skip the header
.map(Person::new)
.collect(toList());
应该有一个构造函数从String
构造一个Person
实例:
public Person(String s) {
String[] values = s.split("\\|");
// validate values.length and set values trimming them first
}
如果只设置特定字段,您最好先写一个静态工厂方法(如Person::createFromFileRow
)。