algorithm - find the first longest ascending or descending sub-sequence in a given unsorted sequence by C++ -
i writing c++ program find , print first longest ascending or descending continuous subsequence vector of integers. example, given vector with
4, 2, 1, 2, 3, 4, 3, 5, 1, 2, 4, 6, 5
return 1,2,3,4
my code follows:
but, not know how return first optimal solution. example, above sequence has 1, 2, 4, 6 4 long. but, need return 1,2,3,4.
bool findlong(const vector<int> v) { if (v.size() <1) return false; if (v.size() == 1){ cout << v[0] << endl; return true; } vector::const_iterator itr_left, itr_right; itr_left = v.begin(); itr_right = v.begin()+1; bool ascending_flag ; int counter =0; if (*itr_right > *(itr_right-1)){ bool ascending_flag = true; ++ascending_counter; } else{ bool ascending_flag = false; ++descending_counter; } int longest = int_min; vector<int>::iterator longest_left = v.begin(), longest_right =v.begin(); ++itr_right; while (itr_right != v.end()) { if (ascending_flag && *itr_right > *(itr_right-1)) ++ascending_counter; if (!ascending_flag&& *itr_right < *(itr_right-1)) ++descending_counter; if (ascending_flag&& *itr_right < *(itr_right-1)) { if (ascending_counter > longest ) { longest = ascending_counter; longest_left = itr_left; longest_right = itr_right; } itr_left = itr_right; ascending_counter = 0 ; ascending_flag = false; } if (ascending_flag && *itr_right > *(itr_right-1)) { if (descending_counter > longest ) { longest = descending_counter; longest_left = itr_left; longest_right = itr_right; } itr_left = itr_right; descending_counter = 0 ; ascending_flag = true; } ++itr_right; } for_each( longest_left , longest_right, print); cout << endl; } void print(int i) { cout << << " , " ; }
any comments welcome !
thanks !
you have lot of typo in code: hide initialization of ascending_flag length count seems incorrect.
following should work (as long there aren't 2 neighbours same values).
bool findlong(const vector<int>& v) { if (v.empty()) return false; if (v.size() == 1) { cout << v[0] << endl; return true; } vector<int>::const_iterator itr_left = v.begin(); vector<int>::const_iterator itr_right = v.begin() + 1; vector<int>::const_iterator longest_left = itr_left; vector<int>::const_iterator longest_right = itr_right; bool ascending_flag = (*itr_right > *(itr_right - 1)); (++itr_right; itr_right != v.end(); ++itr_right) { if (ascending_flag ^ (*itr_right < *(itr_right - 1))) { if (itr_right - itr_left > longest_right - longest_left) { longest_left = itr_left; longest_right = itr_right; } itr_left = itr_right - 1; ascending_flag = !ascending_flag; } } for_each(longest_left, longest_right, print); cout << endl; return true; }
Comments
Post a Comment