How to count duplicates in List<Integer> - list

Duplicate of Count occurrences of words in ArrayList
i trying to counts duplicates of my JSON response.
Im got values from 1,2 ... to 13,14
First what i do is sort the list:
Collections.sort(calues);
every value can be used 4 times.
So at last i have list with 1,1,1,1,2,2,2,2.....14,14,14,14
I need to count repeated values and when any value like 1,2 etc will be repeated 3 times i need to give message to user.
How i can do this?
Thanks for help :)
Going with tutorial i create this:
public int count(List<Integer> nums) {
boolean inclump = false;
int clumpcnt = 0;
for (int i = 1; i < nums.size(); i++) {
if (Objects.equals(nums.get(i), nums.get(i - 1))) {
if (!inclump) {
inclump = true;
clumpcnt++;
if(clumpcnt ==3){
Utils.showToast(getApplicationContext(), "WOW VALUE REPEATED 3 TIMES, YOU WIN");
}
}
} else {
inclump = false;
}
}
return clumpcnt;
}
but this count the values and when values like 2,2 and 3,3 and 4,4 then this function enter
if(clumpcnt ==3){
Utils.showToast(getApplicationContext(), "WOW VALUE REPEATED 3 TIMES, YOU WIN");
}
I declared a list private List<Integer> cardsValues = new ArrayList<>();
Then i added values here:
first 5 on start application:
#Override
public void onNext(#NonNull Cards cards) {
cardsArray = cards.getArrayCards();
for (Card item : cardsArray) {
imgUrls.add(item.getImage());
cardsValues.add(item.getRank());
}
}
And the on every click with "Get new Cards"
Im adding new value with this same method
for (Card item : cardsArray) {
imgUrls.add(item.getImage());
cardsValues.add(item.getRank());
}
And here i call the method
private void checkDuplicateAchievement() {
Collections.sort(cardsValues);
count(cardsValues);
}
Here is my full method
private void getCards(final String deck_id, final int count) {
cardApi.getCards(deck_id, count)
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<Cards>() {
#Override
public void onSubscribe(#NonNull Disposable d) {
}
#Override
public void onNext(#NonNull Cards cards) {
cardsArray = cards.getArrayCards();
for (Card item : cardsArray) {
imgUrls.add(item.getImage());
cardsValues.add(item.getRank());
}
cardsRecyclerView.notifyDataSetChanged(); recyclerView.smoothScrollToPosition(cardsRecyclerView.getItemCount());
checkDuplicateAchievement();
}
#Override
public void onError(#NonNull Throwable e) {
}
#Override
public void onComplete() {
}
});
}

You can make use of a HashMap like below.
** Not tested , typing java after a long time!, Just to give you an idea.
public int count(List<Integer> nums) {
Map<Integer, Integer> countMap = new HashMap<Integer, Integer>();
for (int i = 1; i < nums.size(); i++) {
if(countMap.get(nums[i]) != null){
countMap.set(i, countMap.get(nums[i]) + 1)
if (countMap.get(i) >=3){
Utils.showToast(getApplicationContext(), "WOW VALUE REPEATED 3 TIMES, YOU WIN");
}
}else{
countMap.set(i, 1)
}
}
}

Try this:
public int count(List<Integer> nums) {
boolean inclump = false; // Not used
int clumpcnt = 0;
int value = nums.get(0);
for (int i = 1; i < nums.size(); i++) {
if (Objects.equals(value, nums.get(i))) {
clumpcnt++;
if (clumpcnt == 3) {
Utils.showToast(getApplicationContext(), "WOW VALUE REPEATED 3 TIMES, YOU WIN");
Log.d("COUNT", "WOW VALUE " + String.valueOf(value) + " REPEATED 3 TIMES, YOU WIN");
clumpcnt = 0;
}
} else {
clumpcnt = 0;
value = nums.get(i);
}
}
return clumpcnt;
}
FYI, nums list contains 1,1,1,1,2,2,2,2,3,3,3,3
OUTPUT LOG:
28078-28078/com.ferdous.stackoverflowanswer D/COUNT: WOW VALUE 1 REPEATED 3 TIMES, YOU WIN
28078-28078/com.ferdous.stackoverflowanswer D/COUNT: WOW VALUE 2 REPEATED 3 TIMES, YOU WIN
28078-28078/com.ferdous.stackoverflowanswer D/COUNT: WOW VALUE 3 REPEATED 3 TIMES, YOU WIN

