Print all partitions of a given number - c++

The task is to write a C++ recursive function, that receives an integer and prints all of it partitions. (with importance to order)
Examples:
n=1 the only permutation is {1}
n=2 the permutations are {1,1},{2}
n=3 the permutations are {1,1,1},{1,2},{2,1},{3}
n=4 the permutations are {1,1,1,1},{1,1,2},{1,2,1},{1,3},{2,1,1},{2,2},{3,1},{4}
note the importance for order, for example for n=3 both {1,2} and {2,1} are different and valid answers.
Here is my solution which contains a bug that I'm having a hard time to trace:
#include <iostream>
#include <string>
#include <sstream>
#include <stack>
using namespace std;
stringstream g_ss_str("");
void printSums(int n){
static stack<string> strings;
if (n==0){
cout<<g_ss_str.str()<<endl;
return;
}
for (int i=1; i<=n; ++i){
g_ss_str<<i<<" ";
strings.push(g_ss_str.str());
printSums(n-i);
if (!strings.empty()) {
g_ss_str.str(strings.top());
strings.pop();
}
}
}
The problem starts with n=3, in that case the output I get is:
1 1 1
2 1
2 1
3
Instead of:
1 1 1
1 2
2 1
3
Appreciate your help!

You are playing some unnecessarily complicated games with your stringstream and your stack. Try something like this:
void printSumsHelper(int n, const string& prefix) {
if (n==0){
cout << prefix << endl;
return;
}
for (int i=1; i<=n; ++i) {
ostringstream ss;
ss << prefix << i << ' ';
printSumsHelper(n - i, ss.str());
}
}
void printSums(int n){
printSumsHelper(n, "");
}

Related

Store Matrix with integer from a text file into an array in c++

I have a file named matrices.txt that has two matrices that are 3 by 3.
They are:
1 2 3
4 5 6
7 8 9
1 2 3
4 5 6
7 8 9
I'm trying the read from this file and store it into an array proto_matrix to later split that into two matrices.
The problem I'm having is that I can't store the numbers in the array.
My code is
#include <iostream>
#include <fstream>
using namespace std;
void main()
{
int i = 0, j, k = 0, n, dimension;
cout << "Enter the dimension of square matrices (3 by 3 would be 3) \n";
cin >> n;
dimension = n * n;
int proto_matrix[2 * dimension];
// make array of two matrices combined, this will be split into two matrices
ifstream matrix_file("matrices.txt");
while(matrix_file)
{
matrix_file >> proto_matrix[i];
}
matrix_file.close();
}
I tried debugging the code and it seems like the no integer is stored in the array, just random numbers.
This:
int proto_matrix[2 * dimension];
is a Variable Length Array (VLA), which is not Standard C++, but is supported by some compiler extensions. If compile with g++ -pedantic main.cpp, you will surely get an error.
That means that you need to dynamically allocate your memory, if you had to use an array.
You really don't though, C++ offers std::vector, which can achieve what you want relatively easily. I say relatively, because you have two matrices in one file, which makes parsing the file a bit tricky. Usually we put the one matrix in one file, and the other matrix to another file.
A 2D array can be represented as a 2D vector.
You want two matrices, thus two 2D vectors.
For that reason, I will use an array of size 2 (fixed size!), where every element is going to be a 2D vector.
Moreover, I will keep track of which matrix I am reading from the file right now (the first or the second), and how many rows I have read currently, in order to populate the correct cell of the matrix.
index is going to be equal to 0 or 1, to index the array.
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <sstream>
using namespace std;
int main()
{
int i = 0, j, k = 0, n, dimension;
cout << "Enter the dimension of square matrices (3 by 3 would be 3) \n";
cin >> n;
dimension = n * n;
vector< vector<int> > v[2];
v[0].resize(n);
v[1].resize(n);
// make array of two matrices combined, this will be split into two matrices
ifstream matrix_file("matrices.txt");
string line;
int rows_read = 0, cols_read = 0, index = 0;
while (std::getline(matrix_file, line))
{
std::istringstream iss(line);
int a, b, c;
if (!(iss >> a >> b >> c)) { break; } // error
// process tuple (a, b, c)
if(index == 0 && rows_read >= n)
{
rows_read = 0;
index = 1;
}
//cout<<"rows = " << rows_read << " " << index<<endl;
v[index][rows_read].push_back(a);
v[index][rows_read].push_back(b);
v[index][rows_read++].push_back(c);
}
matrix_file.close();
for(int i = 0; i < 2; ++i)
{
cout << "Printing matrix " << i << endl;
for(auto& matrix: v[i])
{
for(auto& number: matrix)
cout << number << " ";
cout << endl;
}
}
return 0;
}
Output:
Printing matrix 0
1 2 3
4 5 6
7 8 9
Printing matrix 1
1 2 3
4 5 6
7 8 9
PS: Unrelated to your problem, but What should main() return in C and C++? An int.
Based on my answer, I will post here a cleaner example, which achieves what your code tries to achieve: Read all the numbers in a 1D data structure (which will be split in two matrices somehow later).
So for that case, the code boils down to just this:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <sstream>
using namespace std;
int main()
{
int i = 0, j, k = 0, n, dimension;
cout << "Enter the dimension of square matrices (3 by 3 would be 3) \n";
cin >> n;
dimension = n * n;
// make array of two matrices combined, this will be split into two matrices
vector<int> proto_matrix;
ifstream matrix_file("matrices.txt");
string line;
while (std::getline(matrix_file, line))
{
std::istringstream iss(line);
int a, b, c;
if (!(iss >> a >> b >> c)) { break; } // error
proto_matrix.push_back(a);
proto_matrix.push_back(b);
proto_matrix.push_back(c);
}
matrix_file.close();
for(auto& number: proto_matrix)
cout << number << "\n";
return 0;
}
You could just read all the values into a flat container (such as std::vector) and do the re-arrangement at a later point. The following code may give you an idea:
#include <vector>
#include <fstream>
#include <iostream>
int main() {
std::vector<int> values;
std::ifstream fp("matrices.txt");
for (int value; fp >> value; ) {
values.emplace_back(value);
}
std::cout << "I read " << values.size() << " values:\n";
for (auto && value : values) std::cout << value << " ";
std::cout << "\n";
}
Result:
$ clang++ matrixread.cpp -std=c++17
$ ./a.out
I read 18 values:
1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9
You don't increment i, thus always writing to the first element. It should be:
matrix_file >> proto_matrix[i++];

