Extract integer from string - c++

I am new to C++ strings and vectors and would like to know what the issue with this code is, I was provided a vector input of strings in the form "a/b+c/d" and had to print a vector in "e/f" for where a, b, c, d are integers and e/f is in the reduced fraction form. Please help as I want to learn concept of strings properly and shift to C++ from C
vector< string > reducedFractionSums(vector < string > expressions) { int a[4]={0,0,0,0}; vector < string > results;
vector < string > results;
for(int i=0;i<expressions.size();i++){
int tmp=0;
int count=0;
for(int j=0;j<expressions[i].length();j++){
if(isdigit(expressions[i][j])){
tmp=expressions[i][j];
tmp=tmp-48;
a[count]=a[count]*10 + tmp;
}
else
count++;
}
int min=a[0];
for(int i=1;i<4;i++){
if(a[i]<min){
min=a[i];
}
}
int e,f,g=1; //g for GreatestCommonDivisor
f=a[1]*a[3];
e=(a[0]*a[3])+(a[2]*a[1]);
for(int i=1;i<=min;i++){
if(e%i==0 && f%i==0){
g=i;
}
}
e=e/g;
f=f/g;
results.push_back(e + "/" + f);
}
return results;
}
int main(){
vector < string > input;
vector < string > output;
int t;
cin>>t;
while(t--){
string s;
cin>>s;
input.push_back(s);
}
output=reducedFractionSums(input);
for(int i = 0;i<output.size();i++){
cout<<output.at(i);
}
return 1;
}

Use std::stoi to convert Single integer from string, std::to_string to convert integer to string and __gcd to calculate GCD which is defined in algorithm header file to find reduced form of fraction.
#include <bits/stdc++.h>
using namespace std;
vector<int>reduced_fraction(vector<int>v) // Function to find reduced fraction form
{
int num = v[0]*v[3]+v[1]*v[2]; // numerator = a*d+b*c
int den = v[1]*v[3]; // denominator = b*d
int gcd = __gcd(num,den); // gcd = gcd(greatest common divisor) of numerator and denominator
num/=gcd; // num/den = e/f(reduced fraction)
den/=gcd;
vector<int>frac;
frac.push_back(num);
frac.push_back(den);
return frac;
}
int main() {
string s,st;
vector<string>fr; // vector to store strings of form a/b+c/d
int n=2; //Number of Strings
for(int i=0;i<n;i++)
{
cin>>s;
fr.push_back(s);
}
for(int i=0;i<n;i++)
{
s=fr[i];
vector <int>v,red_frac;
while(s.compare("")!=0)
{
if(s.at(0)=='/' || s.at(0)=='+')
s.erase(0,1);
else
{
st=to_string(stoi(s)); // fetch integer from string
v.push_back(stoi(s));
s=s.erase(0,st.length()); // remove integer from string
}
}
red_frac=reduced_fraction(v); // red_frac->reduced fraction
cout<<red_frac[0]<<"/"<<red_frac[1]<<endl;
}
return 0;
}
Input:
14/2+9/6
8/4+5/4
Output:
17/2
13/4
Ideone Link

Related

Why is the error- "AddressSanitizer: allocator is out of memory trying to allocate 0x11780d838 bytes"

Why is this code giving allocation error?Question is -Given a string,s , let U be the set of weights for all possible uniform contiguous substrings of string . I have to answer n queries, where each query consists of a single integer . For each query, print Yes on a new line if found; otherwise, print No .
The weight of a string is the sum of the weights of all the string's characters. For example:
for apple= 1+ 16+16+12 + 5
A uniform string consists of a single character repeated zero or more times. For example, ccc and a are uniform strings, but bcb and cd are not.
Example : if string s = abccddde
then possible uniform string U are
a =1; b=2;c=3;cc=3+3=6; d=4;dd=4+4=8; ddd = 4+4+4=12; e=5;
and if I input a query vector { 2,6,7,9,5}
output should be yes if found else no.
OUTPUT= {YES, YES,NO,NO,YES }
#include <bits/stdc++.h>
using namespace std;
void search(vector<int> v,int o,int item)
{
int low=0;int flag=0;
int high=o;
while(low<high)
{ int mid= (low+high)/2;
if(v[mid]==item)
flag=1;
else if( v[mid]<item)
{
low=mid+1;
}
else
high=mid-1;
}
if(flag==0)
cout<<"Yes"<<endl;
else
cout<<"No"<<endl;
}
// Complete the weightedUniformStrings function below.
void weightedUniformStrings(string s, vector<int> queries)
{
int n=s.length();int o;
int arsize= queries.size();
vector<int> v;
int l;int flag=0;
v[0]=s[0]-'a'+1;
for(int i=1;i<n;i++)
{
if(s[i]==s[i-1])
{
v[i]=(s[i]-'a'+1)+v[i-1];
}
else
v[i]= s[i]-'a'+1;
}
o= v.size();
for(int k=0;k<arsize;k++)
{
int it= queries[k];
search(v,o,it);
}
}
int main()
{
string s;
getline(cin, s);
int queries_count;
cin >> queries_count;
vector<int> queries(queries_count);
for (int i = 0; i < queries_count; i++) {
cin >> queries[I];
}
weightedUniformStrings(s, queries);
return 0;
}

