我有一组代表我所拥有的值的范围 添加新范围时,可能会删除范围之间的间隔。
例:
我有范围getline
,#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *get_input();
char *get_input_scanf();
int main (void) {
char *line = NULL;
printf ("\nEnter input below, [ctrl+d] to quit\n");
for (;;)
{
printf ("\n input: ");
line = get_input();
if (line)
printf (" value: '%s'\n", line);
else {
printf ("\n value: [ctrl+d] received\n");
break;
}
free (line);
line = NULL;
}
if (line) free (line);
printf ("\n");
line = NULL;
printf ("\nEnter input below to read with get_input_scanf\n\n input: ");
line = get_input_scanf();
if (line) {
printf (" value: '%s'\n", line);
free (line);
}
return 0;
}
char *get_input()
{
char *ln = NULL; /* line buffer, NULL - getline allocates */
size_t n = 0; /* initial , 0 - getline decides*/
ssize_t nchr = 0;
if ((nchr = getline (&ln, &n, stdin)) != -1)
{
/* strip newline or carriage rtn */
while (nchr > 0 && (ln[nchr-1] == '\n' || ln[nchr-1] == '\r'))
ln[--nchr] = 0;
/* if (!nchr) { // do not accept blank lines
free (ln);
return NULL;
} */
char *input = strdup (ln); /* duplicate ln in input */
free (ln); /* free getline allocated mem */
return input;
}
return NULL;
}
char *get_input_scanf()
{
char *ln = NULL;
scanf ("%m[^\n]%*c", &ln);
return ln;
}
,$ ./bin/getline_getinput
Enter input below, [ctrl+d] to quit
input: some string of input.
value: 'some string of input.'
input: another string that can be any length ........ ........
value: 'another string that can be any length ........ ........'
input:
value: ''
input: a
value: 'a'
input:
value: [ctrl+d] received
Enter input below to read with get_input_scanf
input: some input to show scanf will allocate dynamically as well!
value: 'some input to show scanf will allocate dynamically as well!'
,其中数据保存在两个列表中:
[10, 50]
(10,70,150)&amp; [70, 100]
(50,100,200)。
以下是我可能通过预期输出获得的4种不同输入:
[150, 200]
结果应为start_list
,因为已添加所有间隔。 end_list
结果应为[20, 170]
,因为已添加所有间隔。 [10, 200]
结果应为[5, 170]
,因为已添加所有间隔。 [5, 200]
结果应为[20, 220]
,[10, 220]
,因为已添加了一些时间间隔。 但是,我似乎无法使用此方法。任何人都可以帮我解决这个问题吗?我无法使条件正确。
答案 0 :(得分:0)
你可以用番石榴来解决这个问题。
RangeSet<Integer> r = TreeRangeSet.create();
r.add(Range.closed(10, 50));
r.add(Range.closed(70, 100));
r.add(Range.closed(150, 200));
// adds
r.add(Range.closed(20, 170));
// r.add(Range.closed(5, 170));
// r.add(Range.closed(20, 220));
// r.add(Range.closed(1, 120));
System.out.println(r);