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
Related
I have an array of 16 numbers that i need to sort in descending order, I tried sorting them this way but can't seem to make it work.
Note : I have to program an algorithm so i can't use any special functions :(
#include <stdio.h>
#include <stdlib.h>
int main() {
int i, temp1, temp2;
int string2[16] = { 0, 4, 2, 5, 1, 5, 6, 2, 6, 89, 21, 32, 31, 5, 32, 12 };
_Bool check = 1;
while (check) {
temp1 = string2[i];
temp2 = string2[i + 1];
if (temp1 < temp2) {
string2[i + 1] = temp1;
string2[i] = temp2;
i = 0;
} else {
i++;
if (i = 15) {
check = !check;
}
}
}
return 0;
}
I realize that this is pretty basic stuff for most of you but any insight is much appreciated!
There're a few problems:
_Bool is a strange thing to use in C++ (maybe this question intended for C?)
You didn't initialize i. This is called an undefined behavior. This may or may not work, depends on the computer, but it's never good to have something like that in your program.
(i=15) is an assignment. Use i==15 for comparison, as == is the comparison operator for "equal to".
Reviewed code:
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
int main()
{
int i = 0,temp1,temp2; //i should be initialized
int string2[16] = {0,4,2,5,1,5,6,2,6,89,21,32,31,5,32,12};
bool check=1;
while(check)
{
temp1=string2[i];
temp2=string2[i+1];
if(temp1<temp2)
{
string2[i+1]=temp1;
string2[i]=temp2;
i=0;
}
else
{
i++;
if(i==15) { check=!check; } // = -> ==
}
}
//if this is intended for C, you can ignore this bit, or use printf
for (int i = 0; i < 16; i++) { std::cout << string2[i] << " ";}
}
Output: 89 32 32 31 21 12 6 6 5 5 5 4 2 2 1 0
A few more aesthetic notes:
If you use indentation (tabs and/or space), be consistent. Others may have a hard time understanding your code, although it doesn't matter when the program compile (to anyone questioning, this is before he re-indented the code).
string2 is an irregular name of an int array. Again, it could cause confusion. A reading : https://1c-dn.com/library/rules_of_naming_variables/
You could also use std::sort with std::greater<int>() parameter:
std::sort(std::begin(string2), std::end(string2), std::greater<int>());
don't invent a bicycle except you need to learn something or you know the way how to optimize your case.
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);
}
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
Here is my code: (C++)
#include <iostream>
#include <stdlib.h>
using namespace std;
int main(){
string sentence[9];
string word[9];
inb b[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
int f = 0;
for (int i = 1; i <= 10; i += 1){
cin >> sentence[i - 1];
}
for (int a = 10; a > 1; a = a - b[f]){
b[f] = 0;
int f = rand() % 10;
b[f] = 1;
word[f] = sentence[f];
cout << world [f] << endl;
}
}
However, when I run this I get a "runtime error". That's it, no line, no further error. Nothing.
The Arrays in the bottom side of the code, like word[f] and b[f] do not work if I use f inside the "[]"'s.
When I change all the "f"'s with [1] to test the code, it works. But when I use "f"'s instead, it returns a runtime error.
Not sure if that is my compiler. But hey - I am a 2 day old C++ coder.
Your sentence is 9 "slots" big (addressed as sentence[0] to sentence[8]). You try to put something in the 10th slot (sentence[9]), which is a no-no.
(This pattern is repeated below with word.)
You most likely want to declare those arrays as 10-element ones.
That's because sentence and word contain nine units. But rand()%10 will produce 9, when you use word[f] = sentence[f], word[9] and sentence[9] are out of range. word[9] is the 10th element of array word.
There are several problems with your code. Firstly, sentence and word only have 9 entries, but you try to use 10. Array declaration is 1-based, e.g.
char foo[2];
declares two characters. However, they are numbered 0 and 1, thus
char foo[2];
foo[0] = 'a'; //valid
foo[1] = 'b'; //valid
foo[2] = 'c'; //very bad.
this problem might be obfuscated for you by the fact that you are making 'b' an auto-sized array.
The second problem is that you declare 'f' twice.
int f = 0;
for (int i = 1; i <= 10; i += 1){
and inside the loop
int f = rand() % 10;
b[f] = 1;
Your for loop, then, is broken:
for (int a = 10; a > 1; a = a - b[f]){
it uses the external 'f', which is always 0, to access element zero of b and subtract that from a.
Here is how I would write the code you're trying to write:
I honestly don't understand what your code is supposed to do, but here is how I might write a simpler version of the same thing:
#include <iostream>
#include <stdlib.h>
#include <array>
//using namespace std; <-- don't do this.
int main(){
std::array<std::string, 10> sentence; // ten strings
// populate the array of sentences.
for (size_t i = 0; i < sentence.size(); ++i) { // use ++ when ++ is what you mean.
std::cin >> sentence[i];
}
for (size_t i = 0; i < sentence.size(); ++i) {
size_t f = rand() % sentence.size(); // returns a value 0-9
std::cout << sentence[f] << " ";
}
std::cout << std::endl;
}
Requires C++11 (-std=c++11 compiler option). ideone live demo here
Basically, I have an array given of "x" numbers and I have to output the amount of how many times the sign changed in the numbers of the array.
For example array is:
2 -4 5 6 7 -2 5 -7
The output should be 5. Why? Because the sign changes first time at -4, second time at 5, third time at -2, fourth time at 5 and last time at -7. Total 5 times.
So, I have this so far but that doesn't work perfectly:
#include <iostream>
using namespace std;
int main()
{
int a[50],n,cs=0,ha=0;
cin >> n;
for (int i=0;i<n;i++)
{
cin >> a[i];
}
for (int j=1;j<=n;j++)
{
if(a[j]<0 && a[j-1]>0)
cs++;
else if(a[j]>0 && a[j-1]<0)
cs++;
}
cout << cs << endl;
return 0;
}
Please help!
Your problem is that you're running into uninitialized memory, which is causing undefined behaviour. You initialize a[0] through a[n-1] in your input loop and then read from a[0] (with j=1 and a[j-1]) to a[n] (j=n and a[j]) in your calculation loop.
Simply change it to j < n.
If STL is an option for you, you can use std::adjacent_find. This is how you would use it in a complete program:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
vector<int> v { 1 , 3, -5, 8, -9, -10, 4 };
auto signSwitch = [] (int x, int y) { return (abs(x) == x) ^ (abs(y) == y); };
int cnt = 0;
auto i = adjacent_find(begin(v), end(v), signSwitch);
while (i != end(v))
{
cnt++;
i = adjacent_find(i + 1, end(v), signSwitch);
}
cout << cnt;
}
Your second loop should terminate at j < n.
On your second for loop you should not have j go to <=. it should just be
for (int j=1;j<n;j++)