# Save the integers in the array given by the first integer

advertisements

I need to know, how to save integers from stdin into array, given by first integer in line... Ehm... hope you understand. I will give you an example.

On stdin I have:

0 : [ 1, 2, 3 ]
5 : [ 10, 11, 12, 13]
6 : [ 2, 4, 9 ]
0 : [ 4, 9, 8 ]
5 : [ 9, 6, 7 ]
5 : [ 1 ]

And I need save these integers to the arrays like this:

0={1, 2, 3, 4, 9, 8}
5={10, 11, 12, 13, 9, 6, 7, 1}
6={2, 4, 9}

I absolutely don't how to do it. There is a problem, that the number of arrays(in this case - 0, 5, 6 - so 3 arrays ) can be very high and I need to work effectively with memory...So I guess i will need something like malloc and free to solve this problem, or am I wrong? The names of arrays (0, 5, 6) can be changed. Number of integers in brackets has no maximum limit.

Thank you for any help.

I go with the assumption, this is homework, and I go with the assumption, this isn't your first homework to do, so I won't present you a solution but instead some tips that would help you to solve it yourself.

Given the input line

5 : [ 10, 11, 12, 13]

I will call "5" the "array name" and 10, 11, 12 and 13 the values to add.

1. You should implement some system to map array names to indices. A trivial approach would be like this:

.

size_t num_arrays;
size_t * array_names;

Here, in your example input, num_arrays will end up being 3 with array_names[3] = { 0, 5, 6}. If you find a new array name, realloc and add the new array name. Also you need the actual arrays for the values:

int * * array;

you need to realloc array for each new array name (like you realloc array_names). array[0] will represent array array_names[0] here array 0, array[1] will represent array array_names[1] here array 5 and array[2] will represent array array_names[2] here array 6.

To access an array, find it's index like so:

size_t index;
for (size_t index = 0; index < num_arrays && array_names[index] != search; ++index) ;

1. The second step is easy. Once you figured out, you need to use array[index] to add elemens, realloc that one (array[index] = realloc(array[index], new size)) and add elements there array[index][i+old_size] = new_value[i].

Obviously, you need to keep track of the number of elements in your separate arrays as well ;)

Hint: If searching for the array names take too long, you will have to replace that trivial mapping part by some more sophisticated data structure, like a hash map or a binary search tree. The rest of the concept may stay more or less the same.

Should you have problems to parse the input lines, I suggest, you open a new question specific on this parsing part.