convert an array string to intger c++ (beginner)

I have a text file which that contains only numbers inside , and i have successfully pulled the numbers from the file and stored it inside an array:
my problem is that the array is "string" and i cant do mathematical operations on the array like Addition and Subtraction
I have tried to use atoi(array[i][j].c_str()) to convert it to intger
but it gives me only the first digit of a number!
my program looks like this for now , its a mess I know :(
#include <iostream>
#include <fstream>
#include <string>
#include <stdlib.h>
using namespace std;
int main()
{
ifstream iFile("input.txt");
string line;
string array[7][7];
for (int i=0;i<7;i++){
for (int j=0;j<6;j++){
getline(iFile,line);
if (!line.empty()){
array[i][j]=line;
}
else {
break;
}
}
}
cout<<"number of processes is: "<<array[0][0]<<endl;
cout<<"resource types: "<<array[1][0]<<endl<<endl;
cout<<"Allocation Matrix:"<<endl;
cout<<" A B C D"<<endl;
cout<<"0: "<<array[2][0]<<endl;
cout<<"1: "<<array[2][1]<<endl;
cout<<"2: "<<array[2][2]<<endl;
cout<<"3: "<<array[2][3]<<endl;
cout<<"4: "<<array[2][4]<<endl;
cout<<"Max Matrix:"<<endl;
cout<<" A B C D"<<endl;
cout<<"0: "<<array[3][0]<<endl;
cout<<"1: "<<array[3][1]<<endl;
cout<<"2: "<<array[3][2]<<endl;
cout<<"3: "<<array[3][3]<<endl;
cout<<"4: "<<array[3][4]<<endl;
cout<<"Need Matrix:"<<endl;
cout<<" A B C D"<<endl;
//cout<<"0: "<<array[3][1]+array[2][1]<<endl;
//int c= atoi(array[3][1].c_str());
//int c2= atoi(array[3][1].c_str());
//cout<<c+c2<<endl;
return 0;
}
my input.txt file looks like this:
5
4
0 0 1 2
1 0 0 0
1 3 5 4
0 6 3 2
0 0 1 4
0 0 1 2
1 7 5 0
2 3 5 6
0 6 5 2
0 6 5 6
1 5 2 0
1:0 4 2 0
edit:
note:if there is an empty line >> stop!
the program is based on banker algorithm which takes the first number from the input.txt as the numbers of of processes
then takes the second number as the numbers of of resource types
then takes the next numbers that there is no empty line between them as Allocation Matrix
then takes the next numbers that there is no empty line between them as max Matrix
and here is my problem when i want do Subtraction between Allocation Matrix and max Matrix because both are strings !
as for 1:0 4 2 0 it means do some operations with process number 1
You can use atoi but in c++ you have better options.
in c++ you can easily use stringstream to convert these types.
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int convert_str_to_int(const string& str) {
int val;
stringstream ss;
ss << str;
ss >> val;
return val;
}
int main () {
string str = "1024";
int val = convert_str_to_int(str);
cout << "Val is: " << val << ", val/2 is " << val/2 << endl;
}

Counting and getting highest number of digits after decimal

I want to get a count of highest number of digits from an array of decimal numbers.
For example, between 2.1 and 2.01, the resultant counter should be 2 since there are 2 digits after 2.01.
Can anyone please help me with this?
#include<conio.h>
#include<stdio.h>
#include<iostream>
using namespace std;
int main()
{
double z[100],x[100],sml;
int count=0,i=0,n;
cout<<"ENter number of elements\n";
cin>>n;
cout<<"Enter the numbers\n";
for(i=0;i<n;i++)
{
cin>>z[i];
}
x[0]=z[0]-int(z[0]);
i=0;
for(i=0;i<n;i++)
while(z[i]>=0.001&&i<n)
{
x[i]=z[i]-int(z[i]);
i++;
}
for(i=0;i<n;i++)
{
cout<<x[i]<<"\t";
}
sml=x[0];
for(i=0;i<n;i++)
if(sml>x[i])
sml=x[i];
sml=sml-int(sml);
while(sml>=0.001)
{
sml=sml*10;
count++;
sml=sml-int(sml);
}
cout<<endl<<count;
return 0;
}
It's not impossible, it should be pretty easy actually. Cast it to a string, get the substring of the results starting at the decimal and count the result.
For this you will need to look up:
-casting
-indexof
-substring
If you give it a try and can't figure out comment and I will offer you a little more guidance but you should try it yourself first.
EDIT:
I don't see much of an attempt to do what I suggested, it looks like you just posted the code you had. So here is some pseudo code for you to work with:
string stringNum = to_string(decimalNum);
int decimalPos = stringNum.find(".");
string newString = stringNum.substr(decimalPos);
int answer = newString.length();
I pretty well answered it for you, you need to figure out the syntax.
just go ahead and use this:
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main(){
float number[] = {1.234,5.64,2.001,7.11112,3.999};
int a,numAfterDecimal = 0;
for(a=0;a<sizeof(number)/sizeof(*number);a++){
ostringstream buff;
buff<<number[a];
string numStr= buff.str();
int pos = numStr.find(".");
string floatStr = numStr.substr(pos+1);
if(a == 0){
numAfterDecimal = floatStr.length();
}
else if(floatStr.length() > numAfterDecimal){
numAfterDecimal = floatStr.length();
}
}
cout << " higest number of digit after decimal is:"<< numAfterDecimal <<endl ;
}
Answer is already accepted. But just for the fun of it. Here a solution using C++ algorithms.
This will reduce the number of statements in main drastically.
Maybe it helps you to better understand modern C++
#include <iostream>
#include <string>
#include <algorithm>
#include <iterator>
#include <vector>
inline size_t getNumberOfDigitsForFraction(const std::string& s)
{
size_t positionOfDecimalPoint = s.find("."); // Look for decimal point
// And count the numbers of digits after the decimal point
return positionOfDecimalPoint == std::string::npos ? 0 : s.substr(positionOfDecimalPoint+1).size();
}
int main()
{
std::cout << "Enter the number of elements that you want to check: ";
size_t numberOfElementsToCheck{0};
// Read how many data the user wants to process
std::cin >> numberOfElementsToCheck;
// Hier we will store the values
std::vector<std::string> elements(numberOfElementsToCheck);
// Copy all wanted values from std::cin
std::copy_n(std::istream_iterator<std::string>(std::cin),numberOfElementsToCheck,elements.begin());
// Get the Element with maximum digits and print the number of digits
std::cout << "Max number of digits following decimal point: " <<
getNumberOfDigitsForFraction(
*std::max_element(elements.begin(), elements.end(),
[](const std::string &sLeft, const std::string &sRight)
{ return getNumberOfDigitsForFraction(sLeft) < getNumberOfDigitsForFraction(sRight);} )) << '\n';
return 0;
}

Sum all integers in a string C++

I have a C++ string in my code that is like:
"1 2 3 4 5 6 7 8"
I know the string is composed of integers separated by a space char. How can I sum them?
I'm quite a C++ newbie and in Java I'd simply do:
String str = "1 2 3 4 5 6 7 8";
int sum = 0;
for (int i = 0; i < str.split(" ").length; i++ {
sum += Integer.parse(str.split(" ")[i];
}
How can I do just like this with my string object in C++?
Some people suggested me stringstream but I still can't understand this object and I need to read the string entirely, getting every single digit within it.
Thanks in advance!
Update: some guys nicely tried to help me but still it's not working. Perhaps because of some quirk of my problem which I haven't clarified before. So here it goes:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
freopen("variable-exercise.in", "r", stdin);
int sum = 0, start = 0;
string line;
while(getline(cin ,line)) {
istringstream iss(line);
while(iss >> start) {
sum += start;
}
cout << start << endl;
sum = start = 0;
}
return 0;
}
Ah, the input file contains the following:
1
3 4
8 1 1
7 2 9 3
1 1 1 1 1
0 1 2 5 6 10
So, for each line, the program must print the sum of all integers in the string line. This example would generate:
1
7
10
21
5
24
thanks
Some people suggested me stringstream but I still can't understand this object and I need to read the string entirely
I guess you were given a good advice. With std::istringstream you could just read in values one after the other as you would read them from the standard input (or any other input stream).
For instance:
#include <sstream>
#include <string>
#include <iostream>
int main()
{
// Suppose at some time you have this string...
std::string s = "1 2 3 4 5 6 7 8 9 10";
// You can create an istringstream object from it...
std::istringstream iss(s);
int i = 0;
int sum = 0;
// And read all values one after the other...
while (iss >> i)
{
// ...of course updating the sum each time
sum += i;
}
std::cout << sum;
}
Like this:
std::stringstream s("1 2 3 4 5 6 7 8 9");
int n = 0;
int x;
while (s >> x)
n += x;
std::cout << n << std::endl;
After your edit:
cout << start << endl;
This is wrong, you should be printing sum instead:
cout << sum << endl;
I used C code to solve this problem. Here's the final solution:
#include <stdio.h>
#include <string.h>
int main() {
char *c;
char line[100];
int x, sum = 0;
while(gets(line)) {
for(c = strtok(line, " "); c ; c = strtok(NULL, " ")) {
sscanf(c, "%d", &x);
sum += x;
}
printf("%d\n", sum);
sum = 0;
}
return 0;
}
Hope it helps anyone who might have the same problem!

How to use string.substr() function?

I want to make a program that will read some number in string format and output it like this: if the number is 12345 it should then output 12 23 34 45 . I tried using the substr() function from the c++ string library, but it gives me strange results - it outputs 1 23 345 45 instead of the expected result. Why ?
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
int main(void)
{
string a;
cin >> a;
string b;
int c;
for(int i=0;i<a.size()-1;++i)
{
b = a.substr(i,i+1);
c = atoi(b.c_str());
cout << c << " ";
}
cout << endl;
return 0;
}
If I am correct, the second parameter of substr() should be the length of the substring. How about
b = a.substr(i,2);
?
As shown here, the second argument to substr is the length, not the ending position:
string substr ( size_t pos = 0, size_t n = npos ) const;
Generate substring
Returns a string object with its contents initialized to a substring of the current object. This substring is the character sequence that starts at character position pos and has a length of n characters.
Your line b = a.substr(i,i+1); will generate, for values of i:
substr(0,1) = 1
substr(1,2) = 23
substr(2,3) = 345
substr(3,4) = 45 (since your string stops there).
What you need is b = a.substr(i,2);
You should also be aware that your output will look funny for a number like 12045. You'll get 12 20 4 45 due to the fact that you're using atoi() on the string section and outputting that integer. You might want to try just outputing the string itself which will be two characters long:
b = a.substr(i,2);
cout << b << " ";
In fact, the entire thing could be more simply written as:
#include <iostream>
#include <string>
using namespace std;
int main(void) {
string a;
cin >> a;
for (int i = 0; i < a.size() - 1; i++)
cout << a.substr(i,2) << " ";
cout << endl;
return 0;
}
Another interesting variant question can be:
How would you make "12345" as "12 23 34 45" without using another string?
Will following do?
for(int i=0; i < a.size()-1; ++i)
{
//b = a.substr(i, 2);
c = atoi((a.substr(i, 2)).c_str());
cout << c << " ";
}
substr(i,j) means that you start from the index i (assuming the first index to be 0) and take next j chars.
It does not mean going up to the index j.
You can get the above output using following code in c
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
char *str;
clrscr();
printf("\n Enter the string");
gets(str);
for(int i=0;i<strlen(str)-1;i++)
{
for(int j=i;j<=i+1;j++)
printf("%c",str[j]);
printf("\t");
}
getch();
return 0;
}
Possible solution without using substr()
#include<iostream>
#include<string>
using namespace std;
int main() {
string c="12345";
int p=0;
for(int i=0;i<c.length();i++) {
cout<<c[i];
p++;
if (p % 2 == 0 && i != c.length()-1) {
cout<<" "<<c[i];
p++;
}
}
}
Possible solution with string_view
void do_it_with_string_view( void )
{
std::string a { "12345" };
for ( std::string_view v { a }; v.size() - 1; v.remove_prefix( 1 ) )
std::cout << v.substr( 0, 2 ) << " ";
std::cout << std::endl;
}
The string constructor can be used to get a copy of a substring.
string(const string& str, size_t pos, size_t n)
For example...
b = string(a, i, 2); // substring of a from position i, including 2 characters
This differs from substr in that the length n cannot be omitted. I offer this only as an alternative, not as an improvement.