Irregular spacing in writing a palindrome pattern - c++

#include<iostream>
using namespace std;
int main(){
int n;
cin>>n;
for(int i=1;i<=n;i++){
int space=n-i;
for(int j=1;j<=space;j++){
cout<<" ";
}
for(int k=i;k>=1;k--){
cout<<k<<" ";
}
for(int l=2;l<=i;l++){
cout<<l<<" ";
}
cout<<endl;
}
return 0;
}
I wrote this code for printing a palindrome pattern but the output I received has irregular spacing and no matter what I couldn't find the error in the code.

I assume the "correct" spacing is where all the 1's line up. Here are some steps you could try to solve the problem:
1. How is the position of 1 determined?
The position should be determined by the last line, starting with n — since we don't require any spaces on the front, according to your program.
2. At which position will 1 appear on the last line?
Before the character 1, there are spaces and other numbers — n-1 numbers from n to 2, and also the same number of spaces, since 1 space is presented after every character, except the last, which doesn't matter here. In total, 2(n-1) characters before 1.
3. Finally, How many spaces are required before line k?
For line k, we can use the above step to know that before the character 1 there are 2(k-1) characters, but we need 2(n-1) to fill the length. Thus, we can obtain the required space in front of the line as 2(n-1)-2(k-1) = 2(n-k). That's why you need the "times 2" over there on line 7.
Try to find steps toward problems.

Related

Rapid Typing Coding Challenge

The question asks for total time that will be required to type a string on a keyboard, which is represented as two dimensional matrix of characters, with one finger.
input:
2 31
YLrJpXOygVUl6MqBIRFWuAKsH7Gw4Z8
kE0tTQdP1CcxSjamizon9e5NfvDbh32
YE0
The first line contains n and m as input denoting dimensions of the keyboard matrix.
Next n lines contain m characters each denoting the character in the keyboard.
Next line will contain a string S
output:
3
Explanation:
The finger is initially at the first symbol of the keyboard so the time taken to press that key is 0. After that the new key is located at 1,1 so total time taken will be |1-0|+|1-0| i.e. 2 . Now the third key is located at position 1,2 so total time to move to that key will be |2-1|+|1-1| = 1 . So our answer is 3.
The string that's asked to print is in the last input line, YE0, consisting of letters from the above 2-D matrix.
The time calculation logic is:
If you are at cell (x1,y1) of the keyboard and now you want to press the key at (x2,y2) then the time taken will be |x1-x2| + |y1-y2|. You need to calculate the total time taken to type the complete string.
In case it is impossible to type the string you have to print -1.
#include<bits/stdc++.h>
using namespace std;
int main() {
int n,m;
cin>>n>>m;
unordered_map<char, pair<int, int>> map1;
for(int i=0;i<n;i++){
string s;
cin>>s;
for(int j=0;j<m;j++) {
map1.insert({s[j], make_pair(i,j)});
}
}
string key;
cin>>key;
long long total=0;
pair<int,int> sp;
for(int i=0;i<key.length();i++) {
if(map1.find(key[i])==map1.end()) {
total=-1;
break;
} else {
auto it = map1.find(key[i]);
if(i==0) sp=it->second;
pair<int,int> p = it->second;
total+=(abs(p.first-sp.first) + abs(p.second-sp.second));
sp=p;
}
}
cout<<total;
}
This solution is partially accepted and I am not able to figure out the edge cases for which its failing. Can somebody help me?
Here is one failing test case for free.
2 31
YLrJpXOygVUl6MqBIRFWuAKsH7Gw4Z8
kE0tTQdP1CcxSjamizon9e5NfvDbh32
YE 0
Should be -1 because the blank is not in the key matrix.
It fails because you only read in the "word" until first whitespace.
Here is another one:
2 31
YLrJpXOygVUl6MqBIRFW AKsH7Gw4Z8
kE0tTQdP1CcxSjamizon9e5NfvDbh32
Y E0
Shoudl not be -1, but is. Same problem, but with the matrix.
So what you need to do is change your input reading to include white space.
It's mentioned in the question that, "The finger is initially at the first symbol of the keyboard" so when you are parsing the key
In your code if(i==0) sp=it->second; should start from {0,0} to consider the movement from the first symbol of the keyboard to the first symbol of the key.

Time limit exceeded on test 10 code forces