You can sort your list and then loop the sorted elements and compare values at adjacent positions.If they match then duplicates are present

Related

Displaying steps to maximum profit

I am passing in a sorted vector that contains a data as such:
Job Details {Start Time, Finish Time, Profit}
Job 1: {1 , 2 , 50 }
Job 2: {3 , 5 , 20 }
Job 3: {6 , 19 , 100 }
Job 4: {2 , 100 , 200 }
The code finds which jobs are the best for profit by checking all paths that don't overlap for example job 1,2,3 or job 1,4 are possible and it determines job 1,4 is the best value. I am trying to build a function that displays the path on how the code got to the best possible solution.
Ex. Job 1 --> Job 4 --> $250.
But am lost on the implementation.
Main.cpp
// Find the latest job (in sorted array) that doesn't
// conflict with the job[i]. If there is no compatible job,
// then it returns -1.
int latestNonConflict(vector<Task>someVector, int i)
{
for (int j = i - 1; j >= 0; j--)
{
if (someVector[j].getEndTime() <= someVector[i - 1].getStartTime())
{
return j;
}
}
return -1;
}
// A recursive function that returns the maximum possible
// profit from given array of jobs. The array of jobs must
// be sorted according to finish time.
int bruteForceMethod(vector<Task>someVector, int n)
{
// Base case
if (n == 1)
{
return someVector[n - 1].getValue();
}
// Find profit when current job is inclueded
int inclProf = someVector[n - 1].getValue();
int i = latestNonConflict(someVector, n);
if (i != -1)
cout << someVector[i].getLabel() << "-->";
inclProf += bruteForceMethod(someVector, i + 1);
// Find profit when current job is excluded
int exclProf = bruteForceMethod(someVector, n - 1);
return max(inclProf, exclProf);
}
// The main function that returns the maximum possible
// profit from given array of jobs
int findMaxProfit(vector<Task>someVector, int n)
{
return bruteForceMethod(someVector, n);
}
int main()
{
cout << "The optimal profit is " << bruteForceMethod(tasksVector,
tasksVector.size()) << endl;
return 0;
}
Task.h
#include <string>
using namespace std;
#ifndef Task_h
#define Task_h
class Task
{
public:
Task();
Task(string, int, int, int);
void setLabel(string);
string getLabel();
void setStartTime(int);
int getStartTime();
void setEndTime(int);
int getEndTime();
void setValue(int);
int getValue();
private:
string label;
int startTime;
int endTime;
int value;
};
#endif
Task.cpp
#include "Task.h"
Task::Task()
{
}
Task::Task(string inLabel, int inStartTime, int inEndTime, int inValue)
{
label = inLabel;
startTime = inStartTime;
endTime = inEndTime;
value = inValue;
}
void Task::setLabel(string inLabel)
{
label = inLabel;
}
string Task::getLabel()
{
return label;
}
void Task::setStartTime(int inStartTime)
{
startTime = inStartTime;
}
int Task::getStartTime()
{
return startTime;
}
void Task::setEndTime(int inEndTime)
{
endTime = inEndTime;
}
int Task::getEndTime()
{
return endTime;
}
void Task::setValue(int inValue)
{
value = inValue;
}
int Task::getValue()
{
return value;
}
You can simply consider a weighted graph G where
a node is a job
a node A is linked to a node B if A.endTime < B.startTime
weight of edge(A,B) is B.profit (taking the path to B means doing job B)
You want to get the path of maximal weight of G.
Usually algorithm want a function to minimize so instead lets take for weight -B.profit.
We can always cite the Floyd–Warshall algorithm , there is even the path reconstruction algorithm provided in link aforementionned.
Home made
But let's do it home-made since it seems to be some homework.
You can do it the bruteforce way (which is less efficient but easier to grasp than Floyd Warshall) and check all the longest paths...
create a root node to which you add for children all the jobs with their respective weight associated then consider the recursive function:
def get_longest_path(node):
if !node.children
return 0
best_all = {
w: weight(node, node.children[0]),
path: [node, get_longest_path(node.children[0])]
}
for node.children as child //starting from 1
best_path_i = get_longest_path(child)
//if we found a path with lower total weight (that is, with maximal profit)
if best_path_i != 0 && best_path_i.weight < best_all.weight
best_all = {
w: weight(node, child),
path:[node, best_path_i]
}
return best_all
get_longest_path(root)
note that you can trivially memoize get_longest_path (to avoid reevalution for an already visited node) without much burden
cache = {}
def get_longest_path(node):
if !node.children
return 0
//node.id is jobId
if node.id in cache
return cache[node.id]
best_all = {
w: weight(node,node.children[0]),
path: [node, get_longest_path(node.children[0])]
}
for node.children as child //starting from 1
best_path_i = get_longest_path(child)
//if we found a path with lower total weight (that is, with maximal profit)
if best_path_i != 0 && best_path_i.weight < best_all.weight
best_all = {
w: weight(node, child),
path:[node, best_path_i]
}
cache[node.id] = best_all
return best_all
get_longest_path(root)
No cycles handled but you don't have a job which reverses time I guess
This algorithm can be approached very similarly to a recursive permutation implementation of say a string ABC which produces ABC, ACB, BAC, BCA, CAB, CBA.
Here is a simple demonstration
You could modify this to "prune" the tree when a condition is not met (eg. the letter after is lower in the alphabet than the previous), so you would get ABC as it is the only one where every succesive letter is lower (A<B<C).
Once you have that, you now understand how to recurse over Task's and prune when comparing the startTime and endTime of jobs...
So here is an implementation of the above in C++:
#include <iostream>
#include <vector>
using namespace std;
struct Task {
// global counter tracking how many instances
static int counter;
int startTime;
int endTime;
int value;
int label;
Task(int inStartTime, int inEndTime, int inValue) {
startTime = inStartTime;
endTime = inEndTime;
value = inValue;
label = Task::counter++;
}
};
// store an index to each Task to keep track
int Task::counter = 1;
// build a search tree of all possible Task sequences
// pruning if next Task and current Task overlap
void jobSearchTree(vector<Task> jobSequence,
vector<Task> possibleJobs,
vector<vector<Task>> &possibleJobSequences) {
for (int i = 0; i < possibleJobs.size(); i++) {
vector<Task> l;
for (int j = 0; j < jobSequence.size(); j++)
{
l.push_back(jobSequence.at(j));
}
l.push_back(possibleJobs[i]);
// initial recursive call
if (!jobSequence.size()) {
vector<Task> searchJobs(possibleJobs);
searchJobs.erase(searchJobs.begin() + i);
jobSearchTree(l, searchJobs, possibleJobSequences);
}
// test if jobs occur sequentially
else if (l.at(l.size()-2).endTime <= l.at(l.size()-1).startTime) {
// add the Task sequence
possibleJobSequences.push_back(l);
vector<Task> searchJobs(possibleJobs);
// remove this Task from the search
searchJobs.erase(searchJobs.begin() + i);
// recursive call with Task sequence as the head
// and the remaining possible jobs as the tail
jobSearchTree(l, searchJobs, possibleJobSequences);
}
}
}
vector<int> getBestJobSequence(vector<vector<Task>> possibleJobSequences) {
int maxProfit = 0;
int totalProfit = 0;
vector<Task> bestJobSequence;
for (auto jobSequence : possibleJobSequences) {
totalProfit = 0;
for (auto Task : jobSequence) {
totalProfit += Task.value;
}
if (totalProfit > maxProfit) {
maxProfit = totalProfit;
bestJobSequence = jobSequence;
}
}
vector<int> jobIds;
for (auto Task : bestJobSequence) {
jobIds.push_back(Task.label);
}
return jobIds;
}
int main()
{
Task s1(1, 2, 50);
Task s2(3, 5, 20);
Task s3(6, 19, 100);
Task s4(2, 100, 200);
vector<Task> allJobs = {s1, s3, s4};
vector<vector<Task>> possibleJobSequences;
vector<Task> currentJobSequence;
jobSearchTree(currentJobSequence, allJobs, possibleJobSequences);
vector<int> bestJobSequence = getBestJobSequence(possibleJobSequences);
for (auto job : bestJobSequence) {
cout << job << endl;
}
return 0;
}

