java - Really need two passes in this algorithm? -
suppose want perform action on each word if sentence contains >= 4 numbers. example,
- this string contains 10, 23, 30, 50, 60.
- this string contains 10, , contains 23.
i need take particular action on first sentence above, since contains more 4 numbers. in algorithm above came with, needs 2 passes of string list. there more efficient algorithm task? instance, 1 pass only? thank you.
void process (list<string> sentence) { boolean has4abovenum = false; if(containsmorethan4numbers(sentence)) { has4abovenum = true; } for(string word : sentence) { if(has4abovenum) { dosomething(word); } } } boolean containsmorethan4numbers(list<string> sentence) { int numcount = 0; for(string word : sentence) { if(numcount>4){ return true; } if(isnumber(word)) { numcount++; } } return false; }
you can on 1 path parsing string, , creating in 1 pass on string list<string>
contains numbers in string, each element in list distinct number found in string.
now, have check list.size()
- , make sure in desired range.
list<string> getnumbers(list<string> sentence) { list<string> res = new arraylist<>(); for(string word : sentence) { if(isnumber(word)) res.add(word); } return res; }
Comments
Post a Comment