I created a matrix class which contains an vector of vectors of a point object (another class i made). Every point in the matrix is walkable or not walkable (the matrix is actually a maze). 1 is walkable, 0 is not.
I want to get the matrix in this form:
4 4 //size of the maze (matrix)
1 0 1 0 (enter)
1 1 0 0 (enter)
0 1 1 0 (enter)
1 0 1 1 (enter)
I tried to get row by row, and then seperate the points (1s and 0s) by stream string. This is my code:
istream & operator >> (istream& input, maze inMaze) {
string rowStream;
string tmpWord;
int num, colCounter; //num = 1 or 0, colCounter = col index
for (int rowIndex = 0; rowIndex < inMaze.rowsSize; rowIndex++){ //over the rows
int colIndex = 0;
bool isWalkable;
input >> rowStream; //input to string
stringstream seperateWord(rowStream); //string to stream string
while (seperateWord >> tmpWord) { //sstring seperate space bars in string, reprasant a row
if (tmpWord == "0") isWalkable = false; //in maze matrix, zero means not a path
else if (tmpWord == "1") isWalkable = true; //else 1 = a path
else throw "invalid input"; //wrong input (num in matrix not 0 nor 1)
inMaze.getMaze[rowIndex][colIndex].setPoint(rowIndex, colIndex, isWalkable); //set point in maze
colIndex++; //next col
} //done filling a row, to next row
}
}
It didnt work. It always ended getting the input after the first row, and filled everything with 1s.
What did I do wrong?
Thank you for your help! and sorry for my poor English.. :-)
The problem in line input >> rowStream; replace it with getline(input,line); and line is string type.
the operator >> of file take one argument ended with white space!
like: 00 1 0 11, first argument is 00, second is 1...
and in your case using stringstream which mean you must take whole line
like: 0 1 0 1 0 1, take it using getline, then use stringstream to get right input. 0 then 1 ...
Related
On the first row, we write a 0. Now in every subsequent row, we look at the previous row and replace each occurrence of 0 with 01, and each occurrence of 1 with 10.
Given row N and index K, return the K-th indexed symbol in row N. (The values of K are 1-indexed.) (1 indexed).
Examples:
Input: N = 1, K = 1
Output: 0
Input: N = 2, K = 1
Output: 0
Input: N = 2, K = 2
Output: 1
Input: N = 4, K = 5
Output: 1
Explanation:
row 1: 0
row 2: 01
row 3: 0110
row 4: 01101001
Link to the Problem:
https://leetcode.com/explore/learn/card/recursion-i/253/conclusion/1675/
Solution:
class Solution {
public:
int kthGrammar(int N, int K) {
if(N==0||K==0)
return 0;
string result="0";
string finals;
int i,j;
for(j=0;j<N-1;j++)
{
for(i=0;i<result.length();i++)
{
if(result[i]=='0')
finals.append("01");
else
finals.append("10");
}
result=finals;
}
return result[K-1]-'0';
}
};
Your finals string remains with old contents. Seems you need to clear it at every loop turn.
Anyway, your approach is not suitable for large inputs - so instead of (huge) string generation consider calculation of needed symbol with some math.
def f(n,k):
if n == 1:
return 0
if k<=pow(2,n-2):
return f(n-1,k)
else:
return 1-f(n-1,k-(pow(2,n-2)))
the above is a better soln. written in python but same logic can be used
I need a program that will output this figure:
1
1 2 1
1 2 4 2 1
1 2 4 8 4 2 1
If you add the numbers on both ends, it will print the output beside it (inward). And then you will also add those two sums and print it again inwardly. Another thing, the input should be the largest number (in this case, number 8) It could be larger than 8 like the figure below.
1
1 2 1
1 2 4 2 1
1 2 4 8 4 2 1
1 2 4 8 16 8 4 2 1
In this case the input is 16. And so on. This is my latest program.
#include<iostream>
using namespace std;
int main(){
int i, j, k, b, a, space=10;
for(int i=0;i<=5;i++){
for(k=0;k<space;k++){
cout<<" ";
}
for(j=1;j<=2*i-1;j=j*2){
cout<<j<<" ";
}
space--;
cout<<endl;
}
system("pause");
return 0;
}
Please help me improve this. It's not yet a pyramid. Help me to output the desired figure at least.
To correctly format your pyramid, supposing you're using fixed width characters, you need to know beforehand some information, e.g.:
what is the largest number that you're going to print.
how many numbers have which width.
Since the pyramid is increasing downwards, this information is available when you print the last line.
So what you need to do is to calculate (but not output, of course) the last line first. Say that you want five rows, then the middle number will be 2^(5-1), i.e. 16. So you will have to output 1 2 4 8 16. The column positions will be 0 (beginning), 2 (0 plus length of "1" plus 1 space), 4 (2 plus 1 plus 1 space), 6 (4 plus 1 plus 1), 8, 11 (8 plus length of "16" which is 2, plus 1 space), 13, 15, 17.
At this point you start output of the first line, beginning at column 5, i.e. at position 8.
The second line will start at column 4, i.e. at position 6.
And so on.
Another possibility is to imagine you're filling a table (as if you were generating a HTML table):
- fill it top to bottom
- "explore" every cell size the same way as above, in any order
- generate column positions accordingly
- print the table top to bottom
This requires only one round of calculations, but needs memory storage for the table itself.
A shortcut is to verify what is the largest number you're gonna print, and format all columns with that width. In this case 16 is 2 characters, so you add one space padding and output all columns padded to 3 character width. This may waste unnecessary space.
The latter case can be implemented using cout.width:
int main() {
int line;
// Read input from standard input
cin >> line;
// We output the pyramid by allocating a fixed width to each number.
// This requires to know beforehand which will be the largest number.
// We can observe that at every line, the largest number is 2 to the
// power of that line number: on line 0, the largest number is 2^0
// which is 1, on line 1 it is 2 which is 2^1... on line 4 it is 16
// which is 2^4. So if we have five lines (from 0 to 4), the largest
// number will be 2 to the 4th.
// Now the length of a number in base 10 is given by the logarithm
// base 10 of that number, truncated, plus 1. For example log10 of
// 1000 is exactly 3, and 3+1 is 4 digits. Log10 of 999 is
// 2.9995654... which truncates to 2, 2+1 is 3 and 999 is 3 digits.
// Here our number is 2 to the power of (line-1).
// By the properties of the logarithm
// this is the same as (line-1)*log10(2), and log10(2) is around 0.3.
// So we multiply (line-1) by log10(2), truncate to integer and add 1
// (or vice versa: we add 1 and then assign to width, which is an
// integer, thereby truncating the value to integer.
// But we need to add another 1 for the padding space (we want 1 2 4
// 2 1, not 12421...). So before assigning, we add 2, not 1.
int width = 2+(line-1)*0.30102999566398119521373889472449;
//////////////////////
// TODO: we're gonna output 2*line+1 strings, each 'width' wide.
// So if (2*line+1)*width > 80 we'd better say it and stop, or the
// output will be sorely messed up, since a terminal is only 80 chars
// wide at the most. Which means that N=9 is the maximum number we
// can print out and still be "nice".
// Having not been asked to do this, we proceed instead.
//////////////////////
// For every line that we need to output...
for (int i = 0; i < line; i++) {
// Pad line-i empty spaces
for (int j = 0; j < (line-i); j++) {
// Set the width of the next cout to "width" bytes
cout.width(width);
cout<<" ";
}
int n = 1;
// output the forward sequence: 1, 2, 4... doubling each time
for (int j = 0; j < i; j++) {
cout.width(width);
cout <<n;
n *= 2;
}
// output the top number, which is the next doubling
cout.width(width);
cout <<n;
// output the sequence in reverse. Halve, output, repeat.
for (int j = 0; j < i; j++) {
n /= 2;
cout.width(width);
cout<<n;
}
// Now n is 1 again (not that we care...), and we output newline
cout <<"\n";
}
// Return 0 to signify "no error".
return 0;
}
Check the Code. This will give the desire output .
#include<iostream>
using namespace std;
int main(){
int line = 4;
for (int i =0; i < line; i++){
for(int j = line - i; j >0 ; j --){
cout<<" ";
}
int temp = 1;
for(int k = 0; k < i + 1; k ++){
cout << " "<<temp;
temp = temp *2;
}
temp /=2;
for(int k =0; k < i; k ++){
temp /=2;
cout << " "<<temp;
}
cout <<"\n";
}
return 0;
}
Output:
1
1 2 1
1 2 4 2 1
1 2 4 8 4 2 1
So, my program is supposed to receive test inputs like:
3
1 0 1
0 1 1
1 0 1
5
1 1 1 0 0
1 1 0 1 1
1 0 1 0 1
0 1 0 1 0
0 1 1 1 1
3
1 0 0
0 1 0
0 0 1
2
1 1
1 1
0
where the single-valued lines (n) are the size of a NxN matrix located in the following n entries like shown above. If n = 0, the program stops. The output must be the biggest sum amongst the columns of the matrix. So I expect outputs like this:
3
4
1
2
After a lot of effort and wasted time, I managed to get the first output correctly, but I noticed the following ones sometimes summed up and suggested some variable was not being reset. Here's my code:
#include <iostream>
using namespace std;
int pop = 0;
int main() {
int n, i, j, k;
cin >> n;
while (n!=0) {
int alunos[n]={0};
pop = 0;
for (i=0;i<n;i++) {
int array[n]={0};
for (j=0;j<n;j++) {
cin >> array[j];
if (array[j]==1) alunos[j]++;
}
}
for (k=0;k<n;k++) {
if(alunos[k]>pop) pop = alunos[k];
}
cout << pop << endl;
cin >> n;
}
return 0;
}
Noticed that I'm outputting pop(the biggest sum) and resetting it to 0 everytime a new n is given. alunos[n] is an array with the sums of each column (also resetted on every while loop) and array[n] is just an auxiliary array for reading each line of input. My outputs with this are:
3
5
6
8
Thanks in advance!
You cannot use initializers with variable length arrays. Either switch to some sort of container:
std::vector<int> alunos(n);
or fill the array with zeros manually:
int alunos[n];
std::fill(alunos, alunos+n, 0);
Also, ignoring errors is unhealthy. Don't do it.
I have matrix of 0 and 1 packed inside vector<int> filled by rows (first row, second row and so on..). How to find index of first and last column and first and last row which does not contain only zeros or only ones inside ?
I have iterated four times with loop and compare but is there faster and more elegant way to do this ?
for example result here is columns with indexes 1 and 4 and rows with 1 and 4.
0 0 0 0 0
0 0 1 0 0
0 1 0 0 1
0 0 0 0 0
0 0 0 1 0
I would say, you just need two iterations: One iteration for rows and one iteration for columns.
If I understand the question right, this coding should show how it could be coded (just a draft):
int firstRow = -1;
int lastRow = -1;
for (row=0; row<numRows; row++) {
int cnt = 0;
for (col=0; col<numCols; col++) {
cnt += vec[row][col];
}
if (cnt != 0 && cnt != numCols) {
if (firstRow == -1) firstRow = row;
lastRow = row;
}
}
// output firstRow, lastRow
Do the same for columns.
This coding is not necessarily faster than four iterations. When four iterations are made from the start and the end, they are faster if the columns are nearer to the limits. But it saves you a little coding.
When the following program is fead the following input (reading from cin):
1 1 1 1 2 1 1 1 1 1 1 1 1 1 1 1
The output is surprising:
1 1 1 2 2 1 1 1 1 1 1 1 1 1 1 1
#include<iostream>
using namespace std;
int main()
{
int arey[3][3];
int i,j;
for(j=0;j<=3;j++)
{
for(i=0;i<=3;i++)
{
cin>>arey[j][i];
}
}
arey[0][0]=1;
arey[3][3]=1;
i=0,j=0;
for(j=0;j<=3;j++)
{
for(i=0;i<=3;i++)
{
cout<<arey[j][i];
}
}
return 0;
}
Can someone explain what I should change to get the same output as the input?
Is the matrix 3x3 or 4x4?
you created 3x3 but the loops run for 4 elements and you also update [3][3]
Basically your indexes overflow and you overwrite a different cell in the matrix.
Update: cheecked your input, use: int arey[4][4];
Arrays use 0 based indices, so the valid range of indices for your
int arey[3][3];
are 0 <= i < 3 and 0 <= j < 3
So you need to change the condition in your for loops to be strictly < instead of <=
I really don't think I understand your question, but this is wrong:
int arey[3][3];
...
for(j=0;j<=3;j++) // <= invalid
...
array[3][3]=1; // out of bounds
arey is a 3*3 array. You can't access arey[3][?], that's out of bounds. The only valid indices are 0..2.
Once you've written past the bounds of your array, your program behavior becomes undefined.