hello i am a beginner in programming and am in the array lessons ,i just know very basics like if conditions and loops and data types , and when i try to solve this problem.
Problem Description
When Serezha was three years old, he was given a set of cards with letters for his birthday. They were arranged into words in the way which formed the boy's mother favorite number in binary notation. Serezha started playing with them immediately and shuffled them because he wasn't yet able to read. His father decided to rearrange them. Help him restore the original number, on condition that it was the maximum possible one.
Input Specification
The first line contains a single integer n (1⩽n⩽105) — the length of the string. The second line contains a string consisting of English lowercase letters: 'z', 'e', 'r', 'o' and 'n'.
It is guaranteed that it is possible to rearrange the letters in such a way that they form a sequence of words, each being either "zero" which corresponds to the digit 00 or "one" which corresponds to the digit 11.
Output Specification
Print the maximum possible number in binary notation. Print binary digits separated by a space. The leading zeroes are allowed.
Sample input:
4
ezor
Output:
0
Sample Input:
10
nznooeeoer
Output:
1 1 0
i got Time limit exceeded on test 10 code forces and that is my code
#include <iostream>
using namespace std;
int main()
{
int n;
char arr[10000];
cin >> n;
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
for (int i = 0; i < n; i++) {
if (arr[i] == 'n') {
cout << "1"
<< " ";
}
}
for (int i = 0; i < n; i++) {
if (arr[i] == 'z') {
cout << "0"
<< " ";
}
}
}
Your problem is a buffer overrun. You put an awful 10K array on the stack, but the problem description says you can have up to 100K characters.
After your array fills up, you start overwriting the stack, including the variable n. This makes you try to read too many characters. When your program gets to the end of the input, it waits forever for more.
Instead of putting an even more awful 100K array on the stack, just count the number of z's and n's as you're reading the input, and don't bother storing the string at all.
According to the compromise (applicable to homework and challenge questions) described here
How do I ask and answer homework questions?
I will hint, without giving a code solution.
In order to fix TLEs you need to be more efficient.
In this case I'd start by getting rid of one of the three loops and of all of the array accesses.
You only need to count two things during input and one output loop.

Using stringstream to indent/center output

I'm learning c++ and got the project to send a pascal's triangle to output (after n-rows of calculation)., getting output like this, stored in a stringstream "buffer"
1
1 1
1 2 1
1 3 3 1
But what I want is rather
1
1 1
1 2 1
1 3 3 1
My idea was: calculate the difference of the last line and current line length (I know that the last one is the longest). Then pad each row using spaces (half of the line-length-difference).
My Problem now is:
I didn't get how getLine works, neither how I might extract a specific (-> last) line
I don't know and could not find how to edit one specific line in a stringstream
Somehow I got the feeling that I'm not on the best way using stringstream.
So this is rather a common question: How'd you solve this problem and if possible with stringstreams - how?
To know the indentation of the first line, you would need to know the number of lines in the input. Therefore you must first read in all of the input. I chose to use a vector to store the values for the convenience of the .size() member function which will give the total number of lines after reading in all input.
#include<iostream>
#include<sstream>
#include<vector>
#include<iomanip> // For setw
using namespace std;
int main()
{
stringstream ss;
vector<string> lines;
string s;
//Read all of the lines into a vector
while(getline(cin,s))
lines.push_back(s);
// setw() - sets the width of the line being output
// right - specifies that the output should be right justified
for(int i=0,sz=lines.size();i<sz;++i)
ss << setw((sz - i) + lines[i].length()) << right << lines[i] << endl;
cout << ss.str();
return 0;
}
In this example, I am using setw to set the width of the line to be right justified. The padding on the left side of the string is given by (sz - i) where sz is the total number of lines and i is the current line. Therefore every subsequent line has 1 less space on the left hand side.
Next I need to add in the original size of the line (lines[i].length()), otherwise the line will not contain a large enough space for the resulting string to have the correct padding on the left hand side.
setw((sz - i) + lines[i].length())
Hope this helps!
If you have access to the code that writes the initial output, and if you know the number of lines N you are writing, you could simply do:
for(int i = 0; i < N; ++i) {
for(int j = 0; j < N - 1 - i; ++j)
sstr << " "; // write N - 1 - i spaces, no spaces for i == N.
// now write your numbers the way you currently do
}

Solving "Welcome to Code Jam" from Google Code Jam 2009

