Permutation and Combination c++ logical error - c++11

This is my assignment, i finished writing my code and it does compile but it is not giving the right answer. So i know there is some logical error but i cannot find out what.
Plz check and tell me, simple code to calculate permutations and combinations
#include <iostream>
using namespace std;
int factorial(int n)
{
if (n == 0 or n == 1)
{
return 1;
}
else
{
return n * factorial(n - 1);
}
}
int permutation(int a, int b)
{
//factorial(a);
int perm = factorial(a) / factorial(a - b);
return perm;
}
int combination(int a, int b)
{
int permutation(int a, int b);
int factorial(int n);
return permutation(a, b) / factorial(b);;
}
int main()
{
int n;
int r;
cout << "Enter n: " << endl;
cin >> n;
cout << "Enter r: " << endl;
cin >> r;
int factorial(int n);
int permutation(int n, int r);
int combination(int n, int r);
if (n >= r)
{
cout << "Permutuation: " << permutation << endl;
cout << "Combination: " << combination << endl;
}
else
{
cout << "Invalid" << endl;
}
return 0;
}
The answer given by the console
Enter n:
6
Enter r:
5
Permutuation: 00AC1375
Combination: 00AC133E

There are a number of errors in your code. First, you should not re-declare your 'permutation' and 'combination' functions inside other functions.
EDIT: Actually, this is not an error but, in my opinion, very bad practice. You could accidentally 'hide' the actual function declaration, which is already provided as you have defined both before any of the calling functions.
Second, your cout << permutation << endl; code is printing a function! This will be taken as meaning the address of that function, which is what you are seeing (HEX addresses).
Here's a 'fixed' version that works (with comments).
#include <iostream>
#include <iso646.h> // Need this in order to use "or" in place of "||"
using namespace std;
int factorial(int n)
{
if (n == 0 or n == 1) {
return 1;
}
else {
return n * factorial(n - 1);
}
}
int permutation(int a, int b)
{
//factorial(a);
int perm = factorial(a) / factorial(a - b);
return perm;
}
int combination(int a, int b)
{
// int permutation(int a, int b); // You don't need to redeclare function inside another one ...
// int factorial(int n);
return permutation(a, b) / factorial(b);;
}
int main()
{
int n, r;
cout << "Enter n: " << endl;
cin >> n;
cout << "Enter r: " << endl;
cin >> r;
// int factorial(int n);
int p = permutation(n, r); // This is how to call your functions ...
int c = combination(n, r); // and assign their returns to values.
if (n >= r) {
cout << "Permutuation: " << p << endl; // Output the values ...
cout << "Combination: " << c << endl; // ...from the functions
}
else {
cout << "Invalid" << endl;
}
return 0;
}
Feel free to ask for further explanations if there's anything I've done that you don't understand.

Related

error: no matching member function for call to 'erase'?

I was working with vector and trying to work with erase function from vector library.
Here is my code
#include <iostream>
#include <vector>
int leftover(std::vector<int> aList)
{
// size = 1 will be termination point
if (aList.size() == 1)
{
return aList.at(0);
}
else
{
aList.push_back(aList.at(0));
aList.erase(aList.at(0));
aList.erase(aList.at(1));
return leftover(aList);
}
}
int main()
{
int x;
std::cout << "Enter a number: ";
std::cin >> x;
std::vector<int> intVector;
for (int i = 0 ; i < x; i++) {
intVector.push_back(i+1);
}
for (const int& i : intVector)
{
std::cout << i << " ";
}
std::cout << "\n";
//int leftwith = leftover(intVector);
//std::cout << leftwith << "\n";
return 0;
}
Anything with remove the element at particular position would be much appreciated.

basic k way merge: terminate called after throwing an instance of 'std::logic_error'

