Find duplicate consecutive numbers in a randomly generated array - c++

I want to find duplicate numbers in a row (2 in a row, 3 in a row, ...) in a randomly generated array. I can't make it further than this:
#include "stdafx.h"
#include <iostream>
#include <cstring>
#include <ctime>
#include <array>
#include <algorithm>
using namespace std;
int main()
{
srand(time(NULL));
const int velikostPolja = 100;
int a[velikostPolja];
int y = 0;
int x = 0;
for (int i = 0; i < velikostPolja; i++)
{
a[i] = rand() % 10;
cout << a[i];
}
cout << endl;
for (int i = 0; i < velikostPolja; i++)
{
if (a[i] == a[i + 1])
x++;
}
cout << endl;
cout << "Two times repated in row: " << x << endl;
system("pause");
return 0;
}

You could do it like this:
int count[velikostPolja] = { 0 };
int c = 0;
for (int i = 1; i < velikostPolja; i++)
{
if (a[i] == a[i - 1])
{
++c;
}
else
{
++count[c];
c = 0;
}
}
for (int i = 1; i < velikostPolja; i++)
{
if (count[i])
{
cout << i + 1 << " times repeated in row: " << count[i] << endl;
}
}
This does not account for any repeats at the end of a, though. I leave that as an exercise for you to do yourself.

You might use:
template <typename IT>
std::size_t count_repetition(IT begin, IT end, std::size_t count)
{
std::size_t res = 0;
auto it = begin;
while (it != end) {
it = std::adjacent_find(it, end);
if (it == end){
return res;
}
const auto it2 = std::find_if(it, end, [it](const auto& e) { return e != *it; });
const auto dist = std::distance(it, it2);
if (count <= dist) {
// how to count 2-repetition for {a, a, a, a}
#if 0
++res; // Count only as 1
#else
res += dist + 1 - count; // count as 3
#endif
}
it = it2;
}
return res;
}
Demo

Related

Program containing threading in cpp is not executed completely

