Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I have an assignment to create a C++ program to find all the possible mathematic equation with operators. Below shows the question:
Given a set of numbers, for example {5, 3, 7, 3, and 11}. Find all the possible mathematic equation with operators such as +, - ,*, / in such a way that the equation will produce the given answer. For example, 5+7-3/3=11.
I need an idea how to start with the code. Is it like brute force algorithm ? I have no idea how to interchange the operators to create the possible equation. I'm not asking for full solution, just an idea how to start the coding.
You could think about it like this. +,-,*,/ can be treated as 1,2,3,4 respectively. Now, if you were to try all the different combinations for whatever size array of numbers you get, you could look at it like this.
example. 4 numbers.
1,1,1,1 1,1,1,2 1,1,1,3 1,1,1,4
1,1,2,1 1,1,2,2 1,1,2,3 1,1,2,4
and so on and so forth. Hope this might help!
I would like to state that this is not my original idea. I will add the reference below.Please find the C++ code below. It might be of some help to you as it has been to me.
#include <iostream>
#include<string>
using namespace std;
void cntdwn(double sum, double previous, string digits, double target, std::string expr) {
if (digits.length() == 0) {
if (sum + previous == target) {
std::cout<<expr << " = " << target;
}
} else {
for (int i = 1; i <= digits.length(); i++) {
double current = std::stod(digits.substr(0, i));
string remaining = digits.substr(i);
cntdwn(sum + previous, current, remaining, target, expr + " + " + std::to_string(current));
cntdwn(sum, previous * current, remaining, target, expr + " * " + std::to_string(current));
cntdwn(sum, previous / current, remaining, target, expr + " / " + std::to_string(current));
cntdwn(sum + previous, -current, remaining, target, expr + " - " + std::to_string(current));
}
}
}
void f(string digits, double target) {
for (int i = 1; i <= digits.length(); i++) {
string current = digits.substr(0, i);
cntdwn(0, std::stod(current), digits.substr(i), target, current);
}
}
int main() {
// The digits go as concatenated string
f("5373",11);
return 0;
}
Output:
5 * 3.000000 - 7.000000 + 3.000000 = 11
References:
Generate all combinations of mathematical expressions that add to target (Java homework/interview)
https://math.stackexchange.com/questions/459857/using-operators-and-4-4-4-4-digits-find-all-formulas-that-would-resolve
https://www.careercup.com/question?id=5735906000502784
Additional Note
a) This code will not make any combinations for the digits. For example if we give (4,4,4,4) as numbers and 10 as target then it will not give any result as the solution in that case should be [(44-4)/4] {this example has been picked from second reference].
b) And this problem is a classic algorithmic problme popularly known as "Countdown Problem" picked from famous UK game.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I've just started learning C++ and I came across a simple problem but couldn't solve. Help me please,
In geometric progression, b1=2, r=3.
Create recursive function that outputs initial n sequences of progression. n should be input.
Assuming b1 is the initial number and r is the multiplier (ratio?), that would give 2, 6, 18, 54, ....
The pseudo-code for such a beast would be:
def geometric (limit, current, multiplier):
if limit <= 0: return
print(current)
geometric(limit - 1, current * multiplier, multiplier)
def main():
b1 = 2
r = 3
n = input("How many terms? ")
geometric(n, b1, r)
The reason it's pseudo-code is that I tend to prefer for educational questions since people learn a lot more by converting it rather than just being given an answer.
So, in terms of how the recursive function works, you pass it the number of terms remaining along with the current term and the multiplier.
Provided it hasn't reached its base case (number of terms remaining is zero), it prints the current term then recursively calls itself, adjusting the arguments so as to approach the base case.
Once it has reached the base case, it will return (from all recursive levels).
Turning that into C++ is an exercise I'll leave for the reader, but I can provide something similar so you will see the approach taken.
Let's say you wanted to sum all the numbers between 1 and a given number. It has the same features as any recursive solution, including the one posed in your question:
an operation that can be defined in terms of a simpler operation; and
the base case.
In C++, a complete program to do that would be something like:
#include <iostream>
void recurse(int number, int sum) {
// Base case for printing and returning.
if (number <= 0) {
std::cout << "Sum is " << sum << '\n';
return;
}
// Recurse to next level.
recurse(number - 1, sum + number);
}
int main() {
int myNum;
std::cout << "Enter your number: ";
std::cin >> myNum;
recurse(myNum, 0);
}
Some sample runs:
Enter your number: 3
Sum is 6
Enter your number: 4
Sum is 10
Enter your number: 5
Sum is 15
Enter your number: 6
Sum is 21
Enter your number: 100
Sum is 5050
The explanatory text on your specific question, along with the C++ code showing how to do it for a different question, should hopefully be enough for you to work it out.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
Chef has a calculator which has two screens and two buttons. Initially, each screen shows the number zero. Pressing the first button increments the number on the first screen by 1, and each click of the first button consumes 1 unit of energy.
Pressing the second button increases the number on the second screen by the number which is currently appearing on the first screen. Each click of the second button consumes B units of energy.
Initially the calculator has N units of energy.
Now chef wonders what the maximum possible number is, that he gets on the second screen of the calculator, with the limited energy.
Here is the link: https://www.codechef.com/JULY17/problems/CALC/
Contest is ended, so I am not trying to cheat.
here is my solution to the problem:
#include<bits/stdc++.h>
using namespace std;
int main()
{
int t;
cin>>t;
while(t--)
{
int n,b;
cin>>n>>b;
int count = 1;
int ans = n-b;
while((n - count*b)>=0)
{
if(count*(n - count*b)>ans)
ans = count*(n - count*b);
count++;
}
cout<<ans<<endl;
}
return 0;
}
I have tried every test case that i can think of... Can anyone help to find the error in my logic.
The errors that I think can be:
1: You didn't handle N<=B case
if (n<=b) {
ans = 0;
}
2: you didn't handle Subtask 2 Constraints
long long int ans = n-b;
3: lastly answer will be n-b if b is three time less than equal to n
if (n<=3*b) {
ans = n-b;
}
4: Look for a straight forward approach
k1 = ((n-(b+1))/(2*b))+1;
i2 = (double((n-(3*b)))/(2*b));
i1 = ceil(i2);
i = n-((3*b)+((i1-1)*(2*b)));
ans = ((2*b)*((k1*(k1-1))/2))+(k1*i);
cout << ans;
Hope this helps :)
It is a mostly a mathematical question:
With
N unit of energy
B energy cost of 2nd screen
p number of time 1st button clicked
s number of time 2nd button clicked
You try to maximize
s * p
whereas
p + B * s <= N
so
p <= N - B * s
and then
maximize: N * s - B * s²
s0 = 0
s1 = N / B
sMax is (s0 + s1) / 2 -> N / (2*B)
so max value is
N²/2B - N²/4B -> N²/4B
so
std::cin >> n >> b;
std::cout << n * n / b / 4 << std::endl
This question already has answers here:
Evaluating arithmetic expressions from string in C++ [duplicate]
(7 answers)
Closed 5 years ago.
Sorry for my lack of English skills.
I want to do an arithmetic operation specified in a string, e.g. "1 + 3 * 11 - 7 / 18".
Multiplication and division have higher priority than addition and subtraction. In the case of operations with the same priority, operations are performed in order from left to right.
I've written code that computes the addition. But I can not get to the next step.
#include <iostream>
#include <string>
using namespace std;
int main() {
string s;
cout << "Enter an arithmetic operation EX) 1 + 3 * 11 + 7 / 18 " << endl;
getline(cin, s, '\n');
int sum = 0;
int search = 0;
while(true) {
int plus = s.find('+', search);
if(plus == -1) {
string aos = s.substr(search);
if(aos == "") break;
cout << aos << endl;
sum += stoi(aos);
break;
}
int count = plus - search;
string aos = s.substr(search, count);
cout << aos << endl;
sum += stoi(aos);
search = plus+1;
}
cout << "Result is " << sum;
}
There is no built-in way to parse and evaluate a string. You'll need to write your own code to do this.
Typically, expression evaluation proceeds in two steps:
Scanning. Rather than working with a single string, break the input apart into individual units called tokens. For example, the string 5 * 3 + 2 might turn into the sequence ["5", "*", "3", "+", "2"]. By doing this step in advance, you make it a lot easier to work with the quantities later on, since there's no need to do a ton of complex string processing.
Evaluation. Given the sequence of tokens, determine what the expression evaluates to.
The approach you're taking - finding an operator and evaluating it - can be made to work. You'll want to search for the highest-priority operator first to evaluate. For example, in the string 5 * 3 + 2, you'd need to evaluate 5 * 3 before 3 + 2.
However, there are other faster and cleaner ways to do this. Dijkstra's shunting-yard algorithm uses two stacks to evaluate expressions and is relatively straightforward to code up. I'd recommend starting there - every time I've needed to make an expression evaluator by hand, I've turned to this particular approach.
There are other heavyweight options. You could look online for an expression parsing library, or you could use a tools like flex and bison to automatically generate a parser. I suspect that's overkill for what you need, though.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I'm having like an assesment exercise.
So given a Number, for example 12345, I must find out the sum sequence of the digits of the given number (1 + 2 +3 + 4 +5) and then add to it the result (15), and repeat this till the sum sequence of the last number is a digit (in this case is 6).
Example : 12345 + 15 + 6 = 12366;
666 + 24 + 6 = 696;
I've been thinkig to store the digits in an array, but then I realized the array's size is static. Now I'm thinking to make a linked list, but I'm not really sure. Does it involve linked lists?
Just guide me to the right path. What should I use?
There's no magic needed here. Just do the obvious computation on integers:
int reduce(int n)
{
int result = 0;
while (n != 0) { result += n % 10; n /= 10; }
return result;
}
int your_problem(int n)
{
int result = n;
while (n >= 10) { n = reduce(n); result += n; }
return result;
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm really fresh to C++, and I faced difficulties with the next question :
Write a program that asks the user to enter a number : n
THEN calculate f(n).
Notice that :
f(0)=3 and f(n+1) = 3/4 * f(n) + 4 ?
For example :
f(1)= 6.25
f(2)= 8.69
f(3)= 10.52
f(4)= 11.89
f(5)= 12.92
====================================================
So, how can I solve this?
thanks for all..
I try this code depending on Mr. paxdiablo answer :
#include<iostream>
using namespace std;
int main()
{
double x=0.0;
cout<<" enter an integer N:";
cin>> x;
double f1(double x)
{
if x==0.0
return 3;
return 3 / 4 * f1 (x-1) + 4;
}
return 0;
}
But the program never runs!
================================================
The Correct Solution is :
#include<iostream>
#include<iomanip> //To enable "setprecision" tool
using namespace std;
double f(int x){
if (x==0)
{return 3;}
return (3.0/4.0) * f(x-1) + 4.0; //we add zeros to get "double" results
}
int main()
{
int n=0;
cout<<" Please, enter an integer :";
cin>> n;
cout<<fixed<<setprecision(2)<<f(n); //"setprecision" used to get only two digits after the point
return 0;
}
BIG thanks to everyone gave me a hand and special thank to Mr. paxdiablo.
This sounds like a job for ... Recursion Man!
Simply define a recursive function that returns 3 when n is zero or calls itself with a reduced problem.
Pseudo-code would be something like
def f(x):
if x == 0:
return 3
return 3 / 4 * f(n-1) + 4
You can use std::cin >> dv to get a value from the user and that function (recoded in C++) to do the grunt work. Then std::cout << result to output the result. Just remember to use doubles rather than ints, including constants like 3.0.
You have to define the recursive function f, then read the input from the user, then apply the function to the input you've read (probably as an integer?), and print the output.