I am trying to solve the following code jam question,ive made some progress but for few cases my code give wrong outputs..
Welcome to Code jam
So i stumbled on a solution by dev "rem" from russia.
I've no idea how his/her solution is working correctly.. the code...
const string target = "welcome to code jam";
char buf[1<<20];
int main() {
freopen("input.txt", "rt", stdin);
freopen("output.txt", "wt", stdout);
gets(buf);
FOR(test, 1, atoi(buf)) {
gets(buf);
string s(buf);
int n = size(s);
int k = size(target);
vector<vector<int> > dp(n+1, vector<int>(k+1));
dp[0][0] = 1;
const int mod = 10000;
assert(k == 19);
REP(i, n) REP(j, k+1) {// Whats happening here
dp[i+1][j] = (dp[i+1][j]+dp[i][j])%mod;
if (j < k && s[i] == target[j])
dp[i+1][j+1] = (dp[i+1][j+1]+dp[i][j])%mod;
}
printf("Case #%d: %04d\n", test, dp[n][k]);
}
exit(0);
}//credit rem
Can somebody explain whats happening in the two loops?
Thanks.
What he is doing: dynamic programming, this far you can see too.
He has 2D array and you need to understand what is its semantics.
The fact is that dp[i][j] counts the number of ways he can get a subsequence of the first j letters of welcome to code jam using all the letters in the input string upto the ith index. Both indexes are 1 -based to allow for the case of not taking any letters from the strings.
For example if the input is:
welcome to code jjam
The values of dp in different situations are going to be:
dp[1][1] = 1; // first letter is w. perfect just the goal
dp[1][2] = 0; // no way to have two letters in just one-letter string
dp[2][2] = 1; // again: perfect
dp[1][2] = 1; // here we ignore the e. We just need the w.
dp[7][2] = 2; // two ways to construct we: [we]lcome and [w]elcom[e].
The loop you are specifically asking about calculates new dynamic values based on the already calculated ones.
Whoa, I was practicing this problem few days ago and and stumbled across this question.
I suspect that saying "he's doing dynamic programming" won't not explain too much if you did not study DP.
I can give clearer implementation and easier explanation:
string phrase = "welcome to code jam"; // S
string text; getline(cin, text); // T
vector<int> ob(text.size(), 1);
int ans = 0;
for (int p = 0; p < phrase.size(); ++p) {
ans = 0;
for (int i = 0; i < text.size(); ++i) {
if (text[i] == phrase[p]) ans = (ans + ob[i]) % 10000;
ob[i] = ans;
}
}
cout << setfill('0') << setw(4) << ans << endl;
To solve the problem if S had only one character S[0] we could just count number of its occurrences.
If it had only two characters S[0..1] we see that each occurrence T[i]==S[1] increases answer by the number of occurrences of S[0] before index i.
For three characters S[0..2] each occurrence T[i]==S[2] similarly increases answer by number of occurrences of S[0..1] before index i. This number is the same as the answer value at the moment the previous paragraph had processed T[i].
If there were four characters, the answer would be increasing by number of occurrences of the previous three before each index at which fourth character is found, and so on.
As every other step uses values from the previous ones, this can be solved incrementally. On each step p we need to know number of occurrences of previous substring S[0..p-1] before any index i, which can be kept in array of integers ob of the same length as T. Then the answer goes up by ob[i] whenever we encounter S[p] at i. And to prepare ob for the next step, we also update each ob[i] to be the number of occurrences of S[0..p] instead — i.e. to the current answer value.
By the end the latest answer value (and the last element of ob) contain the number of occurrences of whole S in whole T, and that is the final answer.
Notice that it starts with ob filled with ones. The first step is different from the rest; but counting number of occurrences of S[0] means increasing answer by 1 on each occurrence, which is what all other steps do, except that they increase by ob[i]. So when every ob[i] is initially 1, the first step will run just like all others, using the same code.

Build a pyramid with numbers between 1 and the inserted integer

i'm trying to build a pyramid with numbers between 1 and the inserted number. For example, if i insert 6 to the integer, that the piramid will be as there:
12345654321
234565432
3456543
45654
565
6
I tried using a for loop but i get in any line one or ++ numbers to 6.
This is the code:
#include<stdio.h>
#include <iostream>
#include <conio.h>
int main()
{
int i,j,d;
std::cin >> d;
for(i=1;i<=d;i++)
{
for(j=1;j<=i;j++)
printf("%d",j);
printf("\n");
}
getch();
return 0;
}
How can i solve this problem building a pyramid like the shown.
Since this is homework, I won't paste an algorithm, but here's a few hints:
This 12345654321 can be printed by counting from one to six and then back to one.
This __3456543__ means that for numbers smaller than n, you have to output a _ instead, where n depends on the level you are printing.
Define your loop variables within the loop: for(int i=1;i<=d;i++) ... They are only interesting within the loop, and access outside the loop is usually an error, which is then flagged by the compiler.
There's no need to for the getch(); at the end. When you're in the debugger, you can put a breakpoint on the last line. If you aren't you don't want to have to press a key just to end your program.
If you use std::cout << j and std::cout << '\n' for outputting, you don't need printf() either. (Once you want formatting, many will tell you that printf format strings are easier. I don't believe that, but would accept it, if it weren't that you can crash any application with an ill-formed printf format string, while it's much harder to come up with a way to crash your app using streams.)
There you go:
for(j=i;j<=d;j++)
Also you forgot about formatting and the right side of the pyramid, but I think that's out of scope for this question and you can figure the code yourself :)
Try to have the first line working the way you want.
Repeat it d times, where d is the number entered by the user.
Notice that on line l, numbers < l are replaced by spaces.
Consider this: you have D rows, 1..D. Six rows means your rows are numbered 1 to 6. Now, for each row d:
print d-1 space characters. First row has no spaces, second has one and so on.
print the numbers d..D. So on the first line you print 1..6, on the second you print 2..6.
print the numbers D-1..d. So on the first line you print 5..1, on the second you print 5..2
print a new line