Execution time of very short function - search

I am required to display the execution time of some searching algorithms. However, when I use start/end_t = clock(), it always displays 0.00000 due to low precision (even with double-type)
Please tell me how to display those running times.
int LinearSearch (int M[], int target, int size)
{
int k = 0;
for (k=0; k<size; k++)
{
if(M[k]==target)
{
return k;
}
//else return -1;
}
}
int LinearSentinelSearch (int M[],int target, int size)
{
int k = 0;
M[size]=target;
while (M[k] != target)
k++;
return k;
}
int binSearch(int List[], int Target, int Size)
{
int Mid;
int low = 0;
int high = Size -1;
int count=0;
int a;
while( low <= high)
{
Mid = (low + high) / 2;
if(List[Mid] == Target) return Mid;
else if( Target < List[Mid] )
high = Mid - 1;
else
low = Mid + 1;
}
return -1;
}

You can calculate the mean execution time by simply executing the algorithm multiple times N and then divide the total time by N. Using your binSearch as an example:
int i;
clock_t start, end;
start = clock();
for (i = 0 ; i < 1000 ; i++) {
binSearch(/* your actual parameters here */);
}
end = clock();
printf("Mean ticks to execute binSearch: %f\n", (end - start) / 1000.0);

Related

"Program has triggered a breakpoint" while free memory malloced

When I free memory, the error "Program has triggered a breakpoint" occur. Check the code below, I wonder where is wrong ?
int SSavep(char *visited, int t, int n, int m)
{
int* map = (int*)malloc(m*n * sizeof(int));
int* q = (int*)malloc(m*n * sizeof(int));
int count = 0, cur = 0;
int begin = 0, end = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
//set value for map
}
}
..........
if (t >= map[end]) {
free(map);
free(q);
return 0;
}
else{
free(map);
free(q);
return -1;
}
}
the entire code is as below:
static int dir[4][2] = { {0,1},{0,-1},{1,0},{-1,0} };
int SSavep(char *visited, int t, int n, int m)
{
int* map = (int*)malloc(m*n * sizeof(int));
int* q = (int*)malloc(m*n * sizeof(int));
int count = 0, cur = 0;
int begin = 0, end = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (visited[i*n + j] == '.')
map[i*n + j] = 0;
else if (visited[i*n + j] == '*')
map[i*n + j] = -1;
else if (visited[i*n + j] == 'p') {
map[i*n + j] = -12;
end = i*n + j;
}
else {
map[i*n + j] = -9;
begin = i*n + j;
}
}
}
q[count++] = begin;
while (cur < count && q[cur] != end) {
int i = q[cur] / n;
int j = q[cur] % n;
for (int k = 0; k < 4; k++) {
int ni = i + dir[k][0];
int nj = j + dir[k][1];
if (ni < 0 || ni >= m || nj < 0 || nj >= n || map[ni*n + nj]>0 || map[ni*n + nj] == -1)
continue;
map[ni*n + nj] = map[i*n + j] + 1;
q[count++] = ni*n + nj;
}
cur++;
}
if (map[end] > 0 && t >= map[end]) {
free(map);
free(q);
return 0;
}
else{
free(map);
free(q);
return -1;
}
}
You are getting error on >> free(q);
for m=n=4
int* q = (int*)malloc(m*n * sizeof(int));
q == [m*n*sizeof(int)] == 4*4*4 == 64 bytes == int[16];
Because you wrote beyond the address space reserved for pointer variable 'q'.
check 'count' variable before free(q). I've got 1208, called with:
char* visited = new char[100 * 100];
memset(visited, 0, 10000);
int res = SSavep(visited, 0, 4, 4);
Btw this algo looks alot like some path finding examining neighboring cells on map and assigning weights, right? If so there are many opensource solutions, why not using them instead of reinventing the wheel? There are links to opensource solutions on wiki Path Finding page:
https://en.wikipedia.org/wiki/Pathfinding
check the bottom of the page for links.

Getting segmentaition fault with subset dp problem

Given a set of numbers, check whether it can be partitioned into two subsets such that the sum of elements in both subsets is same or not
I am getting segmentation fault in C++(g++ 5.4) with a this problem.
This is where i submitted my solution in C++
https://practice.geeksforgeeks.org/problems/subset-sum-problem/0
I am checking if the array can be divided into two parts with equal sum. So I am just checking if there exists a subset with sum equal to half the sum of the array
I have implemented the below logic with dynamic programming
Let dp[i][j] denote yes or no whether a subset with sum j is possible to form with elements in the range [0, i](both inclusive) where i is 0-based index. I have done nothing new with this traditional problem. But I am getting segmentation fault. The program is giving correct output for small test cases. What mistake have I made
I haven't used any comments because I have done nothing new. Hope it is understandable.
#include <iostream>
#include <bits/stdc++.h>
#include<cstdio>
#define ll long long int
using namespace std;
bool isVowel(char c){
return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';
}
bool isLower(char c){
return 97 <= c && c <= 122;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
cout << setprecision(10);
ll t, n;
cin >> t;
while (t--) {
cin >> n;
ll a[n];
ll sum = 0;
for (ll i = 0; i < n; i++) {
cin >> a[i];
sum += a[i];
}
if (sum % 2) {
cout << "NO" << '\n';
continue;
}
sum /= 2;
ll dp[n][sum + 1];
for (ll i = 0; i < n; i++) {
for(ll j = 0; j < sum + 1; j++) {
dp[i][j] = 0;
}
}
for (ll i = 0; i < n; i++) {
dp[i][a[i]] = 1;
dp[i][0] = 1;
}
for (ll i = 1; i < n; i++) {
for (ll j = 1; j < sum + 1; j++){
if (j - a[i] > 0) {
dp[i][j] = dp[i - 1][j - a[i]];
}
dp[i][j] |= dp[i - 1][j];
}
}
cout << (dp[n - 1][sum] ? "YES" : "NO") << '\n';
}
}
The segmentation fault is due to
ll dp[n][sum + 1];
Even though the constraints say 1 <= N<= 100, 0 <= arr[i]<= 1000, the test cases used are probably much larger, so ll dp[n][sum + 1] will end up taking some serious stack memory, use
bool dp[n][sum + 1];
It should work fine.
On a side note, avoid using ll randomly, use them according to the constraints.

