I'm trying to find the sum of the numbers in a char array.
My code works for most cases. Example : a=dasn344wee22ee, the output is:366 - which is good
But when my char is,for example : andre54e5 the output should be 59, but the program displays: 108.
Can anybody tell me what the issue is?
#include <iostream>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
using namespace std;
int getnr(char a[], int i, int j)
{
int counter = 0;
char sir[1000];
for (int x = i; x<j; x++)
{
sir[counter] = a[x];
counter++;
}
return atoi(sir);
}
int main()
{
char a[1000];
int s = 0, inceput, finals;
cin.getline(a, 255);
for (int i = 0; i<strlen(a); i++)
{
if (isdigit(a[i]) )
{
if (i == strlen(a) - 1)
{
s += getnr(a, i, strlen(a));
}
for (int j = i + 1; j<strlen(a); j++)
{
if (!isdigit(a[j]) || j == strlen(a) - 1)
{
s += getnr(a, i, j + 1);
i = j;
break;
}
}
}
}
cout << s;
return 0;
}
In your function int getnr(char a[], int i, int j), you forgot to null-terminate string sir, such that atoi(sir) might yield a garbage value (actually the behaviour is undefined). The following should help:
int getnr(char a[], int i, int j)` {
...
sir[counter] = '\0';
return atoi(sir);
}
The problem is that getnr() doesn't add a null terminator to the sir array, so you're getting undefined behavior when you call atoi(sir).
int getnr(char a[], int i, int j)
{
int counter = 0;
char sir[1000];
for (int x = i; x<j; x++)
{
sir[counter] = a[x];
counter++;
}
sir[counter] = '\0';
return atoi(sir);
}
The issue is within this part of code:
if (i == strlen(a) - 1)
{
s += getnr(a, i, strlen(a));
}
Specifically, if your last number is a single digit (which it is), it will always return junk.
So, I would change to only convert the single char of the char array as a digit and at it to the int s.
Edit:
For some reason when doing s+= a[i], I return junk.
But, doing the following, does the trick:
if (i == strlen(a) - 1)
{
string x;
x[0] = a[i];
int l = stoi(x);
s += l;
}
I know that there's a much more effective way, but I'm not sure why s+= a[i] itself returns false numbers.
Related
I have been practicing median search algorithm, and this is what I wrote-
#include <iostream>
#include <stdlib.h>
using namespace std;
int S1[10] = { 0 };
int S2[1] = { 0 };
int S3[10] = { 0 };
int mediansearch(int A[], int k, int size)
{
int ran = rand() % size;
int i = 0;
int a = 0;
int b = 0;
int c = 0;
for (i = 0; i < size; i++)
{
if (A[ran] > A[i])
{
S1[a] = A[i];
a++;
}
else if (A[ran] == A[i])
{
S2[b] = A[i];
b++;
}
else
{
S3[c] = A[i];
c++;
}
}
if (a <= k)
{
return mediansearch(S1, k, a);
}
else if (a + b <= k)
{
return A[ran];
}
else
{
return mediansearch(S3, k - a - b, c);
}
}
int main()
{
int arr[] = { 6, 5, 4, 8, 99, 74, 23 };
int n = sizeof(arr) / sizeof(arr[0]);
int x = mediansearch(arr, 5, n);
cout << "5th smallest is:" << x << endl;
}
And I have been getting output as-
Process returned -1073741676 (0xC0000094) execution time : 1.704 s
So, what am I doing wrong? Any kind of help will be appreciated.
There are a few issues with this code, the first one being the naming of variables.
I suggest you choose more significative names in the future, because good naming is fundamental when someone else has to understand your code and your ideas.
Another thing is that the arguments of are in a counterintuitive order because the pair related to the array are separated by the index you want to look for.
I'd write int mediansearch(int A[], int size, int k)
Here the comparisons are reversed, k should be less than rather than greater than equal a
if (a <= k) // (k < a)
{
return mediansearch(S1, k, a);
}
else if (a + b <= k) // (k < a + b)
{
return A[ran];
}
else
{
return mediansearch(S3, k - a - b, c);
}
The other thing is that you're sharing S1, S2, and S3 among all the recursive calls and that causes some error that I wasn't able to identify, maybe someone commenting will help me out.
However, I suggest you read this article that explains in detail the procedure you're trying to implement: https://rcoh.me/posts/linear-time-median-finding/
It's python, but it can be easily ported to C/C++, and in fact that's what I did.
#include <iostream>
#include <stdlib.h>
#include <assert.h>
#include <time.h>
using namespace std;
int medianSearch(int A[], int size, int k)
{
int *lows = (int *)calloc(size, sizeof(int));
int lowsLen = 0;
int *highs = (int *)calloc(size, sizeof(int));
int highsLen = 0;
int *pivots = (int *)calloc(size, sizeof(int));
int pivotsLen = 0;
int median;
int pivot;
int i;
if (size == 1)
return A[0];
// Other ways of randomly picking a pivot
// pivot = 0;
// pivot = size-1;
// pivot = size/2;
assert(size > 0);
pivot = rand() % size;
for (i = 0; i < size; ++i)
{
if (A[i] < A[pivot])
{
lows[lowsLen] = A[i];
lowsLen++;
}
else if (A[i] > A[pivot])
{
highs[highsLen] = A[i];
highsLen++;
}
else
{
pivots[pivotsLen] = A[i];
pivotsLen++;
}
}
if (k < lowsLen)
median = medianSearch(lows, lowsLen, k);
else if (k < lowsLen + pivotsLen)
median = A[pivot];
else
median = medianSearch(highs, highsLen, k - lowsLen - pivotsLen);
free(lows);
free(highs);
free(pivots);
return median;
}
int compare(const void *a, const void *b)
{
return ( *(int *)a - *(int *)b );
}
int medianSorted(int A[], int size, int k)
{
qsort(A, size, sizeof(int), compare);
return A[k];
}
#define N 1000
int main()
{
int arr[N];
int brr[N];
int n = sizeof(arr) / sizeof(arr[0]);
int k = 200;
int x;
int y;
for (int i = 0; i < n; ++i)
arr[i] = brr[i] = rand();
x = medianSearch(arr, n, (k-1)%n);
y = medianSorted(brr, n, (k-1)%n);
string suffix;
switch (k % 10)
{
case 1: suffix = "st"; break;
case 2: suffix = "nd"; break;
case 3: suffix = "rd"; break;
case 4:
case 5:
case 6:
case 7:
case 8:
case 9:
case 0: suffix = "th"; break;
}
cout << k << suffix << " smallest is: " << x << endl;
cout << k << suffix << " smallest is: " << y << endl;
}
https://onlinegdb.com/HJc2V6Lbu
d[i] = char(c[i]);
This is not working for me in the below example.
I need my output to be converted to its character values, but after using char(int), its still giving output using the int datatype only.
#include <bits/stdc++.h>
using namespace std;
int main()
{
string str;
cin>>str;
int size=str.size();
int len=0;
if (size % 2 == 0)
{
len=size/2;
}
else
{
len=(size/2)+1;
}
int a[len],b[len],c[len],d[len],x,y;
int i=0,j=size-1;
while(i<len)
{
x=(int)str[i];
y=(int)str[j];
if (i == j)
{
a[i]=x;
}
else
{
a[i]=x+y;
}
b[i]=a[i]%26;
c[i]=x + b[i];
d[i]=char(c[i]);
cout<<"l : "<<d[i]<<endl;
i++;
j--;
}
return 0;
}
Your code fails because you are storing the values in an int[] array. d[i]=char(c[i]); is useless because all you are doing is converting an int to a char back to an int again. You are then outputting the array values as-is as int values instead of converting them back to actual char values.
Try something more like this instead:
#include <vector>
#include <string>
using namespace std;
int main()
{
string str;
cin >> str;
int size = str.size();
int len = (size / 2) + (size % 2);
// VLAs are a non-standard compiler extension are are not portable!
// Use new[] or std::vector for portable dynamic arrays...
//
// int a[len], b[len], c[len];
// char d[len];
//
std::vector<int> a(len), b(len), c(len);
std::vector<char> d(len);
int x, y, i = 0, j = (size-1);
while (i < len)
{
x = (int) str[i];
y = (int) str[j];
if (i == j)
{
a[i] = x;
}
else
{
a[i] = x + y;
}
b[i] = a[i] % 26;
c[i] = x + b[i];
d[i] = (char) c[i];
cout << "l : " << d[i] << endl;
++i;
--j;
}
return 0;
}
I have two algorithms for printing the permutations of a string
Here is the 1st one.
#include<iostream>
int fact(int f)
{
if(f == 0)
return 1;
return f*fact(f-1);
}
int main()
{
char A[] = "abc";
int size = strlen(A);
int per = fact(size); // per is the number of permutations we will get
int j = 0; // j is the index of the elements of A we will swap
// this is the algorithm
for(int i=1;i<=per;i++)
{
cout << A << endl;
if(j == size-1)
j = 0;
swap(A[j],A[j+1]);
j++;
}
return 0;
}
Here is the 2nd one.
// C program to print all permutations of the input string
#include <stdio.h>
#include <string.h>
// Function to swap values at two pointers
void swap(char *x, char *y)
{
char temp = *x;
*x = *y;
*y = temp;
}
// Function to print permutations of string
This function takes three parameters:
1. String
2. Starting index of the string or sub-string
3. Ending index of the string
void permute(char *a, int l, int r)
{
int i;
if (l == r)
printf("%s\n", a);
else
{
for(i = l; i <= r; i++)
{
swap((a+l), (a+i));
permute(a, l+1, r);
swap((a+l), (a+i)); //backtrack to retain the original string
}
}
}
int main()
{
char str[50];
gets_s(str);
int n = strlen(str);
permute(str, 0, n-1);
return 0;
}
According to me...both should perform the same....and they in fact do....but only for small inputs..eg: "abc" , "abcd".But when the string becomes large..eg:
"abcdefghi"..the first one takes a hell of a lot of time as opposed to second one.
Im having a tough time analysing why the second one performs better than the first.Can anybody explain this to me?
Just add below statement in you main function before you start printing:
std::cout.sync_with_stdio(false);
This disables the synchronization with the standard C-streams for every IO operation.
Read more about it here
I try to translate a code from c++ to c but the program didnt work properly.
This is the c++ code
#include <iostream>
#include <limits.h>
using namespace std;
int CoinChangeDynamic(int jumlah, int d[], int size, int C[], int s[])
{
C[0] = 0;
for(int j = 1; j <= jumlah; j++) {
C[j] = INT_MAX;
for(int i = 0; i < size; i++) {
if(j >= d[i] && 1 + C[j-d[i]] < C[j] ) {
C[j] = 1 + C[j-d[i]];
// i-th denomination used for the amount of j
s[j] = i;
}
}
}
return C[jumlah];
}
int main()
{
int d[] = {1, 5, 10, 25, 50, 100,500,1000};
int jumlah ;//= 67;
cout <<"Masukan Jumlah Nilai Koin = ";cin >>jumlah;
int size = sizeof(d)/sizeof(d[0]);
int *C = new int[jumlah+1];
int *s = new int[jumlah+1];
int ans = CoinChangeDynamic(jumlah, d, size, C, s);
cout << "Minimal Koin = " << ans << endl;
cout << "Menggunakan Koin: " ;
int k = jumlah;
while(k) {
cout << d[s[k]] << " ";
k = k - d[s[k]];
}
delete[] C;
delete[] s;
return 0;
}
And this is my translation
#include <stdio.h>
#include <limits.h>
int CoinChangeDynamic(int jumlah, int d[], int size, int C[], int s[])
{
//variabel
int j, i;
//program
C[0] = 0 ;
for(j = 1; j <= jumlah; j++) {
C[j] = INT_MAX;
for(i = 0; i < size; i++) {
if(j >= d[i] && 1 + C[j-d[i]] < C[j] ) {
C[j] = 1 + C[j-d[i]];
// i-th denomination used for the amount of j
s[j] = i;
}
}
}
return C[jumlah];
}
int main()
{
//variabel
int d[] = {1, 5, 10, 25, 50, 100,500,1000};
int jumlah;
printf ("Masukan Jumlah Nilai Koin = "); scanf ("%i", &jumlah);
int size = sizeof(d)/sizeof(d[0]);
int *C = (int *) malloc(sizeof(jumlah+1));
int *s = (int *) malloc(sizeof(jumlah+1));
//program
int ans = CoinChangeDynamic(jumlah, d, size, C, s);
printf ("Minimal Koin = %i \n", ans);
printf ("Menggunakan Koin: ") ;
int k = jumlah;
while(k)
{
printf (" %i ", d[s[k]]);
k = k - d[s[k]];
}
free (C);
free (s);
return 0;
}
But the program didn't work properly like the C++ code.
is there someone who can help me
This will help:
int *C = (int *) malloc((jumlah+1)*sizeof(int));
int *s = (int *) malloc((jumlah+1)*sizeof(int));
You've mistranslated the calls to new.
NB: Purists don't like the cast of malloc to (int *). However for clarity of what is causing the error I've made the minimal changes to correct it.
Also, remember that both C++ iostreams and C FILEs are buffered and you probably need to flush them.
BTW, you C++ code is not genuine C++, you should use containers in it.
To flush a C++ iostream, use std::flush. Notice that std::endl is also flushing (after emitting the newline).
To flush C FILEs, use fflush. Notice that stdout is often (but not always) line buffered, so ending printf control strings with a newline \n is preferable.
I'm working on a Random Quick Sort program in C++, but for some reason, by program is segfaulting, and I'm a little lost as to why.
I'm pretty sure it has something to do with my hoarePartition function, getting caught in a while loop, but I'm not really sure where the problem is.
Any help on solving this problem would be very helpful!
#import <iostream>
#import <cstdlib>
#import <random>
#import <time.h>
#include <ctime>
#include <boost/timer.hpp>
void swap(int& first, int& second)
{
int temp = first;
first = second;
second = temp;
}
int hoarePartition(int* array, int leftIndex, int rightIndex)
{
int partition = array[leftIndex];
int i = leftIndex;
int j = rightIndex + 1;
while (i < j)
{
while (array[i] < partition && i <= j)
{
i = i + 1;
}
while (array[j] > partition && j > i)
{
j = j - 1;
cout << j << endl;
}
swap(array[i], array[j]);
}
swap(array[i], array[j]);
swap(array[leftIndex], array[j]);
return j;
}
void randomQuickSort(int* array, int leftIndex, int rightIndex)
{
if (leftIndex < rightIndex)
{
int q = rand() % (rightIndex - leftIndex) + leftIndex;
swap(array[leftIndex], array[q]);
int s = hoarePartition(array, leftIndex, rightIndex);
randomQuickSort(array, leftIndex, s-1);
randomQuickSort(array, s+1, rightIndex);
}
}
int main(int argc, char** argv)
{
srand(time(NULL));
int size = atoi(argv[1]);
int* array = new int[size];
for (int i = 0; i < size; ++i)
{
array[i] = (100.0 * rand()) / RAND_MAX;
}
boost::timer t;
randomQuickSort(array, 0, size);
std::cout << t.elapsed() << endl;
delete[] array;
return 0;
}
You call randomQuickSort with rightIndex=size, which is one bigger than the index of the last element in the array. Then, passing this to hoarePartition, you initialize j to rightIndex+1, and then (in the second inner while loop) access array[j].
You are accessing size+1 in your hoarePartition function. Which is 2 elements out of range for your array, resulting in a index out of range exception.