how to store float value in the array in C++

I am getting an integer value as my output but i want it to be a float value.I am not able to figure out the problem in my code.
Here is the code.
#include <iostream>
#include <vector>
#include <bits/stdc++.h>
using std::vector;
using namespace std;
double get_optimal_value(int n, int capacity, vector<int> weights, vector<int> values) {
double value = 0.0,p=0.0;
float max=0.0;
float m=n,i,k,j,t;
// write your code here
vector<double> a(m);
for(i=0;i<m;i++)
{
p=(values[i]/weights[i]);
a.push_back(p);
}
sort(a.begin(), a.end(), greater<double>());
for(j=0;j<m;j++)
{
for(k=0;k<m;k++)
{
if(a[j]==values[k]/weights[k])
{
if(weights[k]<=capacity){
value= value + values[k];
capacity=capacity-weights[k];
if(capacity==0)
{
return value;
}
}else if(weights[k]>capacity){
value=value + a[j]*capacity;
return value;
}
}
}
}
return value;
}
int main() {
int n;
int capacity;
std::cin >> n >> capacity;
vector<int> values(n);
vector<int> weights(n);
for (int i = 0; i < n; i++) {
std::cin >> values[i] >> weights[i];
}
double optimal_value = get_optimal_value(n,capacity, weights, values);
std::cout.precision(10);
std::cout << optimal_value << std::endl;
return 0;
}
INPUT
1 10
500 30
output
160
but i want the answer to be a double or a float value
and the
Expected Output is
166.667
could you guys help me out.
In expressions like this
p=(values[i]/weights[i]);
or like this
if(a[j]==values[k]/weights[k])
in the right hand side there is used the integer arithmetic.
To get a float result you should cast one of operands to the type double as for example
p = static_cast<double>( values[i] ) / weights[i];
or
if ( a[j] == static_cast<double>( values[k] ) / weights[k] )
I looked over your code and I'm pretty sure get_optimal_value can only return integer values. For instance, the line p=(values[i]/weights[i]); loses a floating point value. I highly recommend using a debugger to closely follow your program and find out where it went wrong.

Getting variables values from a .txt file in C++

I am writing a CFD solver in C++ but I am in the very beginning. Now I am coding a solver for the linear convection. The math is ok, working well, but I need to write also a code for reading variables from a .txt file.
My code is:
//Code for solving the convection linear equation from Navier-Stokes
#include <iostream>
using namespace std;
int main()
{
float endtime=0.3; //simulation time
float dx=0.025; //element size
float xmax=2; //domain size
float c=1; //wave velocity
float C=0.3; //Courant-Friedrich-Lewy number
float dt=C*dx/c; //defining timestep by the Courant equantion
int nx=xmax/dx + 1; //defining number of elements
int nt=endtime/dt; //defining number of time points
float u[nx] = { }; //defining an initial velocity array.
float un[nx] = { };
for(int i = 4; i <= 9; i++) //defining contour conditions
{
u[i] = 2;
}
for(int n=1; n<=nt; n++)
{
std::copy(u, u + nx, un);
for(int i=1; i<=nx; i++)
{
u[i] = un[i] - c*(dt/dx)*(un[i]-un[i-1]);
}
}
for (int i = 0; i <= nx; i++)
{
cout << u[i] << endl;
}
return 0;
}
I need to take these variables values from a .txt, like the end time, element size, etc. Then, I have a .txt called "parameters", which is exactly written like that:
endtime=0.3
dx=0.025
xmax=2
c=1
C=0.3
What's the most effiecient way to get these variables values from this .txt and use it in the code?
Using only standard features:
#include <iostream>
#include <tuple>
using namespace std;
tuple<bool, string, string> read_one_value(istream& in)
{
string name;
if(getline(in, name, '='))
{
string value;
if(getline(in, value))
{
return make_tuple(true, name, value);
}
}
return make_tuple(false, "", "");
}
int main()
{
for(auto val = read_one_value(cin); get<0>(val); val = read_one_value(cin))
{
std::cout << get<1>(val) << " -> " << get<2>(val) << '\n';
}
return 0;
}
This leaves converting from the value string objects to the needed type as an exercise for the reader, and assumes your format of name=value is consistent.

find method giving wrong answer in c++

