I have made a code to solve a problem.
This is the link of problem: https://brilliant.org/practice/bijections-overview/?p=2
My opinion is use recursion. I have 3 elements to sum up 5, I iterate single element from 0 to 5 and so on.
This is my code:
#include<bits/stdc++.h>
using namespace std;
int count_sum_5(int sum, int n)
{
if(n == 1) return 1;
for(int i = 0; i <= sum ; i++){
return 1 + count_sum_5(sum - i, n - 1);
}
}
int main()
{
int sum = 5;
int count_ele = 3;
cout << count_sum_5(sum, count_ele);
}
Its output is 3, I think it only runs on i = 0 but does not run on i = 1, 2, 3, 4, 5. Could you help me?
Your function will return 1 if n is 1. Otherwise it will enter the for cycle, which will return the value of the first iteration. You call your function by passing 5 and 3, respectively.
First call: It returns 1 + count_sum_5(5, 2)
Second call: It returns 1 + count_sum_5(5, 1)
Third call: It returns 1
So, the second call will evaluate to 1 + 1 = 2 and then the second call will evaluate to 1 + 2 = 3. I'm not sure what your intention is, but the for cycle is not needed for your recursion. Your function is equivalent to
int count_sum_5(int sum, int n)
{
if(n == 1) return 1;
return 1 + count_sum_5(sum, n - 1);
}
I'm not sure whether you are satisfied with this. If not, then please let me know what you intend to achieve, sample inputs and outputs would help. If you provide further information, then I will edit my answer accordingly.
return evaluates 1 + count_sum_5(sum - i, n - 1) and then immediately exits the whole function, on the first iteration of the loop. It's not possible to return from a function multiple times.
I don't know what exactly are you trying to solve using that. But For loop will run only one time for i=0, because as soon as it evaluates the 1+count_sum(sum-i, n-1), It will return it.
However, you can do the following changes:
#include<bits/stdc++.h>
using namespace std;
int count_sum_5(int sum, int n)
{
if(n == 1) return 1;
int temp = 0;
for(int i = 0; i <= sum ; i++){
temp += (1 + count_sum_5(sum - i, n - 1));
}
return temp;
}
int main()
{
int sum = 5
int count_ele = 3;
cout << count_sum_5(sum, count_ele);
}
Related
So I have set up my code to be this (note I have my user input for the array and display of the results in another function and a beginner)
int main( )
{
using namespace std;
int a[8];
populateArray(a, 8);
cout<<"The array is: ";
displayArray(a, 8);
cout<<"\nThis array becomes: "<<sameElement(a, 8);
int sameElement(int a[], int size)
{
using namespace std;
for(int i = 0; i < size; i ++)
{
if( a[i] == a[i +1])
{
a[i + 1] = 0;
return i;
}
else
{
return a[i];
}
}
}
Been trying to see if a user puts a duplicate number(that works fine and great). That same array that the user input I want to replace that duplicate to a zero. Sadly I get either a single 0, 1, or 2 and it replaces the entire array. not sure how to return it back to my main as it also says that I have nothing returning from my function despite invoking it in my function and trying to find the right way to return my function. I have declared my function on top and they both match with the parameter as well. So still don't see why I keep getting an issue of returning my function to main?
Example:
The array: 1 2 2 3 4 5 5 7
Array becomes 1 0 0 3 4 0 0 7
I suppose you want to replace duplicate entries of an array in sameElement function. You're getting single integer because sameElement function returns single integer.
Instead of returning value in for loop, let the function run through. Also note that a[i+1] will go over limit of array a, so you have to change ending condition to size - 1.
void sameElement(int a[], int size)
{
for(int i = 0; i < size - 1; i++)
{
if( a[i] == a[i +1])
{
a[i] = 0;
if(i + 1 == size - 1)
{
a[i + 1] = 0;
}
}
}
}
Because the function no longer returns value, you must display it on its own.
cout << "\nThis array becomes: ";
sameElement(a, 8);
displayArray(a, 8);
Lastly, I don't know if this is intentional but sameElement function will only find duplicate entries if they are next to each other: it won't turn 1 2 1 2 1 2 1 2 to zeroes.
I want the result to be the returned value from the mystery function,but the result is always 0 .but I want the program to return a value that's collected from the mystery function
#include <iostream>
using namespace std;
int Mystery(int n)
{
// int k;
if (n <= 1)
{
return 0;
}
else
{
int k = n;
for (int i = 1; i <= n; i++)
{
k = k + 5;
}
cout << ((k * (n / 2)) + (8 * (n / 4)));
cout << "\n ";
return ((k * Mystery(n / 2)) + (8 * Mystery(n / 4)));
}
}
int main(void)
{
int i, n;
cout << "Enter n:"; //array size
cin >> n;
int result = Mystery(n);
cout << "The result is " << result;
return 0;
}
Let's desk check what happens when you call Mystery(2). The final return value is:
((k* Mystery(n/2)) + (8* Mystery(n/4)))
We know that n == 2 so let's substitute that:
((k* Mystery(1)) + (8* Mystery(0 /* by integer division of 2/4 */)))
This will call the function recursively twice with the respective arguments 1 and 0. But we know that the terminating case n <= 1 returns 0, so we can substitute that:
((k* 0) + (8* 0))
Anything multiplied by zero is zero, so this reduces to 0 + 0 which is also zero. It doesn't even matter what k is.
Quite simply, the terminating case for this recursion mandates that the result is always zero.
In the terminating case the return value is zero.
In the recursive case, the recursive call result is multiplied with another value to produce the return value.
Therefore, the result is always going to be zero for any n.
I'm not sure exactly how this function is supposed to work as you have not explained that, but changing the terminating case to return 1; may solve the problem.
I don't expect which result you want, but I think you can get write result when you correct conditions like
if (n == 0)
return 0;
if (n == 1)
return 1;
I hope it returns the right result.
This question already has answers here:
How to get the least number after deleting k digits from the input number
(11 answers)
Closed 6 years ago.
I am trying to code a program that can do something like this:
in:
5 4
1 9 9 9 0
out:
9990
and i have a problem. It doesnt work on any set of numbers. For example it works for the one above, but it doesnt work for this one:
in:
15 9
2 9 3 6 5 8 8 8 8 7 2 2 8 1 4
out: 988887814
2 9 3 6 5 8 8 8 8 7 2 2 8 1 4
I did this with a vector approach and it works for any set of numbers, but i'm trying to do it a stack for a better complexity.
EDIT ---- MODIFIED FOR STD::STACK
Code for method using stack:
#include <iostream>
#include <fstream>
#include <stack>
using namespace std;
ifstream in("trompeta.in");
ofstream out("trompeta.out");
void reverseStack(stack<char> st) {
if(!st.empty())
{
char x = st.top();
st.pop();
reverseStack(st);
out<<x;
}
return;
}
int main()
{
int n,m,count=1;
stack <char> st;
char x;
in>>n>>m;
in>>x;
st.push(x);
for(int i=1; i<n; i++)
{
in>>x;
if(st.top()<x && count+n-i-1>=m)
{
st.pop();
st.push(x);
}
else
{
st.push(x);
count++;
if (count>m-1) break;
}
};
reverseStack(st);
}
Code for method using vectors:
#include <iostream>
#include <fstream>
using namespace std;
ifstream in ( "trompeta.in" );
ofstream out ( "trompeta.out" );
int main ()
{
int i = 0, N, M, max, j, p = 0, var;
in >> N >> M;
char* v = new char[N];
char* a = new char[M];
in >> v;
var = M;
max = v[0];
for ( i = 0; i < M; i++ )
{
for ( j = p ; j < N-var+1; j++ )
{
if ( v[j] > max )
{
max = v[j];
p = j;
}
}
var--;
a[i] = max;
max = v[p+1];
p = p+1;
}
for ( i = 0; i < M; i++ )
out << a[i]-'0';
}
Can any1 help me to get the STACK code working?
Using the fact that the most significant digit completely trumps all other digets except in place of a tie, I would look at the first (N-M+1) digits, find the largest single digit in that range.
If it occurs once, the first digit is locked in. Discard the digits which occur prior to that position, and you repeat for "maximum value of M-1 numbers of out N-position" to find the remaining digits of the answer. (or N-position-1, if position is zero based)
If it occurs multiple times, then recursively find "maximum value of M-1 numbers out of N-position" for each, then select the largest single result from these. There can be at most N such matches.
I forgot to mention, if N==M, you are also done.
proof of recursion:
Computing the value of the sub-match will always select M-1 digits. When M is 1, you only need to select the largest of a few positions, and have no more recursion. This is true for both cases. Also the "select from" steps always contain no more than N choices, because they are always based on selecting one most significant digit.
------------------ how you might do it with a stack ----------------
An actual implementation using a stack would be based on an object which contains the entire state of the problem, at each step, like so:
struct data { // require: n == digits.size()
int n, m;
std::string digits;
bool operator<(const data &rhs){ return digits < rhs.digits; }
};
The point of this is not just to store the original problem, but to have a way to represent any subproblem, which you can push and pop on a stack. The stack itself is not really important, here, because it is used to pick the one best result within a specific layer. Recursion handles most of the work.
Here is the top level function which hides the data struct:
std::string select_ordered_max(int n, int m, std::string digits) {
if (n < m || (int)digits.size() != n)
return "size wrong";
data d{ n, m, digits };
data answer = select_ordered_max(d);
return answer.digits;
}
and a rough pseudocode of the recursive workhorse
data select_ordered_max(data original){
// check trivial return conditions
// determine char most_significant
// push all subproblems that satisfy most_significant
//(special case where m==1)
// pop subproblems, remembering best
return answer {original.m, original.m, std::string(1, most_significant) + best_submatch.digits };
}
String comparison works on numbers when you only compare strings of the exact same length, which is the case here.
Yes, I know having n and m is redundant with digits.size(), but I didn't want to work too hard. Including it twice simplified some recursion checks. The actual implementation only pushed a candidate to the stack if it passed the max digit check for that level of recursion. This allowed me to get the correct 9 digit answer from 15 digits of input with only 28 candidates pushed to the stack (and them popped during max-select).
Now your code has quite a few issues, but rather than focusing on those lets answer the question. Let's say that your code has been corrected to give us:
const size_t M where M is the number of digits expected in our output
const vector<int> v which is the input set of numbers of size N
You just always want to pick the highest value most significant number remaining. So we'll keep an end iterator to prevent us from picking a digit that wouldn't leave us with enough digits to finish the number, and use max_element to select:
const int pow10[] = { 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000 };
auto maximum = 0;
auto end = prev(cend(v), M - 1);
auto it = max_element(cbegin(v), end);
for (auto i = M - 1; i > 0; --i) {
maximum += *it * pow10[i];
advance(end, 1);
it = max_element(next(it), end);
}
maximum += *it;
Live Example
This code depends upon M being greater than 0 and less than N and less than log10(numeric_limits<int>::max())
EDIT: Sad to say this solves the consecutive digits problem, after edits the question wants subsequent digits, but not necessarily consecutive
So the little known numeric library provides inner_product which seems like just the tool for this job. Now your code has quite a few issues, but rather than focusing on those lets answer the question. Let's say that your code has been corrected to give us:
vector<int> foo(M) where M is the number of digits expected in our output
const vector<int> v which is the input set of numbers of size N
We'll use foo in the inner_product, initializing it with decreasing powers of 10:
generate(begin(foo), end(foo), [i=int{1}]() mutable {
auto result = i;
i *= 10;
return result; });
We can then use this in a loop:
auto maximum = 0;
for (auto it = prev(rend(v), size(foo) + 1); it != rbegin(v); advance(it, -1)) {
maximum = max<int>(inner_product(cbegin(foo), cend(foo), it, 0), maximum);
}
maximum = max<int>(inner_product(cbegin(foo), cend(foo), rbegin(v), 0), maximum);
Live Example
To use it's initialization requires that your initial M was smaller than N, so you may want to assert that or something.
--EDITED--
here's my suggestion with STACK based on my previous suggestion using vector
findMaxValueOutOfNDigits(stackInput, M, N)
{
// stackInput = [2, 9, 3, 6, 5, 8, 8, 8, 8, 7, 2, 2, 8, 1, 4]
// *where 4 was the first element to be inserted and 2 was the last to be inserted
// if the sequence is inverted, you can quickly fix it by doing a "for x = 0; x < stack.length; x++ { newStack.push(stack.pop()) }"
currentMaxValue = 0
for i = 0; i < (M - N + 1); i++
{
tempValue = process(stackInput, M, N)
stackInput.pop()
if (tempValue > currentMaxValue)
currentMaxValue = tempValue
}
return currentMaxValue
}
process(stackInput, M, N)
{
tempValue = stackInput.pop() * 10^(N - 1)
*howManyItemsCanILook = (M - N + 1)
for y = (N - 2); y == 0; y++
{
currentHowManyItemsCanILook = *howManyItemsCanILook
tempValue = tempValue + getValue(stackInput, *howManyItemsCanILook) * 10^(y)
*howManyItemsCanILook = *howManyItemsCanILook - 1
for x = 0; x < (currentHowManyItemsCanILook - *howManyItemsCanILook); x++
{
stackInput.pop()
}
}
return tempValue
}
getValue(stackInput, *howManyItemsCanILook)
{
currentMaxValue = stackInput.pop()
if (currentMaxValue == 9)
return 9
else
{
goUntil = *howManyItemsCanILook
for i = 0; i < goUntil; i++
{
*howManyItemsCanILook = *howManyItemsCanILook - 1
tempValue = stackInput.pop()
if (currentMaxValue < tempValue)
{
currentMaxValue = tempValue
if (currentMaxValue == 9)
return currentMaxValue
}
}
return currentMaxValue
}
}
note: where *howManyItemsCanILook is passed by reference
I hope this helps
The program runs but it also spews out some other stuff and I am not too sure why. The very first output is correct but from there I am not sure what happens. Here is my code:
#include <iostream>
using namespace std;
const int MAX = 10;
int sum(int arrayNum[], int n)
{
int total = 0;
if (n <= 0)
return 0;
else
for(int i = 0; i < MAX; i ++)
{
if(arrayNum[i] % 2 != 0)
total += arrayNum[i];
}
cout << "Sum of odd integers in the array: " << total << endl;
return arrayNum[0] + sum(arrayNum+1,n-1);
}
int main()
{
int x[MAX] = {13,14,8,7,45,89,22,18,6,10};
sum(x,MAX);
system("pause");
return 0;
}
The term recursion means (in the simplest variation) solving a problem by reducing it to a simpler version of the same problem until becomes trivial. In your example...
To compute the num of the odd values in an array of n elements we have these cases:
the array is empty: the result is trivially 0
the first element is even: the result will be the sum of odd elements of the rest of the array
the first element is odd: the result will be this element added to the sum of odd elements of the rest of the array
In this problem the trivial case is computing the result for an empty array and the simpler version of the problem is working on a smaller array. It is important to understand that the simpler version must be "closer" to a trivial case for recursion to work.
Once the algorithm is clear translation to code is simple:
// Returns the sums of all odd numbers in
// the sequence of n elements pointed by p
int oddSum(int *p, int n) {
if (n == 0) {
// case 1
return 0;
} else if (p[0] % 2 == 0) {
// case 2
return oddSum(p + 1, n - 1);
} else {
// case 3
return p[0] + oddSum(p + 1, n - 1);
}
}
Recursion is a powerful tool to know and you should try to understand this example until it's 100% clear how it works. Try starting rewriting it from scratch (I'm not saying you should memorize it, just try rewriting it once you read and you think you understood the solution) and then try to solve small variations of this problem.
No amount of reading can compensate for writing code.
You are passing updated n to recursive function as argument but not using it inside.
change MAX to n in this statement
for(int i = 0; i < n; i ++)
so this doesnt really answer your question but it should help.
So, your code is not really recursive. If we run through your function
int total = 0; //Start a tally, good.
if (n <= 0)
return 0; //Check that we are not violating the array, good.
else
for(int i = 0; i < MAX; i ++)
{
if(arrayNum[i] % 2 != 0) //THIS PART IS WIERD
total += arrayNum[i];
}
And the reason it is wierd is because you are solving the problem right there. That for loop will run through the list and add all the odd numbers up anyway.
What you are doing by recursing could be to do this:
What is the sum of odd numbers in:
13,14,8,7,45,89,22,18,6,10
+
14,8,7,45,89,22,18,6
+
8,7,45,89,22,18
+
7,45,89,22 ... etc
And if so then you only need to change:
for(int i = 0; i < MAX; i ++)
to
for(int i = 0; i < n; i ++)
But otherwise you really need to rethink your approach to this problem.
It's not recursion if you use a loop.
It's also generally a good idea to separate computation and output.
int sum(int arrayNum[], int n)
{
if (n <= 0) // Base case: the sum of an empty array is 0.
return 0;
// Recursive case: If the first number is odd, add it to the sum of the rest of the array.
// Otherwise just return the sum of the rest of the array.
if(arrayNum[0] % 2 != 0)
return arrayNum[0] + sum(arrayNum + 1, n - 1);
else
return sum(arrayNum + 1, n - 1);
}
int main()
{
int x[MAX] = {13,14,8,7,45,89,22,18,6,10};
cout << sum(x,MAX);
}
The output is supposed to be in this fashion
I
IN
IND
INDI
INDIA
INDIA
INDI
IND
IN
I
I was wondering if there is anyway to make my program shorter.
Maybe use 2 while loops or 2 for loops instead of 4.
#include<iostream>
#include<conio.h>
using namespace std;
void main()
{
char a[]={'I','N','D','I','A'};
int r,c;
for(r=1;r<=5;r++)
{
for(c=0;c<r;c++)
cout<<a[c]<<" ";
cout<<endl;
}
for(r=5;r>=0;r--)
{
for(c=0;c<r;c++)
cout<<a[c]<<" ";
cout<<endl;
}
_getch();
}
This is nice and short, if you have C++11:
#include <stdio.h>
#include <initializer_list>
int main() {
for (int i : {1,3,5,7,9,9,7,5,3,1})
printf ("%.*s\n", i, "I N D I A") ;
}
I put it on ideone at this link.
The "cheating" ;-) but very short solution is
#include <cstdio>
int main() {
puts("I\nIN\nIND\nINDI\nINDIA\nINDIA\nINDI\nIND\nIN\nI\n");
}
Yet another solution based on TonyK's beautiful idea (works in C and C++):
#include <stdio.h>
int main() {
for (int i = 1; i < 11; ++i)
printf("%.*s\n", i < 6 ? i : 11 - i, "INDIA") ;
}
Update: (After TonyK's comment):
If you want spaces, then replace the printf above with this
printf("%.*s\n", 2*(i < 6 ? i : 11 - i), "I N D I A ");
Update: A solution with no loop:
#include <stdio.h>
int main(int i, char**) {
return printf("%.*s\n", i < 6 ? i : 11 - i, "INDIA") - 1 && main(i + 1, 0);
}
Detailed explanations for the benefit of beginners follow.
The most important point is that this is an "academic" exercise. The code is obscure and one should refrain from writing serious code like this.
The standard doesn't fix a particular signature for the function main. It only says that it must return an int and the compiler must accept two particular forms:
int main();
int main(int argc, char** argv);
I'm using the second one. The more popular form int main(int argc, char* argv[]) is equivalent to (2). Indeed, in general, an array of T used as a function argument is implicitly converted to pointer to T. In this example, char* argv[] is an array of pointer to char which becomes a pointer to pointer to char. The above program is not using the second parameter though (it's either ignored or given a NULL, i.e. 0 value).
Instead of doing a loop, the program calls main recursivelly. Actually, this is illegal but the major compilers turn a blind eye to it (at most GCC gives a warning if you ask it to be pedantic with option -Wpedantic). When the program is called from the command line with no arguments the operating system calls main passing 1 (which is 1 + the number of arguments) and a pointer to pointer to char which, as said, is ignored by this program. Hence, i = 1 at the first call.
Subsequently, main potentially calls itself incrementing i each time. In summary, main is sequentially called with i being 1, 2, 3, 4, ...
It's easy to see that for this sequence of values for i, the expression i < 6 ? i : 11 - i evaluates to 1, 2, 3, 4, 5, 5, 4, 3, 2, 1, 0, ... (This can also be expressed by 5.5 - abs(5.5 - i) as per Drew Dorman's solution but using the ternary operator avoids the need to #include <cmath> which saves a line ;-) These numbers are the quantity of characters of "INDIA" that should be displayed at each time.
The call printf("%.s\n", j, "INDIA"), where j = i < 6 ? i : 11 - i, displays the first j characters of "INDIA" followed by a new line and returns the number of characters effectivelly printed (including the new line), i.e. j + 1. Taking away 1 yields j.
We recall now an important point of the semantics of a && b, for integers a and b. If a == 0, then b is not evaluated. Otherwise, b is evaluated. For us, a = printf("%.*s\n", j, "INDIA") - 1 (i.e. a = j) and b = main(i + 1, 0).
Now, let's put these pieces together.
1. Initially, i = 1 and j = 1. The call to printf outputs "I\n" and returns 2. Taking away 1, gives a = 1 != 0. Therefore, b = main(2, 0) is evaluated (that is, main(2, 0) is called).
2. Well, for this second call to main, we have i = 2, j = 2, printf displays "IN\n", a = 2 != 0 and b = main(3, 0) is evaluated.
Repeating this argument, at each call to main we have:
3. i = 3, j = 3, "IND\n" is printed, a = 3 != 0 and main(4, 0) is called.
4. i = 4, j = 4, "INDI\n" is printed, a = 4 != 0 and main(5, 0) is called.
5. i = 5, j = 5, "INDIA\n" is printed, a = 5 != 0 and main(6, 0) is called.
6. i = 6, j = 5, "INDIA\n" is printed, a = 5 != 0 and main(7, 0) is called.
7. i = 7, j = 4, "INDI\n" is printed, a = 4 != 0 and main(8, 0) is called.
...
10. i = 10, j = 1, "I\n" is printed, a = 1 != 0 and main(11, 0) is called.
11. i = 11, j = 0, "\n" is printed, a = 0. Now main(12, 0) is not exectued and the main returns
Notice that main in step 1 calls main in step 2, which calls main in step 3, ... which calls main in step 11. Therefore, main in step 11 returns to main in step 10, which returns to main in step 9, ..., which returns to main in step 1. Finally, main in step 1 returns to the operating system.
If you are interested in even more obfuscated code, see present and past winners of the IOCCC. Enjoy!
Shorter.
#include <iostream>
#include <cmath>
int main()
{
char a[]={'I','N','D','I','A'};
for(int r=1;r<=10;r++)
{
int c = 5.5 - std::abs(5.5 - r);
std::cout << std::string(a, 0, c) << std::endl;
}
}
You could use substr.
Additionally, if you want to add spaces between the characters (as it's in your code right now) you could do that once for the whole word and then work on that modified string:
input = "INDIA";
modifiedInput = ...; // Figure out a way to get "I N D I A " here
for (int i = 1; ...)
cout << substr(modifiedInput, 0, 2 * i) << endl;
...
smth like this:
Anyway, 2 loops is hard thing)
int i=1;
bool ind=0;
for(r=0;r<10;r++)
{
if (ind == 0){
for(c=0;c<i;c++)
cout<<a[c]<<" ";
i++; }
if (ind == 1){
for(c=0;c<i;c++) cout<<a[c]<<" ";
i--;
}
if (i % 5 == 0) ind=1;
cout<<endl;
}
Here is an example using two loops:
#include<iostream>
using namespace std;
int main()
{
char a[]={'I','N','D','I','A'};
int arr_length=5;
bool two_times=false;//if you want to output INDIA twice
for(int i=2*arr_length-1; i>=1; i--)
{
for(int j=0; j<arr_length-abs(arr_length-i); j++)
{
cout << a[j];
}
if(i==arr_length && !two_times){ two_times=true; i++;}//if you want to output INDIA twice
cout << endl;
}
return 0;
}
Output:
I
IN
IND
INDI
INDIA
INDIA
INDI
IND
IN
I
You can do like this:
void main()
{
char a[]={'I','N','D','I','A'};
int r,c;
int x = 0; // initially x is 0
int l = 5;
for(r=1;r<= 11 ;r++) //loop runs for 5*2 + 1 times
{
if(r>=6){
x = l - r % 6; //set x to remaining length
l--;
}
for(c=0;c< (r % 6) + x; c++) // add x
cout<<a[c]<<" ";
cout<<endl;
}
}
and you can find it working here.
Another solution based on TonyK's answer. You can enter your desired string.
#include <stdio.h>
#include <string.h>
int main() {
char s[100];
gets(s);
for (int i = 0; i < strlen(s) * 2; i++)
printf ("%.*s\n", i < strlen(s) ? i + 1: 2 * strlen(s) - i, s);
}
http://ideone.com/Zsg5Lu