Get a number between two numbers question
I need help with some c.
I have some code that opens a directory and reads in the names of files which are e.g. 0001, 0002, 0003 up to 9999. I need to get all these numbers and then generate a new number that is not one of these numbers already. here is my code to check the files in the directory DIR *d; struct dirent *dir; int i = 0; d = opendir( "//mydir//" ); if( d ) { printf("Directory stream is now open\n"); while ((dir = readdir(d)) != NULL) { int num = atoi(dir->d_name); printf("Filename=%s number=%d\n", dir->d_name, num); if( num > 0 && num < 9999)// { //I need to add all my numbers to an array or list // and then get a new number which is between 0 and 9999 //that does not include any of my added numbers //Preferably the next logical number e.g. if i have 0,1,2,3 then i should get 4 as my next number } } Can someone help me?? thanks |
Create an int array n[10000] and set the value to 1 if the name is used, otherwise 0.
as in your example: Code:
n[0] = 1; Another better and more difficult solution would be creating a singly linked list of unused names, which you could manage (add/remove members) dynamically. Code:
struct slist |
HarryBoy: Are the names of the files represented by consecutive numbers? (is it possible to have only the following file names: 0001, 0002, 0004)
Alien_Hominid: why would the 'linked list' solution be better in this particular case? |
Thanks guys, the names can be any numer e.g. 0001, 0002, 0099, 1234, 4567, 9999.
here is an attempt by me, please could you guys 'code review' it for me if possible? Code:
const char* getstreamFileNo( void ) |
Actually, a double-linked list:
Code:
struct dlist { |
Re your code:
|
We are talking about finding a "missing number" between 1 and 9999. I'd take the easy array solution without thinking twice about it. I also consider it the superior approach because of the specifics of the task.
HarryBoy: Keep working on it, reread Alien_Hominid's initial suggestion. |
You could try using scandir as well, code not really tested so usual disclaimers apply:
Code:
|
Singly linked list is enough because:
|
That seems to imply creating the complete list first, also, assume you read number N, how do you remove the associated element from the list? A better question would be: what is the representation of the singly-linked list?
|
http://en.wikipedia.org/wiki/Linked_...y-linked_lists
No, you read through directory listing. Assume 4 is missing, you add it to the list, then you find that 9 is missing, you add it to the list, etc, etc... You get 4 -> 9 -> ... While doubly linked list would be: 4 <-> 9 <->, which is unecessary because you always take lowest number first. |
Ah. I got it, you were saying that a singly linked list would suffice given the choice between singly linked and doubly linked. Quite.
|
All times are GMT -5. The time now is 04:30 AM. |