I am trying to implement basic merge k sorted array algorithm but with strings.
I am getting the following error.
terminate called after throwing an instance of 'std::logic_error'
what(): basic_string::_M_construct null not valid
The code works fine if the names vector has just 2 sub vectors, but when I add another list in the names vector I am getting the above error.
Whats wrong with the code?
#include <iostream>
#include <string>
#include <vector>
using namespace std;
vector<string> merge_2_names(vector<string> a, vector<string> b){
int i = 0 ; int j = 0;
vector<string> res;
while(i < a.size() && j < b.size()){
if (a[i].compare(b[j]) < 0){
res.push_back(a[i]);
i++;
}else{
res.push_back(b[j]);
j++;
}
}
while (i < a.size()){
res.push_back(a[i]);
i++;
}
while(j < a.size()){
res.push_back(b[j]);
j++;
}
return res;
}
vector<string> merge_k_names(vector<vector<string>> names){
vector<string> result;
cout << names.size() << "\n";
for (string s: names[0]){
result.push_back(s);
}
for(int i=1;i<names.size();i++)
{
result=merge_2_names(result,names[i]);
}
return result;
}
int main() {
vector<vector<string>> names {{"adam" , "raja" , "zync"},
{"edam" , "some" , "zian"},
{"mike" , "jimm" , "pame"}};
cout << names.size() << "\n";
vector<string> res = merge_k_names(names);
for (string s: res){
cout << s << " ";
}
return 0;
}

Pairs x,y verify equation