In the following code we have to first calculate the weights of uniform substrings present in our strings . Uniform sub strings are those which contain just one character like "a" or "aaa". The weight of the character is defined as a-1 b-2......z-26.
After calculating the weights of all the valid uniform substrings we will be given with various queries and we have to check whether the given no. is the array or not.
Here is the link of the code and corresponding output to it:
https://www.ideone.com/pIBPtQ
#include<bits/stdc++.h>
using namespace std;
int main()
{
string s;
cin>>s;
int i=0,j=0,k=0;
int arr[10000];
int c=0;
while(s[i]!='\0')
{
int x=(int)s[i];
x=x-96;
arr[c++]=x;
j=i+1;
int sum=x;
while(s[j]==s[i])
{
sum+=x;
arr[c++]=sum;
j++;
}
i=j;
}
int q;
cin>>q;
for(i=0;i<q;i++)
{
int val;
cin>>val;
bool exists=find(begin(arr),end(arr),val)!=end(arr);
if(exists==true)
cout<<"Yes"<<endl;
else
cout<<"No"<<endl;
}
cout<<"the elements of the array are:"<<endl;
for(i=0;i<c;i++)
cout<<arr[i]<<" ";
return 0;
}
You forgot to initialize arr.
Change
int arr[1000];
to
int arr[1000] = {0};
https://www.ideone.com/wIj4vp
Also x=x-96; should be better written as x -= 'a';.

Summing Large Numbers

I have being doing some problems on the Project Euler website and have come across a problem. The Question asks,"Work out the first ten digits of the sum of the following one-hundred 50-digit numbers." I am guessing there is some mathematical way to solve this but I was just wondering how numbers this big are summed? I store the number as a string and convert each digit to a long but the number is so large that the sum does not work.
Is there a way to hold very large numbers as a variable (that is not a string)? I do not want the code to the problem as I want to solve that for myself.
I was just wondering how numbers this big are summed?
You can use an array:
long LargeNumber[5] = { < first_10_digits>, < next_10_digits>....< last_10_digits> };
Now you can calculate the sum of 2 large numbers:
long tempSum = 0;
int carry = 0;
long sum[5] = {0,0,0,0,0};
for(int i = 4; i >= 0; i--)
{
tempSum = largeNum1[i] + largeNum2[i] + carry; //sum of 10 digits
if( i == 0)
sum[i] = tempSum; //No carry in case of most significant digit
else
sum[i] = tempSum % 1000000000; //Extra digits to be 'carried over'
carry = tempSum/1000000000;
}
for( int i = 0; i < 5; i++ )
cout<<setw(10)<<setfill('0')<<sum[i]<<"\n"; //Pad with '0' on the left if needed
Is there a way to hold very large numbers as a variable (that is not a
string)?
There's no primitive for this, you can use any data structure (arrays/queues/linkedlist) and handle it suitably
I am guessing there is some mathematical way to solve this
Of course! But,
I do not want the code to the problem as I want to solve that for myself.
You may store the digits in an array. To save space and increase performance in the operations, store the digits of the number in base 10^9. so a number
182983198432847829347802092190
will be represented as the following in the array
arr[0]=2092190
arr[1]=78293478 arr[2]=19843284 arr[3]=182983
just for the sake of clarity, the number is represented as summation of arr[i]*(10^9i)
now start with i=0 and start adding the numbers the way you learnt as a kid.
I have done in java, Here I am taking to numbers N1 and N2, And I have create an array of size 1000. Lets take an example How to solve this, N1=12, N2=1234. For N1=12, temp=N1%10=2, Now add this digit with digit N2 from right to Left and store the result into array starting from i=0, similarly for rest digit of N1. The array will store the result but in reverse order. Have a looking on this link. Please check this link http://ideone.com/V5knEd
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception {
Scanner scan=new Scanner(System.in);
int A=scan.nextInt();
int B=scan.nextInt();
int [] array=new int[1000];
Arrays.fill(array,0);
int size=add(A,B,array);
for(int i=size-1;i>=0;i--){
System.out.print(array[i]);
}
}
public static int add(int A, int B, int [] array){
int carry=0;
int i=0;
while(A>0 || B>0){
int sum=A%10+B%10+carry+array[i];
array[i]=sum%10;
carry=sum/10;
A=A/10;
B=B/10;
i++;
}
while(carry>0){
array[i]=array[i]+carry%10;
carry=carry/10;
i++;
}
return i;
}
}
#include<iostream>
#include<fstream>
#include<sstream>
using namespace std;
struct grid{
int num[50];
};
int main()
{
struct grid obj[100];
char ch;
ifstream myfile ("numbers.txt");
if (myfile.is_open())
{
for(int r=0; r<100; r++)
{
for(int c=0; c<50; c++)
{
myfile >> ch;
obj[r].num[c] = ch - '0';
}
}
myfile.close();
int result[50],temp_sum = 0;
for (int c = 49; c>=0; c--)
{
for (int r=0; r<100; r++)
{
temp_sum += obj[r].num[c];
}
result[c] = temp_sum%10;
temp_sum = temp_sum/10;
}
string temp;
ostringstream convert;
convert << temp_sum;
temp = convert.str();
cout << temp_sum;
for(unsigned int count = 0; count < (10 - temp.length()); count++)
{
cout << result[count];
}
cout << endl;
}
return 0;
}
This the best way for your time and memory size :D
#include <iostream >
#include <climits >
using namespace std;
int main()
{
unsigned long long z;
cin >>z;
z=z*(z+1)/2;
C out << z;
return 0;
}