Code given below is not executed completely;
I have looked for everything on web but I don't know why it is working for starting numbers from nums (i.e. 1000 and sometimes 5000) and after that it starts execution but in between program terminates itself and stopes working.
#include <bits/stdc++.h>
// #include <iostream>
// #include <chrono>
// #include <vector>
#define UPPER_LIMIT 10
using namespace std;
using namespace std::chrono;
bool inTimeLimit = true;
bool isFinished = false;
bool isRunning = true;
class Timer {
public:
time_point<high_resolution_clock> start, end;
Timer() {
start = high_resolution_clock::now();
}
~Timer() {
end = high_resolution_clock::now();
auto durationTime = durationCounter();
cout << "\n\nTaken time Duration " << (unsigned long long)durationTime << " us; " << (unsigned long long)durationTime * 0.001 << "ms.";
}
float durationCounter() {
auto currTime = high_resolution_clock::now();
auto durationTime = duration_cast<microseconds>(currTime - start);
return durationTime.count();
}
};
void printVector(vector <int> v) {
cout << endl;
for (int x : v) {
cout << setw(3) << x << " ";
}
}
void printVectorToFile(ofstream &fout , vector <int> v, string msg) {
fout << "\n\n===================\n\n";
fout << msg << endl;
fout << endl;
for (int x : v) {
fout << setw(5) << x << " ";
}
fout << endl;
}
void swap (int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
vector <int> randomArrayGenerator(int n) {
vector<int> v(n);
for (int i = 0; i < n; ++i)
v[i] = i + 1;
srand(time(0));
for (int i = 0; i < n; ++i)
{
int pos = rand() % n;
swap(&v[i], &v[pos]);
}
return v;
}
string sortingChecker(vector<int> v) {
for (int i = 0; i < (int)v.size() - 1; ++i)
{
if (v[i] > v[i + 1]) return "false";
}
return "true";
}
bool sortChecker(vector<int> v) {
for (int i = 0; i < (int)v.size() - 1; ++i)
{
if (v[i] > v[i + 1]) return false;
}
return true;
}
// Merge function
void merge(vector <int> &v, int begin, int middle, int end) {
vector <int> left, right;
for (int i = begin; i < middle + 1; ++i)
{
left.push_back(v[i]);
}
for (int i = middle + 1; i <= end; ++i)
{
right.push_back(v[i]);
}
int p1 = 0, p2 = 0, n1 = left.size(), n2 = right.size(), p = begin;
while ((p1 < n1 ) || (p2 < n2)) {
if ((p1 != n1 ) && ((p2 == n2) || left[p1] < right[p2]))
v[p++] = left[p1++];
else
v[p++] = right[p2++];
}
}
void mergeSortByIteration(vector <int> &v, bool &isTimeDelayed) {
int low = 0, high = v.size();
cout << "Thread ID: " << this_thread::get_id() << endl;
// n :for taking individual block of vector containing number of elements n=[1,2,4,8,..]
for (int n = 1; n < high; n *= 2) {
if (isTimeDelayed) return;
// taking block according to n and then sorting them by merge function
// n=1 => i=0,2,4,8,16
// n=2 => i=0,4,8
for (int i = 0; i < high; i += 2 * n) {
if (isTimeDelayed) return;
int begin = i;
int mid = i + n - 1;
int end = min(i + 2 * n - 1 , high - 1);
merge(v, begin, mid, end);
}
}
}
// Merge by recurision
void mergeSortByRecursion (vector <int> &v, int begin, int end, bool &isTimeDelayed) {
if (end <= begin || isTimeDelayed) return;
int middle = begin + (end - begin) / 2;
mergeSortByRecursion(v, begin, middle, isTimeDelayed);
mergeSortByRecursion(v, middle + 1, end, isTimeDelayed);
merge(v, begin, middle, end);
}
int main() {
int nums[] = {1000, 5000, 10000, 50000, 100000};
// int nums[] = {50000};
ofstream vectorOutput ;
vectorOutput.open("outputTexts\\prac1_resultedArrays.txt", ios::trunc);;
for (int n : nums)
// ``````` Merge by Iteration ````````
{
vector<int> num, arr = randomArrayGenerator(n);
cout << "\n=======";
cout << "\n\nMerge by Iteration:" << endl;
num = arr;
cout << "Array size: " << num.size() << endl;
bool isTimeOut = false, isSorted = false;
Timer timer;
std::thread worker(mergeSortByIteration, ref(num), ref(isTimeOut));
// mergeSortByIteration(num, isTimeOut);
// std::thread worker(mergeSortByRecursion, ref(num), 0, n - 1, ref(isTimeOut));
while ( ( ( timer.durationCounter() / 1000000 ) < 5) && (!isSorted ) ) {
// this_thread::sleep_for(seconds(1));
// cout << timer.durationCounter() << " ";
isSorted = sortChecker(num);
}
if ( ( ( ( timer.durationCounter() / 1000000 ) > 5) && (!isSorted ) ) )
{
isTimeOut = true;
cout << endl << "!!!!!Execution Terminated ---- Time Limit reached!!!!!!" << endl;
}
if (worker.joinable())
worker.join();
printVector(num);
cout << "\nCheck result for sorted Vector:" << (isSorted ? "true" : "false") << endl;
// printVectorToFile(vectorOutput, num, "Merge By Iteration for size:" + to_string(n) );
}
cout << "\n\ndone" << endl;
return 0;
}
can anyone help me out here?
If issue is not clear fill free to ask.

for loop done without meeting the condition I set

#include <iostream>
#include <vector>
using namespace std;
int main()
{
int n = 5;
int nums[] = {0 ,1};
if (n == 0)
{
return 0;
} else if (n == 1)
{
return 1;
} else{
for (int i = 2; i < n + 1; i++)
{
cout << i << endl;
nums[i] = nums[i-2] + nums[i-1];
}
return nums[n]
}
return 0;
}
It is just a simple fibonacci array, but my code only gives stdout one time and it is two. FYI: this code may not be correct to compute the nth term of fibonacci array, but i am strugglling with this for loop.
I think the condition of i < n+1 is not meet, but why this for loop ends
nums[i] has size 2. You can't access nums[i] for i >= 2. An array doesn't grow. You can't change the size of an array. Use a std::vector. You've already included the header. A return statement finishes a function. In case of the main function it causes the program to stop. The return value of the main function by convention describes if the program was successful or errors occurred. You are returning
return nums[n];
That's probably not your intention. I assume you want to print the vector.
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int n = 5;
std::vector<int> nums {0 ,1};
if (n == 0)
{
return 0;
} else if (n == 1) {
return 1;
} else {
nums.reserve(n + 1);
for (int i = 2; i < n + 1; i++)
{
cout << i << '\n';
nums.emplace_back(nums[i-2] + nums[i-1]);
}
for (const auto num : nums)
{
cout << num << '\n';
}
}
return 0;
}
it's because you can't access to nums[2] so the correct version of your code is :
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int n = 5;
int nums[5] = {0 ,1};
if (n == 0)
{
return 0;
} else if (n == 1)
{
return 1;
} else{
for (int i = 2; i < n + 1; i++)
{
cout << i << endl;
nums[i] = nums[i-2] + nums[i-1];
}
return nums[n]
}
return 0;
}
you must provide estimated size to array or you will create vector or some dynamic array..
Your approach always give Segmentation fault;
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int n = 5;
vector<int> nums(n+1);
nums[0]=0;
nums[1]=1;
if (n == 0)
{
return 0;
} else if (n == 1)
{
return 1;
} else{
for (int i = 2; i < n + 1; i++)
{
// cout << i << endl;
nums[i] = nums[i-2] + nums[i-1];
}
for(int i=0;i<n;i++)
{
cout<<nums[i]<<endl; }
}
return 0;
}
*/

