-
consecutive number
Hi,
Just a quick questions. I just wanted to know if it it possible
to tell the program to look at a bunch of characters in an array,
and see if there are any consecutive number in the the string. I know
I have to use a loop statement to check the elements, but then I become
clueless. I was told to use strstr but I haven't got a clue how to use it.
Could someone just point me in the direction.
Thanks for any replies.
-
for example, say our list was: 1, 3, 4, 2.
looping over the entire list, store the first number (1). on the next iteration, compare the current number (2nd number, 3) with the stored number 1, they arent consecutive, so save the current number 3 and go to the next iteration. compare the now current number (3rd number, 4) with the saved number 3, and you see they are consecutive.
you didnt mention the purpose of finding consecutive numbers (ie what to do when you do find one), so i havent really handled what to do then. also, note i used a list of integers, but you said your list was characters. the algorithm should be the same, except you skip over characters that are not numeric (unless you want to find consecutive characters too, then you skip whenever a character is non-alphanumeric)
question to you: how do you know if two numbers (or characters) a and b are consecutive?
hope this was what your looking for.
-
Thanks nadroj, i wanted this part of the program to act like a error checker, I just wanted it to take in a string (roman numeral), and print out a error message if there are more then 3 consecutive numbers found i.e XIIII.
sorry but I didn't really understand this question "question to you: how do you know if two numbers (or characters) a and b are consecutive?"
-
ok, by consecutive i thought you meant 1,2,3,4,..., so the method above is different from what you want.
one way to do this is to loop through the string and compare the current character with the next 3 characters. you can use an integer to count the number of times a character is repeated in order.
for example, with XIIII:
iteration 1:
- current character = 'X', count = 1
- next character = 'I',
- characters not equal, store current character 'I' and reset count to 1 (which happens to be redundant in this case)
iteration 2:
- current character = 'I', count = 1
- next character = 'I',
- characters are equal, increase the count: count = 2
iteration 3:
- current character = 'I', count = 2
- next character = 'I',
- characters are equal, increase the count: count = 3
iteration 4:
- current character = 'I', count = 3
- next character = 'I',
- characters are equal, increase the count: count = 4
iteration 5:
- count = 4 > 3 (meaning more than 3 of the same characters in order)
- handle duplicate error, break out of loop
note: make sure you dont go out of the bounds of your array. ie, dont compare the last character with the last + 1 character because there isnt one.