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.
Related
I solved this problem from codeforces: https://codeforces.com/problemset/problem/1471/B. But when I upload it it says memory limit exceeded. How can I reduce the memory usage? I used C++ for the problem. The problem was the following: "You have given an array a of length n and an integer x to a brand new robot. What the robot does is the following: it iterates over the elements of the array, let the current element be q. If q is divisible by x, the robot adds x copies of the integer qx to the end of the array, and moves on to the next element. Note that the newly added elements could be processed by the robot later. Otherwise, if q is not divisible by x, the robot shuts down.
Please determine the sum of all values of the array at the end of the process".
This is the code:
#include <iostream>
#include <cstdlib>
#include <vector>
using namespace std;
int main()
{
vector<int> vec;
vector<int> ans;
int temp;
int t;
cin >> t;
int a = 0;
int n, x;
for(int i=0; i<t; i++){
cin >> n >> x;
while(a<n){
cin >> temp;
a++;
vec.push_back(temp);
}
int q = 0;
while(true){
if(vec[q]%x == 0){
for(int copies=0; copies<x; copies++){
vec.push_back(vec[q]/x);
}
}
else{
break;
}
q++;
}
int sum = 0;
for(int z: vec){
sum += z;
}
ans.push_back(sum);
vec.clear();
a = 0;
}
for(int y: ans){
cout << y << endl;
}
return 0;
}
Thanks.
You don't need to build the array as specified to compute the sum
You might do:
int pow(int x, int n)
{
int res = 1;
for (int i = 0; i != n; ++i) {
res *= x;
}
return res;
}
int compute(const std::vector<int>& vec, int x)
{
int res = 0;
int i = 0;
while (true) {
const auto r = pow(x, i);
for (auto e : vec) {
if (e % r != 0) {
return res;
}
res += e;
}
++i;
}
}
Demo
Consider:
If you find an indivisible number in the original array, you're going to stop before you reach the numbers you have added (so they don't affect the result).
If you add q/x to the array but q/x isn't divisible by x, you're going to stop there when you reach it, if you haven't already stopped earlier. (On the other hand, if q/x is divisible by x, the sum of x copies of q/x is q, so adding them is equivalent to adding q.)
So you don't need to expand the array, you just need to sum the elements and - on the side - keep the sum of all the numbers you would have expanded with until you find one that is not a multiple of x.
Then you either add that to the sum of the array or not, depending on whether you reached the end of the array.
I'm trying to solve fractional knapsack problem, for now logic aside can anyone suggest me or explain me what is happening here? I never seen this runtime-error before, any help would be awesome, thank you.
#include <iostream>
#include <vector>
#include <algorithm>
using std::vector;
bool myfunction(int a, int b){return(a>b);}
double get_optimal_value(int capacity, vector<int> weights, vector<int> values) {
double value = 0.0;
vector<double> prop(weights.size());
for(int i=0;i<=weights.size();i++){
double Pvalue = (weights.at(i))/(values.at(i));
prop.push_back(Pvalue);
}
std::sort(prop.begin(),prop.end(),myfunction);
for(int it =0;it<=values.size();it++){
while(capacity >=prop.at(it)){
value+=prop.at(it);
capacity-=prop.at(it);
}
}
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(capacity, weights, values);
std::cout.precision(10);
std::cout << optimal_value << std::endl;
return 0;
}
Suppose that v is a vector, only elements v[0] to v[v.size() - 1] are available and v[v.size()] is out-of-range.
Therefore,
for(int i=0;i<=weights.size();i++)
and
for(int it =0;it<=values.size();it++)
should be
for(int i=0;i<weights.size();i++)
and
for(int it =0;it<values.size();it++)
(use < instead of <=)
for(int i=0;i<=weights.size();i++)
Will access the array one past the end of it. You need to use < weights.size() because c++ arrays are 0-based.
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.
This question already has answers here:
C++ Multiplying elements in a vector
(3 answers)
Closed 3 years ago.
I have the following vector values: [2, 3, 7].
I want to output the product of the vector, as in 2*3*7 = 42.
I wrote some code for it but it doesn't appear to be working. I am new to C++, so I am not sure how to get the product of the values in a vector given any numeric vector of any size.
#include <bits/stdc++.h>
int main()
{
int n;
cin >> n;
vector<int> vec;
while (n--)
{
int temp;
cin >> temp;
vec.push_back(temp);
}
int total = 1;
total *= vec;
cout << vec << endl;
return 0;
}
Using std::accumulate, one can do
#include <numeric> // std::accumulate
#include <functional> // std::multiplies
const auto total = std::accumulate(vec.cbegin(), vec.cend(), 1, std::multiplies<int>{});
By wrapping into a templated function, the code would be more generic
template<typename Type>
auto product(const std::vector<Type>& vec, Type init)
{
return std::accumulate(vec.cbegin(), vec.cend(), init, std::multiplies<Type>{});
}
and call it with
const auto total = product(vec, /*value to be initialized/ started with*/);
With std, you might use std::accumulate:
int product(const std::vector<int>& v)
{
return std::accumulate(v.begin(), v.end(), 1, std::multiplies<>{});
}
Try multiplying each value inside the vector.
for(std::size_t i=0; i<vec.size(); i++) {
total *= vec[i];
}
Here is what I would do for your example:
#include <iostream>
int main ()
{
int n;
std::cin >> n;
int total = 1;
while(n--) {
int temp;
std::cin >> temp;
total *= temp;
}
std::cout << "Total: " << total << std::endl;
return 0;
}
My solution uses std::accumulate with the operator std::multiplies to accumulate all elements by multiplying them. By just modifying your code, the end result would be:
#include <bits/stdc++.h>
int main() {
int n;
std::cin >> n;
std::vector<int> vec;
while(n--) {
int temp;
std::cin >> temp;
vec.push_back(temp);
}
int result = std::accumulate(std::begin(vec), std::end(vec), 1, std::multiplies<int>());
std::cout << result << std::endl;
return 0;
}
You were not processing the vector at all, and also outputting the vector but not the total result.
If you want to get the product of any numeric vector of any size, here's a function that works with any numeric type of vector with the help of templates:
template <class any>
long double vectorProduct(vector<any> vec) {
long double total = 1;
for(any num : vec) {
total *= num;
}
return total;
}
Usage:
cout << vectorProduct(vec) << endl;
Welcome. My problem is that I have given an array of numbers which I need to calculate the average (that part I did), but then I have to find the array element (module), which is closer to the average. Below paste the code (a form of main () imposed)
#include <iostream>
using namespace std;
double* aver(double* arr, size_t size, double& average){
double count;
for(int p = 0; p < size; p++)
count += arr[p];
count /= size;
double * pointer;
pointer = &count;
average = *pointer;
}
int main() {
double arr[] = {1,2,3,4,5,7};
size_t size = sizeof(arr)/sizeof(arr[0]);
double average = 0;
double* p = aver(arr,size,average);
cout << p << " " << average << endl;
}
The program should give a result
4 3.66667
I have no idea how to check which element is nearest to another, and substitute it into *p
I will be very grateful for any help.
Okay, this is not the answer to your problem, since you already got couple of them
How about trying something new ?
Use std::accumulate, std::sort and std::partition to achieve same goal.
#include<algorithm>
//...
struct comp
{
double avg;
comp(double x):avg(x){}
bool operator()(const double &x) const
{
return x < avg;
}
};
std::sort(arr,arr+size);
average =std::accumulate(arr, arr+size, 0.0) / size;
double *p= std::partition(arr, arr+size, comp(average));
std::cout<<"Average :"<<average <<" Closest : "<<*p<<std::endl;
This algorithm is based on the fact that std::map keeps its elements sorted (using operator<):
#include <map>
#include <iostream>
#include <math.h>
using namespace std;
double closest_to_avg(double* arr, size_t size, double avg) {
std::map<double,double> disturbances;
for(int p = 0; p < size; p++) {
disturbances[fabs(avg-arr[p])]=arr[p]; //if two elements are equally
} //distant from avg we take
return disturbances.begin()->second; //a new one
}
Since everybody is doing the kids homework...
#include <iostream>
using namespace std;
double min(double first, double second){
return first < second ? first : second;
}
double abs(double first){
return 0 < first ? first : -first;
}
double* aver(double* arr, size_t size, double& average){
double count;
for(int p = 0; p < size; p++)
count += arr[p];
average = count/size;
int closest_index = 0;
for(int p = 0; p < size; p++)
if( abs(arr[p] - average) <
abs(arr[closest_index] - average) )
closest_index = p;
return &arr[closest_index];
}
int main() {
double arr[] = {1,2,3,4,5,7};
size_t size = sizeof(arr)/sizeof(arr[0]);
double average = 0;
double* p = aver(arr,size,average);
cout << *p << " " << average << endl;
//Above ^^ gives the expected behavior,
//Without it you'll get nothing but random memory
}
I insist that you need the * before the p, it gives the value that the pointer is pointing too. Without the * then the value is the address of the memory location, which is indeterminate in this case. Ask your professor/teacher whether the specification is correct, because it isn't.
Try and understand the style and functions involved - it isn't complicated, and writing like this can go a long ways to making your graders job easier.
Also that interface is a very leaky one, in real work - consider some of the standard library algorithms and containers instead.