Problem to acces a position in an list c++

I'm implementing a function to insert a set of nodes in a set of routes. This function is described as follows:
void Repair_ChooseARouteAndAPositionRandomly (SOLUTION &sol, vector<int> &NodesPscine, vector<int>&RoutesPscine, DATA data, int max_slot){
while (NodesPscine.size() != 0) {
int aux;
int pairpos;
int pairRoute;
int pairNode;
list<VEHICLE>:: iterator irouteit;
vector<bool> RotaJaFoiSorteada = vector<bool>(sol.SetP.size(),false);
pairpos = rand() % NodesPscine.size();
pairNode = NodesPscine[pairpos];
pairRoute = RoutesPscine[pairpos];
bool sorteaDenovo = true;
while (sorteaDenovo == true) {
bool rotaJafoiSorteada = false;
while (rotaJafoiSorteada == false) {
aux = rand() % sol.SetP.size();
if (RotaJaFoiSorteada[aux] == false) {
irouteit = next(sol.SetP.begin(), aux);
rotaJafoiSorteada = true;
RotaJaFoiSorteada[aux] = true;
}
}
bool NoJaExisteNaRota = false;
list<int>:: iterator ii;
for (ii = irouteit->rotaVehicle.begin(); ii != irouteit->rotaVehicle.end(); ii++) {
if (pairNode == *ii) {
NoJaExisteNaRota = true;
break;
}
}
if (NoJaExisteNaRota == false) {
double melhorDur = 0;
list <int>::iterator melhorPos = irouteit->rotaVehicle.begin();
double NovaDur;
InsereNaPosicaoMaisBarata (irouteit->rotaVehicle, irouteit->type, pairNode, data, melhorDur, melhorPos);
NovaDur = irouteit->duracaoTotal + melhorDur;
if (NovaDur <= max_slot) {
irouteit->rotaVehicle.insert(melhorPos,pairNode);
irouteit->duracaoTotal = NovaDur;
int cont = 0;
list<int>::iterator itprim = irouteit->rotaVehicle.begin();
list<int>::iterator itseg;
irouteit->distanceTotal = 0;
while (cont < irouteit->rotaVehicle.size()-1) {
itseg = next(itprim, 1);
irouteit->distanceTotal += data.dist[*itprim][*itseg];
++itprim;
++cont;
}
sorteaDenovo = false;
NodesPscine.erase(NodesPscine.begin()+pairpos);
RoutesPscine.erase(RoutesPscine.begin()+pairpos);
} // if (NovaDur <= max_slot) {
} // if (NoJaExisteNaRota == false) {
} // while (sorteaDenovo == true) {
} // while (NodesPscine.size() != 0) {
}
I also describe another function and some structs that may be important to identify my mistake.
void InsereNaPosicaoMaisBarata (list<int> Rota, int vehicle, int no, DATA data, double &melhorDur, list <int>::iterator &melhorPos ) {
list <int>:: iterator itprim = Rota.begin();
list <int>:: iterator itseg;
int cont = 0;
melhorDur = 10000000000000000;
while (cont < (Rota.size()-1)) {
itseg = next(itprim, 1);
double aux = data.l[vehicle][*itprim][no] + data.l[vehicle][no][*itseg] - data.l[vehicle][*itprim][*itseg];
if (melhorDur > aux) {
melhorDur = aux;
melhorPos = itseg;
}
++itprim;
++cont;
}
}
struct VEHICLE {
int type;
int idx;
double custo;
double distanceTotal;
double duracaoTotal;
list<int> rotaVehicle;
};
struct SOLUTION {
list<VEHICLE> SetP;
};
Everything goes fine to insert the first pairNode randomly chosen. However, when a second pairNode is chosen, the program runs until the line just after calling the function InsereNaPosicaoMaisBarata. If I put any cout inside this function, it does not appear. I think the problem is in the line "irouteit->rotaVehicle.insert(melhorPos,pairNode);", because when I comment it, the code runs until the end.
If I have, for example, these routes:
route 1 { 4 2 1 3 4 }
route 2 { 3 2 4 3 }
route 3 { 4 2 1 3 4 }
route 4 {4 1 3 4 }
route 5 { 2 4 2 }
route 6 { 3 2 4 3 }
If we have the nodes to be inserted in any of these routes as NodesPscine = {3,2}. If node 3 is randomly chosen to be inserted in route 5, it works well.
After, node 4 is chosen to be inserted in route 4. Then, the program runs until the function InsereNaPosicaoMaisBarata and the error message appears:
*** Error in `./heuristica': malloc(): memory corruption (fast): 0x00000000035d0680 ***
I suppose the way I'm identifying the melhorPos is not okay. But I can't figure out what is wrong.
You did not post all of your code, but one obvious mistake is this:
InsereNaPosicaoMaisBarata (irouteit->rotaVehicle, // <-- This parameter
irouteit->type,
pairNode,
data,
melhorDur,
melhorPos);
Your function is declared as this:
void InsereNaPosicaoMaisBarata (list<int> Rota, // <-- passed by value
int vehicle,
int no,
DATA data,
double &melhorDur,
list <int>::iterator &melhorPos )
Then inside the function, you do this:
list <int>:: iterator itprim = Rota.begin(); // <-- This is a local std::list
list <int>:: iterator itseg;
//...
itseg = next(itprim, 1);
//...
melhorPos = itseg; // <-- This is now referencing a local std::list entry
On return, you then use the last parameter:
irouteit->rotaVehicle.insert(melhorPos,pairNode); // <-- Trouble
The problem with all of this is that the first parameter (Rota) is passed by value. That means the function InsereNaPosicaMaisBarata is working with a temporary std::list.
You then set melhorPos to point to an entry into the temporary list. The problem is that on return, Rota has been destroyed, and you now have an invalid iterator being used on the return.
The solution is to change the function to have the first parameter as a reference:
void InsereNaPosicaoMaisBarata (list<int>& Rota, // <-- passed by reference
int vehicle,
int no,
DATA data,
double &melhorDur,
list <int>::iterator &melhorPos )

How to limit a decrement?

There is a initial game difficulty which is
game_difficulty=5 //Initial
Every 3 times if you get it right, your difficulty goes up to infinity but every 3 times you get it wrong, your difficulty goes down but not below 5. So, in this code for ex:
if(user_words==words) win_count+=1;
else() incorrect_count+=1;
if(win_count%3==0) /*increase diff*/;
if(incorrect_count%3==0) /*decrease difficulty*/;
How should I go about doing this?
Simple answer:
if(incorrect_count%3==0) difficulty = max(difficulty-1, 5);
But personally I would wrap it up in a small class then you can contain all the logic and expand it as you go along, something such as:
class Difficulty
{
public:
Difficulty() {};
void AddWin()
{
m_IncorrectCount = 0; // reset because we got one right?
if (++m_WinCount % 3)
{
m_WinCount = 0;
++m_CurrentDifficulty;
}
}
void AddIncorrect()
{
m_WinCount = 0; // reset because we got one wrong?
if (++m_IncorrectCount >= 3 && m_CurrentDifficulty > 5)
{
m_IncorrectCount = 0;
--m_CurrentDifficulty;
}
}
int GetDifficulty()
{
return m_CurrentDifficulty;
}
private:
int m_CurrentDifficulty = 5;
int m_WinCount = 0;
int m_IncorrectCount = 0;
};
You could just add this as a condition:
if (user words==words) {
win_count += 1;
if (win_count %3 == 0) {
++diff;
}
} else {
incorrect_count += 1;
if (incorrect_count % 3 == 0 && diff > 5) {
--diff
}
}
For example:
if(win_count%3==0) difficulty++;
if(incorrect_count%3==0 && difficulty > 5) difficulty--;
This can be turned into a motivating example for custom data types.
Create a class which wraps the difficulty int as a private member variable, and in the public member functions make sure that the so-called contract is met. You will end up with a value which is always guaranteed to meet your specifications. Here is an example:
class Difficulty
{
public:
// initial values for a new Difficulty object:
Difficulty() :
right_answer_count(0),
wrong_answer_count(0),
value(5)
{}
// called when a right answer should be taken into account:
void GotItRight()
{
++right_answer_count;
if (right_answer_count == 3)
{
right_answer_count = 0;
++value;
}
}
// called when a wrong answer should be taken into account:
void GotItWrong()
{
++wrong_answer_count;
if (wrong_answer_count == 3)
{
wrong_answer_count = 0;
--value;
if (value < 5)
{
value = 5;
}
}
}
// returns the value itself
int Value() const
{
return value;
}
private:
int right_answer_count;
int wrong_answer_count;
int value;
};
And here is how you would use the class:
Difficulty game_difficulty;
// six right answers:
for (int count = 0; count < 6; ++count)
{
game_difficulty.GotItRight();
}
// check wrapped value:
std::cout << game_difficulty.Value() << "\n";
// three wrong answers:
for (int count = 0; count < 3; ++count)
{
game_difficulty.GotItWrong();
}
// check wrapped value:
std::cout << game_difficulty.Value() << "\n";
// one hundred wrong answers:
for (int count = 0; count < 100; ++count)
{
game_difficulty.GotItWrong();
}
// check wrapped value:
std::cout << game_difficulty.Value() << "\n";
Output:
7
6
5
Once you have a firm grasp on how such types are created and used, you can start to look into operator overloading so that the type can be used more like a real int, i.e. with +, - and so on.
How should I go about doing this?
You have marked this question as C++. IMHO the c++ way is to create a class encapsulating all your issues.
Perhaps something like:
class GameDifficulty
{
public:
GameDifficulty () :
game_difficulty (5), win_count(0), incorrect_count(0)
{}
~GameDifficulty () {}
void update(const T& words)
{
if(user words==words) win_count+=1;
else incorrect_count+=1;
// modify game_difficulty as you desire
if(win_count%3 == 0)
game_difficulty += 1 ; // increase diff no upper limit
if((incorrect_count%3 == 0) && (game_difficulty > 5))
game_difficulty -= 1; //decrease diff;
}
inline int gameDifficulty() { return (game_difficulty); }
// and any other access per needs of your game
private:
int game_difficulty;
int win_count;
int incorrect_count;
}
// note - not compiled or tested
usage would be:
// instantiate
GameDiffculty gameDifficulty;
// ...
// use update()
gameDifficulty.update(word);
// ...
// use access
gameDifficulty.gameDifficulty();
Advantage: encapsulation
This code is in one place, not polluting elsewhere in your code.
You can change these policies in this one place, with no impact to the rest of your code.

check how often value of array consecutively appears [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
i have a string "param", say :
param = aaaa;
and i have an array "word" which consists of :
word = [aaaa,aabb,aacc,aaaa,cccc,bbbb,ccdd,ccbb,ddcc,ccee,aaaa];
and i want to check how often another string than param appears on word. from that example above, i expects result to be :
2
6
how do i check that false string consecutively?
i tried to implement some code like this :
bool check(std::string param, std::vector< std::string > word)
{
int sum = 0; //sums of consecutive false string
for (unsigned int limit =0;limit<word.size();limit++)
{
if (word[limit]!=param)
{
sum = sum + 1;
}
else
{
sum = sum - 1;
}
}
if (sum>=10)
{
return true;
}
else
{
return false;
}
}
input
param : "aaaa"
word : ["aaaa",
"bbbb",
"bbbb",
"bbbb",
"bbbb",
"bbbb",
"bbbb",
"bbbb",
"bbbb",
"bbbb",
"bbbb",
"aaaa"]
output ==> false
expected output ==> true
i finally found the answer. thanks to #πάντα ῥεῖ and #Anedar
here is the right code :
bool check(std::string param, std::vector< std::string > word)
{
int sum = 0; //sums of consecutive false string
std:vector<int> sums; //array of sum value
for (unsigned int limit =0;limit<word.size();limit++)
{
if (word[limit]!=param)
{
++sum;
}
else if (sum!=0)
{
sums.push_back(sum);
sum = 0;
}
}
if (sum!=0)
{
sums.push_back(sum); //make sure even if word vector does not end with param, the number still get pushed to counter vector
}
int temp = 0; //variable to store maximum value of consecutive array
for (int iter = 0; iter < sums.size(); iter ++)
{
if (sums[iter]>temp)
temp = sums[iter]; //store maximum value of consecutive array
}
//now the return bool value
if (temp>=10)
{
return true;
}
else
{
return false;
}
}
Ok, first of all, you resetted your sum every loop, so the only two possible results you can get after your for-loop are 1 and -1. What you really want to do when checking consecutives is to reset it only when your current streak has finished, so what you need is something like this:
bool check(std::string param, std::vector< std::string > word)
{
int current=0; //current sum of consecutive false string
std::vector<int> sums; //finished consecutives are stored here
for (unsigned int limit =0;limit<word.size();limit++)
{
if (word[limit]!=param)
{
++current;
}
else if (current != 0)
{
//a consecutive run has just finished
sums.push_back(current);
current=0;
}
}
if (current != 0)
sums.push_back(current);
//deal with sums here
}
I think what it does is pretty straightforward: Count the current strings != param and if it finds a param push the length of the current streak to a vector. You then need to deal with this vector in some way, either by returning it (then bool is the wrong return type) or by doing some other checks with it.
Oh and a small edit: the last if makes sure that even if your vector does not end with a param the number gets pushed to your vector.
expected output ==> true
Just remove the subtraction in the else part inside the for() loop to get the expected output:
bool check(std::string param, std::vector< std::string > word)
{
int sum = 0; //sums of consecutive false string
for (unsigned int limit =0;limit<word.size();limit++)
{
if (word[limit]!=param)
{
sum = sum + 1;
}
// else
// {
// sum = sum - 1;
// }
}
if (sum>=10)
{
return true;
}
else
{
return false;
}
}

QListWidget Insert Items

I am trying to add two items into my QListWidget dynamically. However, the following codes only allow me to add only the last item into the list. strList.size() contains 4 items. Assuming name contains "ABC 1" and "ABC 2".
Is my loop incorrect? Or is my method of adding items into the listWidget wrong?
.h:
public:
QListWidgetItem *item[2];
.cpp:
...
while(!xml.atEnd())
{
xml.readNextStartElement();
if(xml.isStartElement())
{
if(xml.name() == "OS")
{
strList << xml.readElementText();
}
}
}
int num = 0;
for(int i = 0; i < strList.size(); i++)
{
if(strList[i] == "ABC")
{
QString name = strList[i] + strList[i+1];
item[num] = new QListWidgetItem();
item[num]->setText(name);
ui.listWidget->insertItem(num, item[num]);
num += 1;
}
}
Output (listWidget):
ABC02
Expected output (listWidget):
ABC01 ABC02