Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I want my program to create and output 4 sets, each having 13 numeric elements.
Expected output is 1.1, 1.2, ..., 1.13, 2.13, ..., 4.13 (set and element is represented as set.element):
Set Element
1 1
1 2
...
1 13
2 1
2 2
...
2 13
...
4 13
I also want to store this data in a std::vector so that I can access and reuse it by using functions at or operator[].
My current output is 0. I want to display the output at a particular index, say output at index 30.
Code:
vector<int> storein(52);
int sortn;
for(int i = 0; i < 4; i++)
{
for(int j = 0; j < 13; j++)
{
storein.push_back(j);
cout << i + 1 << "\t" << j << endl;
}
}
// cout << storein.size();
cout << storein[30] << endl;
Live example: http://ideone.com/XcGAyX
vector<int> storein(52);
The vector now has 52 elements.
The calls to push_back add more elements to the end of the vector. When you refer to storein[30], you find one of the original 52 elements.
Try this:
vector<int> storein;
In general, when you start to use a new tool, you should try the simplest things you can do, test the results, and build up to more complex operations. This is a vital skill.
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 4 months ago.
Improve this question
I am a student and am looking for a way to solve a problem online with content like the image below
Please solve it for me with C++ code
If you want to solve such a problem, then you need split the big problem in to smaller problems. Then the solution is easier.
So, let's first strip of the '*'. They are always starting a row and ending it. This is not needed in the beginning.
Next. You see some sequences, like
1
121
12321
1234321
123454321
1234321
12321
121
1
You see that the digits will be incremented by one until we hit the maximum value for this row and then decremented again until they are 1.
The decreasing numbers are also not important at the moment, because, it is simple to decrement them from the maximum number.
Stripping of the decremented numbers, we will get:
1
12
123
1234
12345
1234
123
12
1
And this looks like a triangle and can be generated mathematically by a typical triangular function.
We want to calculate the maximum number in a row from the row value istelf. Applying the algorithm from the triangular function, will always result in a formular with the "abs"-function. So taking the absolute value.
We will then get something like the below:
Row 5-abs(Row-5)
0 0
1 1
2 2
3 3
4 4
5 5
6 4
7 3
8 2
9 1
10 0
We see also that the number of output lines is double the input value.
We can then do a simple increment/decrement loop, to show the digits according to the before shown values.
Then we add a little bit the output of the "". Please note, that the "closing" star "" at the end of the line is not needed in the first and last row.
Having explained all the above, we can now start writing the code. There are really many many potential solutions, and I just show you one of them as an example.
Please have a look and implement your own solution.
#include <iostream>
#include <cmath>
int main() {
// Tell user what to do
std::cout << "\nPlease add number for the triangle: ";
// Get the maximum extent from the user. Limit values
int maxN{};
if ((std::cin >> maxN) and (maxN >= 0) and (maxN < 10)) {
// Now we want to print row by row
for (int row=0; row <= (maxN * 2); ++row) {
// Calculate the maximum value that should be shown in this row
int maxValueForRow = maxN - std::abs(row-maxN);
// You may uncomment the following line for getting more info
//std::cout << maxValueForRow << '\t';
// Always print at least on beginning star
std::cout << '*';
// Now we want to print the digits. Start counting with 0
int i = 0;
// Print and increment digits
for (i = 0; i < maxValueForRow; ++i) std::cout << i+1;
// And now decrement the digits and print them
for (i=i-2; i >= 0; --i) std::cout << i+1;
// Show closing star only, if we are not in first or last row
if (maxValueForRow > 0) std::cout << '*';
// Start a new line
std::cout << '\n';
}
}
else std::cerr << "\n\nError: Invalid input\n";
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I want to obtain the absolute difference of the sum of left and right diagonal of the given 2d array.
I have written the following function-
int diagonalDifference(vector<vector<int>> arr) {
int n=arr.size();
int summ1=0,summ2=0,result=0;
for(int i=0;i<n;i++)
{ for(int j=0;j<n;j++)
{
if(i==j)
{ summ1=summ1+arr[i][j];}
else if((i+j)==(n-1))
{ summ2=summ2+arr[i][j];}
}
}
result=abs(summ1-summ2);
return result;
}
input array
11 2 4
4 5 6
10 8 -12
Explanation- summ1=11+5+(-12)
summ2=4++5+10 result=|4-19|=|-15|=15
expected output: 15
The output I am getting is 10
Here is a solution in O(n) complexity. reference
for (int i = 0; i < n; i++)
{
summ1 += arr[i][i];
summ2 += arr[i][n-i-1];
}
The else-if should be an if by itself.
The else-if prevents the 5 from being added to summ2. Which means the final calculation is: (11+5-12)-(4+10) = -10. Whose absolute value is 10.
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 2 years ago.
Improve this question
Problem statement: Given an undirected graph E. Build a C++ program to color it using greedy algorithm. You will read input from the file "graph.txt", the first line contains the total number of nodes n and the total number of edges m, each of the (m+1) line contains two positive integers representing an edge. The result should be printed out to the file "coloredgraph.dot", which represents the colored graph in DOT language. (Nodes are indexed from 1 to n)
For example:
Input:
5 5
1 2
2 3
3 4
4 1
1 5
Output:
graph E
{
5 [fillcolor=red, style=filled];
4 [fillcolor=red, style=filled];
1 [fillcolor=green, style=filled];
3 [fillcolor=green, style=filled];
2 [fillcolor=red, style=filled];
1 -- 2;
2 -- 3;
3 -- 4;
4 -- 1;
1 -- 5;
}
I built a C++ program to color the graph and then stored the result in array color[] (in which color[i-1] is the color of nodes i). For example, from the input above, i got the result color[] = {0, 1, 0, 1, 1} (I used number 0 -> n-1 to represent colors. These numbers could represent any colour available in DOT/Graphviz, different numbers mean different colours. In this case, 0 could mean black/white/etc and 1 could mean green/blue/etc, but 1 and 0 have to represent two different colours). But i'm currently stuck at how the result that i found could be converted to a .dot file with the format as required above. I'm just a beginner in C++ and i have no prior experience with DOT or Graphviz. Could anyone help me to print the output as required, using the result that I found? Many thanks for any advice.Greedy algorithm implementation can be found here: https://www.geeksforgeeks.org/graph-coloring-set-2-greedy-algorithm/ P/s : Sorry for my bad English
You can print the file with:
std::cout << "graph E\n{\n";
for (std::size_t i = 0; i < nodes; ++i) {
std::cout << (i+1) << "[fillcolor=" << color[i] << ", style=filled];\n";
}
for (std::size_t i = 0; i < edges.size(); ++i) {
std::cout << edges[i][0] << " -- " << edges[i][1] << ";\n";
}
std::cout << "}\n";
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 am taking a course on edx.org Introduction to C++ by Microsoft. I get unwanted output when looping through a single dimensional array. The code is below.
<#include <iostream>
int main() {
int arrayName[10] = { 1,2,3,4,5,6,7,8,9,10 };
for (int i = 1; arrayName[i] <= 20; i++) {
std::cout << i << std::endl;
}
The output of this is:
1
2
3
4
5
6
7
8
9
10
11
Where does the 11 come from? And, if I make i=0, it also prints a 0. How does it print more than 10? And, when I try to change arrayName[10] to arrayName[9], I get a compiler error that there are too many initialized values:
int arrayName[10] = { 1,2,3,4,5,6,7,8,9,10 };
do {
std::cout << i << std::endl;
i++;
} while (arrayName[i] < 5);
The output is:
12
13
14
15
16
17
18
That do-while loop outputs 7 integers that I did not specify to be included in the arrayName[] array.
I don't know what I am doing wrong or what I am not understanding.
Please help. Thank you!
First, note that arrays in c++ start at index 0. So in int arrayName[3] = {10, 42, 88}; then arrayName[1] is 42, not 10. That means the last element in this array is int arrayName[2]. There is no element at index 3.
Your array only contains 10 elements (indices 0 to 9). The standard does not specify what happens when you access an element past the end of an array, anything can happen. In your case, arrayName[10] and arrayName[11] happens to give you something less than or equal to 20, and then arrayName[12] gave you something greater than 20, ending the loop. If you try it on another computer, or even at a different time, the results will vary. It might also crash (this is the best case scenario).
See this answer for more information on undefined behavior.
I finally found this: Correct way of loop through the C++ arrays, answer by https://stackoverflow.com/users/1619294/mark-garcia.
Changed my code to:
std::cout << "Looping through arrayName3 with std::array and letting the compiler determine how many objects to print:" << std::endl;
// Need to #include <array>
std::array<int, 10> arrayName3 = { 1,2,3,4,5,6,7,8,9,10 };
for (const auto& i : arrayName3) // Range-for
{
std::cout << i << std::endl;
}
The output was what I wanted:
1
2
3
4
5
6
7
8
9
10
This let's the compiler know it is deciding what to output. It would be great to know how to change this to control how many indices to loop through.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am working on an assignment where I am supposed to try out a class I made in four different ways.
This shall be done 100 times in every way, and every single of those 100 iterations contains another for-loop wich runs 5000 iterations.
My problem is that. whilst running, the program randomly stops. It just stops.
No exception. No breakpoint. No crash. No nothing.
It just stops computing.
I've written down a couple of the places it stops
Simplifyed code:
for(int i = 0; i < 100; i++)
{
//Some stuff
for(int j = 0; j < 5000; j++)
{
//Some other stuff
cout << i << "\t" << j << endl;
}
}
Som of the places it has stopped computing at are:
3 3564
1 2273
1 4999
2 4999
0 3430
7 4566
1 4916
0 4999
So the only pattern I see is that it quite often stops at 4999 of the "j-loop" and very early in the "i-loop".
I am really confused about this since I'm sure that what I'm doing in the loops should not be a problem.
Please help!
Complete code Link
In the first line:
for(int i; i < 100; i++)
the variable i is not initialized. So it contains an arbitrary value that gets incremented every iteration and eventually it stops. Try initializing it: for(int i = 0; i < 100; i++).