Having trouble with pointers in C++

I am trying to access an array from inside of a function, but I get the
"Error C2065 'i': undeclared identifier." I know that I am making a mistake with the pointer. I was able to pull information from the array in the function below the one I'm having issues with, so I'm not sure why I am unable to do the same thing here. Thank you for your time.
#include <iostream>
#include <cmath>
using namespace std;
double mean(int size, int* numbers);
double sDeviation(int numOfScores, int average, int* scores);
int histogram(int numOfScores, int* scores); //<<<This is what I'm having trouble with
int main()
{
int count = 0;
int scores[100];
while (true)
{
int scoreToBeEntered;
cout << "Please enter a score: ";
cin >> scoreToBeEntered;
if(scoreToBeEntered == NULL)
cout << "No value entered" << endl;
else if(scoreToBeEntered != -1)
scores[count++] = scoreToBeEntered;
else
break;
}
for(int i = 9; i >= 0; i--)
cout << i << "|" << endl;
cout << "SD: " << sDeviation(count, mean(count, scores), scores) << endl;
system("pause");
return 0;
}
int histogram(int numOfScores, int* scores)//this is where the issue starts
{
int* bins = new int[10];
for(int i = 0; i < numOfScores; i++);
if(scores[i] >= 90) //<<<<This is the undeclared "i"
{
bins[9]++;
}
}
double sDeviation(int numOfScores, int average, int* scores)
{
double deviation = 0;
for (int i = 0; i < numOfScores; i++)
deviation += pow(scores[i] - average, 2);
return sqrt(deviation / numOfScores);
}
double mean(int size, int* numbers)
{
double sum = 0;
for (int i = 0; i < size; i++)
sum += numbers[i];
return sum / size;
}

time command shows user time greater than real time

I have more or less the same question as
linux time command resulting real is less than user
and
user time larger than real time
but can't post a comment on those questions.
When I run the non-multi-threaded program given below, I occasionally get user time greater than real time with both /usr/bin/time and bash's builtin time. I don't see anything that might use a different core. Is rand() somehow the culprit? How? Thanks!
#include <stdio.h>
#include <stdlib.h>
#define N 100
#define MM_MAX 50000
int
main(int ac, char **av)
{
unsigned int i, j, k, n;
int A[N][N], B[N][N], C[N][N];
if (ac != 2) {
fprintf(stderr, "Usage: matmul <seed>");
exit(1);
}
srand((unsigned int) atoi(av[1]));
for (n = 0; n < atoi(av[1]); n++) {
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++) {
A[i][j] = rand() % MM_MAX;
B[i][j] = rand() % MM_MAX;
}
}
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++) {
C[i][j] = 0;
for (k = 0; k < N; k++) {
C[i][j] += A[i][k] * B[k][j];
}
printf("%7d ", C[i][j]);
}
putchar('\n');
}
}
return 0;
}

Will this cause a race condition?

I made a program in C that will create 10 threads, and inside each thread add 10,000 integers [0-100]. When the thread ends it adds the partial sum to the total sum. It is unlikely that 2 threads will end at the exact same time, but if they do will there be a problem?
#include <stdio.h>
#include <time.h>
#include<pthread.h>
pthread_t pid[10];
int i = 0;
int sum;
void* partial(void *arg)
{
int partial = 0;
pthread_t id = pthread_self();
int k = 0;
for(k = 0; k < 10000; k++) {
int r = rand() % 101;
partial += r;
}
sum += partial;
return NULL;
}
main() {
srand(time(NULL));
clock_t begin,end;
double timeSpent;
begin = clock();
while(i < 10) {
pthread_create(&(pid[i]), NULL, &partial, NULL);
printf("\n Thread created successfully\n");
i++;
}
sleep(10);
end = clock();
timeSpent = (double)(end-begin);
printf("\n Time taken: %f", timeSpent);
printf("\n sum: %d \n", sum);
return 0;
}
Yes, without locking with mutexes there is (an unlikely but possible) chance of a race condition.
If two threads do finish at the same time they will try to modify the common resource (sum) at the same time and that will lead to the common resource not being updated properly, since both threads will "race" to read the value of sum when incrementing it in the statement sum+=partial.

Resources