Generate Partition of integer into k different integers (C++)

I have problem with the constraint
I have to partition it to "exact" k "different" integers
e.g. 10 = 1+2+7 -> valid
10 = 2+2+6 -> invalid
I don't want to print them, I want to store them in to vectors or something
I am thinking of recursive solution, but still can't come up with a efficient way to store them...(the solution I found can only print it)
And I think it should store in vector<vector>
the struct should be like this?
Partition(){
....
....
}
Partition_main(){
...
Partition()
....
}
In practice, the problem is to enumerate all the solutions.
This can be done by a DFS.
In the following code, the DFS is implemented with a help of a FIFO (i.e. a std::queue).
The little trick is, for a given candidate at a given step, to calculate the minimum
sum that can be obtained in the next steps.
If this minimum sum is larger than n, then we can stop the research in this direction.
#include <iostream>
#include <vector>
#include <queue>
#include <cassert>
struct Parti {
std::vector<int> v;
int sum = 0;
};
std::vector<std::vector<int>> get_partitions (int n, int k) {
std::vector<std::vector<int>> result;
std::queue<Parti> fifo;
Parti start;
fifo.push(start);
while (!fifo.empty()) {
Parti elt = fifo.front();
fifo.pop();
int sum = elt.sum;
int remain = k-elt.v.size();
if (remain == 1) {
int last = n - sum;
if (k > 1) assert (last > elt.v.back());
elt.v.push_back(last);
result.push_back (elt.v);
continue;
}
int i;
if (elt.v.size() == 0) i = 1;
else i = elt.v.back() + 1;
while (true) {
int min_sum = sum + remain*(2*i + remain - 1)/2;
if (min_sum > n) break;
Parti new_elt = elt;
new_elt.v.push_back(i);
new_elt.sum += i;
fifo.push (new_elt);
++i;
};
}
return result;
}
int main() {
int n = 15;
int k = 4;
auto res = get_partitions (n, k);
if (res.size() == 0) {
std::cout << "no partition possible\n";
return 0;
}
for (const auto& v: res) {
std::cout << n << " = ";
for (int i = 0; i < v.size(); ++i) {
std::cout << v[i];
if (i == v.size()-1) {
std::cout << "\n";
} else {
std::cout << " + ";
}
}
}
return 0;
}

Incorrect Comparisons And Swaps Counter Output for Quicksort Function

