I have a problem with generating a pascal triangle in c++, same algorithm works good in java and in c++ it only works for the first two numbers of every line of the triangle in any other it generates way to big numbers. For example in java it generates:
1 5 10 10 5 1 and in C++: 1 5 1233124 1241241585 32523523500 etc
Here is code:
#include <cstdlib>
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
class Pascal {
private:
int* tab;
int prev1;
int prev2;
public:
Pascal(int n) {
tab = new int[n+1];
prev1=0;
prev2=0;
for(int i = 0; i <= n; i++) {
for(int k = 0; k <= i; k++) {
if (k == 0) {
tab[k] = 1;
prev2 = 1;
} else {
prev1 = tab[k-1] + tab[k];
tab[k-1] = prev2;
prev2 = prev1;
}
}
}
}
int wspolczynnik(int m) {
return tab[m];
}
};
int main (int argc, char* argv[]) {
int n = 0, m = 0;
n = atoi(argv[1]); // konwersja string na int
if (n >= 0)
for (int i = 2; i < argc; i++) {
Pascal *wiersz = new Pascal(n);
m = atoi(argv[i]);
int result = wiersz->wspolczynnik(m);
if (m < 0 || m > n)
cout << m << " - element poza zakresem" << endl;
else
cout << m << " : " << result << endl;
delete[] wiersz;
}
return 0;
}
See if initializing the tab array helps:
tab = new int[n+1]();
Related
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int n = 5;
int nums[] = {0 ,1};
if (n == 0)
{
return 0;
} else if (n == 1)
{
return 1;
} else{
for (int i = 2; i < n + 1; i++)
{
cout << i << endl;
nums[i] = nums[i-2] + nums[i-1];
}
return nums[n]
}
return 0;
}
It is just a simple fibonacci array, but my code only gives stdout one time and it is two. FYI: this code may not be correct to compute the nth term of fibonacci array, but i am strugglling with this for loop.
I think the condition of i < n+1 is not meet, but why this for loop ends
nums[i] has size 2. You can't access nums[i] for i >= 2. An array doesn't grow. You can't change the size of an array. Use a std::vector. You've already included the header. A return statement finishes a function. In case of the main function it causes the program to stop. The return value of the main function by convention describes if the program was successful or errors occurred. You are returning
return nums[n];
That's probably not your intention. I assume you want to print the vector.
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int n = 5;
std::vector<int> nums {0 ,1};
if (n == 0)
{
return 0;
} else if (n == 1) {
return 1;
} else {
nums.reserve(n + 1);
for (int i = 2; i < n + 1; i++)
{
cout << i << '\n';
nums.emplace_back(nums[i-2] + nums[i-1]);
}
for (const auto num : nums)
{
cout << num << '\n';
}
}
return 0;
}
it's because you can't access to nums[2] so the correct version of your code is :
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int n = 5;
int nums[5] = {0 ,1};
if (n == 0)
{
return 0;
} else if (n == 1)
{
return 1;
} else{
for (int i = 2; i < n + 1; i++)
{
cout << i << endl;
nums[i] = nums[i-2] + nums[i-1];
}
return nums[n]
}
return 0;
}
you must provide estimated size to array or you will create vector or some dynamic array..
Your approach always give Segmentation fault;
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int n = 5;
vector<int> nums(n+1);
nums[0]=0;
nums[1]=1;
if (n == 0)
{
return 0;
} else if (n == 1)
{
return 1;
} else{
for (int i = 2; i < n + 1; i++)
{
// cout << i << endl;
nums[i] = nums[i-2] + nums[i-1];
}
for(int i=0;i<n;i++)
{
cout<<nums[i]<<endl; }
}
return 0;
}
*/
I am trying to figure out how to print all the combinations in c++.
Given input is {"abc","xyz"} and desired output is {"ax", "ay", "az", "bx", "by", "bz", "cx", "cy","cz"}
I found this recursion code snippet :
`#include <bits/stdc++.h>
using namespace std;
void printKLengthString(char set[], string sequence, int n, int k) {
if (k == 0){
cout<<sequence<<"\t";
return;
}
for (int i = 0; i < n; i++){
string newSequence;
newSequence=sequence+set[i];
printKLengthString(set, newSequence, n, k - 1);
}
}
int main() {
char set[] = {'a', 'b'};
int n = 2;
int k = 3;
printKLengthString(set, "", n, k);
}`
but I am not able to manipulate it according to my desired inputs
Update 1:
Here is my code:
`#include <bits/stdc++.h>
using namespace std;
void printKLengthString(vector<char> set, string sequence, int n, int k) {
if (k == 0){
cout<<sequence<<"\t";
return;
}
for (int i = 0; i < n; i++){
string newSequence;
newSequence=sequence+set.at(i);
printKLengthString(set, newSequence, n, k - 1);
}
}
int main() {
vector<string> stringIn = {"ab", "xy"};
// int n = 2;
// int k = 2;
// for (int i = 0; i < set.size(); i++) {
// cout << set[i] << "\n";
// }
vector<char> set;
for (int i = 0; i < stringIn.size(); i++) {
for (int j = 0; j < stringIn[0].size(); j++) {
// cout << stringIn[i].at(j) << "\n";
// str += char(set[i].at(j));
set.push_back(stringIn[i].at(j));
}
}
// for (char k: set) {
// cout << k << "\t";
// }
cout << "\n";
// cout << "stringIn Size : " << stringIn.size() << "\n";
// cout << "set Size : " << set.size() << "\n";
int k = stringIn.size();
int n = set.size();
printKLengthString(set, "", n, k);
}`
I am getting output as :
aa ab ax ay ba bb bx by xa xb xx xy ya yb yx yy
which is permutation but I just want the combination , which I am not able to figure out..
Anyone could guide me?
Update 2: I want to scale this for multiple inputs, e.g. {"abc","def","ghi","xyz"}
const unsigned int n1 = strlen(s1);
const unsigned int n2 = strlen(s2);
for (unsigned int i1=0;i1<n1;i1++)
{
for (unsigned int i2=0;i2<n2;i2++)
{
printf("%c%c\n",s1[i1],s2[i2]);
}
}
#include <cstdlib>
#include <iostream>
#include <Math.h>
#include <algorithm>
#include <string>
#include <iterator>
#include <iostream>
#include <vector> // std::vector
using namespace std;
int stepCount, i, x, y, z, j, k, array1Size, array2Size, tester, checker;
int numstring[10] = { 0,1,2,3,4,5,6,7,8,9 };
int numstringTest[10] = { 0,1,2,3,4,5,6,7,7,9 };
int* numbers;
int* differentNumbers;
int* p;
int* otherNumbers;
void stepCounter(int a) {
// determines the step number of the number
if (a / 10 == 0)
stepCount = 1;
else if (a / 100 == 0)
stepCount = 2;
else if (a / 1000 == 0)
stepCount = 3;
else if (a / 10000 == 0)
stepCount = 4;
else if (a / 100000 == 0)
stepCount = 5;
else if (a / 1000000 == 0)
stepCount = 6;
else if (a / 10000000 == 0)
stepCount = 7;
else if (a / 100000000 == 0)
stepCount = 8;
else if (a / 1000000000 == 0)
stepCount = 9;
}
void stepIndicator(int b) {
// indicates each step of the number and pass them into array 'number'
stepCounter(b);
numbers = new int[stepCount];
for (i = stepCount; i>0; i--) {
//
/*
x = (round(pow(10,stepCount+1-i)));
y = (round(pow(10,stepCount-i)));
z = (round(pow(10,stepCount-i)));
*/
x = (int)(pow(10, stepCount + 1 - i) + 0.5);
y = (int)(pow(10, stepCount - i) + 0.5);
numbers[i - 1] = (b%x - b%y) / y;
}
}
int sameNumberCheck(int *array, int arraySize) {
//checks if the array has two or more of same integer inside return 1 if same numbers exist, 0 if not
for (i = 0; i<arraySize - 1; i++) {
//
for (j = i + 1; j<arraySize; j++) {
//
if (array[i] == array[j]) {
//
return 1;
}
}
}
return 0;
}
void getDifferentNumbers(int* array, int arraySize) {
//
k = 0;
j = 0;
checker = 0;
otherNumbers = new int[10 - arraySize]; //exact number of other numbers is 10 - numbers we have
for (i = 0; i<10; i++) {
if ((i>0)&(checker = 0)) {
k++;
otherNumbers[k - 1] = i - 1;
}
//
checker = 0;
for (j = 0; j<arraySize; j++) {
//
p = array + j;
cout << *p << endl; //ilkinde doğru sonra yanlış yapıyor?!
if (*p = i) {
checker++;
}
}
}
}
int main(int argc, char *argv[])
{
stepCounter(999999);
cout << stepCount << endl;
stepIndicator(826424563);
for (j = 0; j<9; j++) {
//
cout << numbers[j] << endl;
}
cout << sameNumberCheck(numstringTest, 10) << " must be 1" << endl;
cout << sameNumberCheck(numstring, 10) << " must be 0" << endl;
cout << endl;
getDifferentNumbers(numstringTest, 10);
cout << endl;
cout << endl << otherNumbers[0] << " is the diff number" << endl;
system("PAUSE");
return EXIT_SUCCESS;
}
Hi, my problem is with pointers actually. You will see above, function getDifferentNumbers. It simply does a comparement if in any given array there are repeated numbers(0-9). To do that, I passed a pointer to the function. I simply do the comparement via pointer. However, there is a strange thing here. When I execute, first time it does correct, but secon time it goes completely mad! This is the function:
void getDifferentNumbers(int* array, int arraySize) {
//
k = 0;
j = 0;
checker = 0;
otherNumbers = new int[10 - arraySize]; //exact number of other numbers is 10 - numbers we have
for (i = 0; i<10; i++) {
if ((i>0)&(checker = 0)) {
k++;
otherNumbers[k - 1] = i - 1;
}
//
checker = 0;
for (j = 0; j<arraySize; j++) {
//
p = array + j;
cout << *p << endl; //ilkinde doğru sonra yanlış yapıyor?!
if (*p = i) {
checker++;
}
}
}
}
and this is the array I passed into the function:
int numstringTest[10] = {0,1,2,3,4,5,6,7,7,9};
it should give the number 7 in otherNumbers[0], however it does not. And I do not know why. I really can not see any wrong statement or operation here. When I execute, it first outputs the correct values of
numstringTest: 1,2,3,4,5,6,7,7,9
but on next 9 iteration of for loop it outputs:
000000000011111111112222222222333333333344444444445555555555666666666677777777778888888888
You have some basic problems in your code.
There are multiple comparisons that are not really comparisons, they're assignments. See the following:
if((i>0) & (checker=0)){
and
if(*p = i){
In both cases you're assigning values to the variables, not comparing them. An equality comparison should use ==, not a single =. Example:
if (checker == 0) {
Besides that, you're using & (bitwise AND) instead of && (logical AND), which are completely different things. You most likely want && in your if statement.
I've just noticed this:
getDifferentNumbers(numstringTest, 10);
and in that function:
otherNumbers = new int[10 - arraySize];
which doesn't seem right.
I am working on visual studio 2013, with a windows8 hp.My code is trying to add two int arrays of size [20] and output the sum. I know I am out or range some where ,but I can't seem to find where. I am the first digit from each array during my convert function and my answer[i] output is only 19 digits when it should be 21digits.
#include<iostream>
#include<string>
#include<cmath>
#include<cstring>
using namespace std;
int globalnum[20];
int total[21];
int i;
void convert(char[], int);
void add(int[], int[], int);
void printAnswer(int[], int);
int main()
{
char n1[20];
char n2[20];
int num1[20];
int num2[20];
int answer[21];
cin >> n1 >> n2;
int l1 = strlen(n1);
int l2 = strlen(n2);
int max = fmax(l1, l2);
convert(n1, l1);
for (int i = 0; i < max - 1; i++)
num1[i] = globalnum[i];
for (int i = 0; i < max; i++)
cout << num1[i];
cout << endl;
convert(n2, l2);
for (int i = 0; i < max - 1; i++)
num2[i] = globalnum[i];
for (int i = 0; i < max; i++)
cout << num2[i];
cout << endl;
add(num1, num2, max);
for (int i = 0; i < max - 1; i++)
answer[i] = total[i];
// printAnswer(answer,max);
for (int i = 0; i < max - 1; i++)
cout << answer[i];
return 0;
}
void convert(char c1[], int size)
{
for (int i = 0; i < size - 1; i++)
globalnum[i] = c1[size - 1 - i] - '0';
}
void add(int add1[], int add2[], int s1)
{
int sum[21];
int remain = 0;
for (i = 0; i < s1 - 1; i++)// This starts to add the numbers.
{
sum[i] = (add1[s1 - 1 - i] + add2[s1 - 1 - i] + remain) % 10;
if (add1[s1 - 1 - i] + add2[s1 - 1 - i] + remain >= 10)
remain = 1;
else
remain = 0;
if (remain != 0)
total[s1 - 1 - i] = 1;
else total[s1 - 1 - i] = 0;
total[s1 - 1 - i] = sum[i];
}
if (remain != 0)
total[0] = 1;
}
//void printAnswer(int t[], int b)
// {
// for (int i = b - 1; i < 0; i--)
// cout << t[i];
// }
// cout << endl;
//}
There's too many problems with your code to give a simple answer. It's maybe easier to work backwards from working code. You haven't fully specified the problem but this was my best guess at what you're trying to do:
#include <algorithm>
#include <iostream>
#include <iterator>
#include <string>
#include <vector>
using namespace std;
vector<int> toInts(const string& s) {
vector<int> v(s.size());
transform(cbegin(s), cend(s), begin(v), [](int c) { return c - '0'; });
return v;
}
int main() {
string a, b;
cin >> a >> b;
auto n = toInts(a);
auto m = toInts(b);
const auto size = max(n.size(), m.size());
n.resize(size);
m.resize(size);
vector<int> sums(size);
transform(cbegin(n), cend(n), cbegin(m), begin(sums), plus<>{});
copy(cbegin(sums), cend(sums), ostream_iterator<int>{cout, ", "});
cout << endl;
}
I've tried to solve a coin change problem in such a way that it'll compute the minimum numbers of coins that can be used. I've used the algorithm post on http://www.algorithmist.com. Here's the algorithm:
C(N,m) = min(C(N,m - 1),C(N - Sm,m) + 1)
with the base cases:
C(N,m) = 1,N = 0
C(N,m) = 0,N < 0
C(N, m) = 0, N >= 1, m <= 0
But when I write the code it run to infinity.
Here's the code:
#include <iostream>
#include <algorithm>
using namespace std;
int Types[101];
int Coins(int N, int m)
{
if(N==0)
{
return 1;
}
else if(N<0)
{
return 0;
}
else if(N>0 && m<=0)
{
return 0;
}
else
{
int a = Coins(N,m-1);
int b = Coins(N-Types[m],m) + 1;
int c = min(a,b);
return c;
}
}
int main()
{
int noOfCoins, Target;
cin >> noOfCoins >> Target;
for(int i = 0; i<noOfCoins; i++)
{
cin >> Types[i];
}
cout << Coins(Target, noOfCoins);
return 0;
}
What can be wrong?
It should be cout << Coins(Target, noOfCoins - 1);
instead of cout << Coins(Target, noOfCoins);
Otherwise you are accessing a 0 element, and go to the same state again and again here:
int b = Coins(N-Types[m],m) + 1;