I have to build a program as bellow:
User enters 3 Integers: a, b, c
User enters one integer n, and then n integers (ascending, and different numbers)
Program checks all possible pairs (x,y) (with x!=y) of the numbers entered if verifies the equation ax^2 + by^2 = c and prints all pairs which verifies the equation.
I done the program as bellow:
#include<iostream>
using namespace std;
int main() {
int a,b,c,n,i,j;
cin >> a;
cin >> b;
cin >> c;
cin >> n;
int num[n];
for(i=0;i<n;i++) {
cin >> num[i];
}
for (i=0;i<n;i++)
for (j=i+1;j<n;j++) {
if(a*num[i]*num[i]+b*num[j]*num[j] == c) {
cout << "(" << num[i] << "," << num[j] << ")";
}
if(a*num[j]*num[j]+b*num[i]*num[i] == c) {
cout << "(" << num[j] << "," << num[i] << ")";
}
}
return 0;
}
I made it by O(nlogn) with two 'for' statements but i know it could be done by O(n).
NOTE THAT MY PROGRAM WORKS AND I DON'T NEED TO ADD EXPECTED OUTPUT AND MY CURRENT OUTPUT AS YOU SAID IN THE COMMENTS. I ONLY WANT IT TO BE O(N) not O(nlogn) -> I WANT AN OPTIMIZED VERSION OF THE CODE!
How can I do this?
Example of running program: a=1, b=1, c=20
Then n = 5
Then n numbers: 2 3 4 9 18
Program will show all pairs (x,y) which verifies the equation x^2 + y^2 = 20. In this case it shows (2,4)
and (4,2).
Thank you!
Assuming 0 based index...
Set i=0
Set j=n-1
While i<n or j>=0
Set sum=a(num[i]^2)+b(num[j^2)
If sum==c then found pair, and increase i
If sum<c increase i
If sum>c decrease j
I found exactly this problem solved here: http://lonews.ro/educatie-cultura/22899-rezolvare-admitere-universitatea-bucuresti-2015-pregatire-informatica.html and changed a bit to show the pairs (it originally shows the number of pairs).
#include <iostream>
using namespace std;
int main()
{
int a, b, c, n, i=0;
cout << "a = ";
cin >> a;
cout << "b = ";
cin >> b;
cout << "c = ";
cin >> c;
cout << "n = ";
cin >> n;
int s[n];
for(i=0; i<n; i++) {
cout << "s[" << i+1 << "] = ";
cin >> s[i];
}
int j=n-1;
i = 0;
while(j>=0 || i<n) {
if(a*s[i]*s[i] + b*s[j]*s[j] == c) {
cout << "(" << s[i] << "," << s[j] << ") ";
i++;
}
if(a*s[i]*s[i] + b*s[j]*s[j] < c) {
i++;
}
if(a*s[i]*s[i] + b*s[j]*s[j] > c) {
j--;
}
}
return 0;
}

Vector of random integer sets

I'm trying to write a little program to create a vector of random integer sets, but the problem is once the first set is created the program keeps storing the same set of numbers in subsequent iterations. Any help to explain or correct this problem would be very much appreciated. Thanks!
#include<iostream>
#include<cstdlib>
#include<ctime>
#include<set>
#include<vector>
using namespace std;
typedef set<int> Set_I;
typedef set<int>::iterator It;
typedef vector<set<int> > vec_Set;
int random();
void print_set(Set_I s);
void print_vec(vec_Set v);
int main()
{
srand(time(0));
Set_I s;
vec_Set v;
v.resize(4);
for(int i=0; i<4;i++)
{
//cout << s.size() << " " <<endl;
while(s.size()<6)
{
s.insert(random());
}
v[i] = s;
s.empty();
}
//print_set(s);
print_vec(v);
cout << endl << s.size() <<endl << v.size();
system("PAUSE");
}
int random()
{
int r = 1 + rand()%49;
return r;
}
void print_set(Set_I s)
{
for(It it=s.begin(); it!=s.end(); it++)
{
cout << *it << " ";
}
cout << endl;
}
void print_vec(vec_Set v)
{
for(int i=0;i<v.size();i++)
{
cout << "{ ";
for(It j = v[i].begin() ; j != v[i].end() ;j++)
{
cout << *j << " ";
}
cout <<"}";
cout <<endl;
}
}
s.empty() returns a bool stating that the set is empty or not. It has no effect on the members of the set!!
you have to use s.clear() for emptying (clearing) your set.

How to ignore 0's in an Array and print out unique numbers

so my program is supposed to use one 5 sized array to store inputted integers. If it's a duplicated integer it would not be stored into the array.
The problem here is there would be 0's in my array indefinitely since i initialized the size to 5. I need to output only the unique numbers how would i do so?
One thing i noticed was that without my unsigned int position; whenever i enter a duplicate integer it would skip the index;
e.g. array[0] = 10, array[1] = 10 // duplicate, array[2] = 20 // inputted 20, this should've been stored into array[1] but it doesn't.
So i had the position to only increment whenever it's not a duplicate to make sure it's not skipping over the index when a duplicate is entered.
And was there anything i could've done or do a different approach to get my result?
Code:
#include <iostream>
#include <iomanip>
#include <array>
using namespace std;
const unsigned int MIN_VALUE = 10;
const unsigned int MAX_VALUE = 100;
const size_t arraySize = 5;
array <int, arraySize> numberArray = {};
template<size_t size>
bool isDuplicate(array<int, size> array, int value)
{
for (unsigned int i = 0; i < array.size(); i++)
{
if (value == array[i])
{
return true;
}
}
return false;
}
int main()
{
unsigned int input;
unsigned int position = 0;
for (unsigned int i = 0; i < arraySize; i++)
{
cout << "Enter # " << (i + 1) << " : ";
cin >> input;
if (input < MIN_VALUE || input > MAX_VALUE)
{
cout << "The number entered is not in valid range of 10 to 100" << endl;
--i;
}
else if (!isDuplicate(numberArray, input))
{
numberArray[position] = input;
position++;
cout << "The number: " << input << " is unique\n" << endl;
}
}
}
Thanks!
The only missing part in your code is an additional block below your else if block:
else {
cout << "The number: " << input << " is not unique\n" << endl;
--i;
}
where you would decrease your position when the value is a duplicate, and warn the user about it.
If I had to update your program while keeping the most of your code I would write:
#include <iostream>
#include <iomanip>
#include <array>
using namespace std;
const unsigned int MIN_VALUE = 10;
const unsigned int MAX_VALUE = 100;
const size_t arraySize = 5;
// Initialize all array values to 0 (see std::array documentation)
array <int, arraySize> numberArray = {0};
template<size_t size>
bool isDuplicate(array<int, size> arr, int val)
{
bool ret = false;
// Do not waste time with invalid values
if (val < MIN_VALUE || val > MAX_VALUE)
return ret;
// Using size_t to express size
size_t pos = 0;
// Loop until reaching the end OR a not yet set array value
while ( pos < arr.size() && arr[pos]){
if (arr[pos] == val) {
// Found!
ret = true;
break;
}
++pos;
}
return ret;
}
int main()
{
unsigned int input = 0;
size_t position = 0;
while (position < numberArray.size()) {
cout << "Enter # " << (position + 1) << " : ";
cin >> input;
if (input < MIN_VALUE || input > MAX_VALUE) {
cout << "The number entered is not in valid range of 10 to 100" << endl;
} else if (!isDuplicate(numberArray, input)) {
numberArray[position] = input;
// Pre-increment operator is more efficient, see doc.
++position;
cout << "The number: " << input << " is unique\n" << endl;
} else {
cout << "The number: " << input << " is not unique\n" << endl;
}
}
}
It looks like an exercise with a really weird specification. It should be better explained so as to give you a more relevant real-life solution. ;)
Hope this helps.

Resources