Im currently trying to implement a c++ program which compares the number of swaps and comparisons in a variety of different sorting methods. The program appears to be working perfectly for all sorting methods (selection sort, insertion sort) except quicksort which only outputs a comparison and swap count of 0 no matter the data size or order of the list. Ive included the full program below. The quicksort function is definitely working its only the counting element which isn't which is strange since it uses external compare and swap functions which are meant to increment the appropriate counter each time they are called. Any help is greatly appreciated.
#include <cstdlib>
#include <getopt.h>
#include <iostream>
#include <string>
#include<limits>
using namespace std;
unsigned long long comparisons = 0;
unsigned long long swaps = 0;
bool comp_less(int a, int b){
++comparisons;
if ( comparisons == std::numeric_limits<unsigned long long>::max() )
{
std::cout << "Number of comparisons reached max value. Resetting it 0.\n";
swaps = 0;
}
return a < b;
}
void swap(int& a, int& b)
{
++swaps;
if ( swaps == std::numeric_limits<unsigned long long>::max() )
{
std::cout << "Number of swaps reached max value. Resetting it 0.\n";
swaps = 0;
}
int t = a;
a = b;
b = t;
}
void selectionSort(int *first, int *last)
{
for(int *i = first; i < (last - 1); ++i){
int *min = i;
for(int *j = i + 1; j < last; ++j){
if(comp_less(*j, *min)){
min = j;
}
}
swap(*i, *min);
}
}
void insertionSort(int* first, int* last)
{
for (int *i = first + 1; i < last; ++i)
{
int temp = *i;
int *j;
for (j = i; j > first && comp_less(temp, *(j - 1)); --j)
{
swap(*j, *(j - 1));
}
*j = temp;
}
}
int *partition(int *first, int *last)
{
int *pivot = last - 1;
int *i = first;
int *j = last - 1;
for (;;)
{
while (comp_less(*i, *pivot) && i < last)
{
++i;
}
while (*j >= *pivot && j > first)
{
--j;
}
if (i >= j)
break;
swap(*i, *j);
}
swap(*(last - 1), *i);
return i;
}
void quickSort(int* first, int* last) {
{
if ((first - last) <= 1)
return;
int *pivot = partition(first, last);
quickSort(first, pivot);
quickSort(pivot + 1, last);
}
}
int main(int argc, char** argv)
{
string algorithm = "selection";
string dataset = "random";
for (int c; (c = getopt(argc, argv, "ravqsin")) != -1;) {
switch (c) {
case 'r':
dataset = "random";
break;
case 'a':
dataset = "sorted";
break;
case 'v':
dataset = "reverse";
break;
case 'q':
algorithm = "quicksort";
break;
case 's':
algorithm = "selection";
break;
case 'i':
algorithm = "insertion";
break;
case 'n':
algorithm = "none";
break;
}
}
argc -= optind;
argv += optind;
const int size = argc > 0 ? atoi(argv[0]) : 10000;
int* data = new int[size];
if (dataset == "sorted") {
for (int i = 0; i < size; ++i) {
data[i] = i;
}
}
else if (dataset == "reverse") {
for (int i = 0; i < size; ++i) {
data[i] = size - i - 1;
}
}
else if (dataset == "random") {
for (int i = 0; i < size; ++i) {
data[i] = rand() % size;
}
}
if (algorithm == "quicksort") {
quickSort(data, data + size);
}
else if (algorithm == "selection") {
selectionSort(data, data + size);
}
else if (algorithm == "insertion") {
insertionSort(data, data + size);
}
else if (algorithm=="none"){
cout<< "Oops!" <<'\n';
exit(1);
}
cout << "OK" << '\n';
cout << "Algorithm: " << algorithm << '\n';
cout << "Data set: " << dataset << '\n';
cout << "Size: " << size << '\n';
cout << "Swaps: " << swaps << '\n';
cout << "Comparisons: " << comparisons << '\n';
return 0;
}
In your quickSort function, change
if ((first - last) <= 1)
to
if ((last - first) <= 1)

Find substring in string from the end

I need to find position of string in substring. Scan has to begin from the end. For example:
findch(L"asdhuifdsahdfasasd", L"asd");
return 16 instead of 1
Here is my function:
int findchr(LPCWSTR T, LPCWSTR P)
{
int n = lstrlenW(T);
int m = lstrlenW(P);
for (int i = 0; i <= n - m; ++i) {
int j = 0;
while (j < m && T[i + j] == P[j]) {
++j;
}
if (j == m) {
return i;
}
}
return -1;
}
You can try using std::string::rfind which does exactly what you want:
Finds the last substring equal to the given character sequence.
Then you can have something like this:
#include <string>
#include <iostream>
std::string::size_type reverse_find(std::string const& str, std::string const& substr) {
return str.rfind(substr);
}
int main() {
auto first = reverse_find("asdhuifdsahdfasasd", "asd");
if (std::string::npos != first) {
std::cout << first << std::endl; // 15
}
auto second = reverse_find("asdhuifdsahdfasasd", "z");
if (std::string::npos != second) {
std::cout << second << std::endl; // won't be outputted
}
return 0;
}
Demo
Above reverse_find function returns 15 because indices start at 0.
int findchr(LPCWSTR str, LPCWSTR substr)
{
int n = lstrlenW(str);
int m = lstrlenW(substr);
for (int i = n; i >= m - n; --i) {
int j = 0;
while (j < m && str[i + j] == substr[j]) {
++j;
}
if (j == m) {
return i;
}
}
return -1;
}