Create all possible combinations using a deque and recursion C++ - c++

I have a deque that contains a series of numbers {0, 1, 2, 3, 4, 5, 6} and I am trying to create all possible combinations of these numbers using recursion.
Here is my current code
void combination(vector<node> &comb, deque<node> &numbers) {
if (numbers.empty()) {
for (unsigned int i = 0; i < comb.size(); i++) {
cout << comb[i].id << " ";
}
cout << "\n";
return;
}
comb.push_back(numbers.front());
numbers.pop_front();
combination(comb, numbers);
comb.pop_back();
combination(comb, numbers);
}
I've ran this through on paper and it makes sense but when I run it this is the output:
0 1 2 3 4 5 6
0 1 2 3 4 5
0 1 2 3 4
0 1 2 3
0 1 2
0 1
0
Why isn't the function printing out all possible combinations?
Also, this is what I want to use - A deque that contains the numbers and a vector that contains each combination.

You are using Pass by reference, i have made some minor changes and it works
code :
#include <bits/stdc++.h>
using namespace std;
void combination(vector<int> comb, deque<int> numbers) {
if (numbers.empty()) {
for (unsigned int i = 0; i < comb.size(); i++) {
cout << comb[i] << " ";
}
cout << "\n";
return;
}
comb.push_back(numbers.front());
numbers.pop_front();
combination(comb, numbers);
comb.pop_back();
combination(comb, numbers);
}
int main() {
// your code goes here
vector<int> comb;
deque<int> numbers;
for(int i = 0;i < 7;i++) numbers.push_back(i);
combination(comb, numbers);
return 0;
}
Link to solution on ideone : http://ideone.com/vgukF3

Related

Logic error in remove duplicates in a vector while preserving the order function

void vectorDeduplicator(std::vector<std::string>& inputVector){
for(int i = 0; i < inputVector.size() - 1; i++){
for(int x = 1; x <= inputVector.size() - 1; x++)
if(inputVector.at(i) == inputVector.at(x) && i != x){
inputVector.erase(inputVector.begin() + x);
}
}
}
Input: 1 1 2 2 4 4 3 3 1 1 3 3 3 2 2
Output: [1,2,4,1,3,2]
You can see the function I'm trying to use to remove duplicates inside of a vector. It works when duplicates are adjacent. I wouldn't like to use a faster and an efficient method without knowing anything about it that already exists within the standard library or anything else. I'd like to learn the algorithm behind it as this is for learning purposes.
The problem is you ignore one value as you erase. You need to decrement x:
#include <vector>
#include <iostream>
void vectorDeduplicator(std::vector<int>& inputVector)
{
for(int i = 0; i < inputVector.size() - 1; i++)
{
for(int x = 1; x < inputVector.size(); x++)
{
if(inputVector.at(i) == inputVector.at(x) && i != x)
{
inputVector.erase(inputVector.begin() + x);
x--; // go one back because you erased one value
}
}
// to debug
for(const auto& x : inputVector)
std::cout << x << " ";
std::cout << std::endl;
}
}
int main(){
std::vector<int> vector{1, 1, 2, 2, 4, 4, 3, 3, 1, 1, 3, 3, 3, 2, 2};
vectorDeduplicator(vector);
// output
for(const auto& x : vector)
std::cout << x << " ";
return 0;
}
The output then is:
1 2 2 4 4 3 3 3 3 3 2 2
1 2 4 4 3 3 3 3 3
1 2 4 3 3 3 3 3
1 2 4 3
1 2 4 3

Getting unknown values along with answer

Smaller Greater Equal Numbers
PrepBuddy has N baskets containing one fruit each with some quality factor(ith basket have Ai quality factor) and Tina has one single basket with one fruit having quality factor K. She wants to know how many PrepBuddy's baskets have quality factor less(L) than K, how many baskets have quality factor more(M) than K and how many baskets have quality factor equal(E) to K.
Input format
The first line contains an integer T, representing the number of test cases.T test cases follow,First linecontains two space-separated integers N and K.The second line contains N space-separated integers representing the quality factor of the basket.
Output format
For each test case on a new line, print three space-separated integers representing the values of L, M,and E.
Constraints
1<=T<=100
1<=N,K<=10^5
−10^6<=A[i]<=10^6
Sum of all N over any test case file doesn't exceed 5∗10^6
Time Limit
1 second
Example
Input
2
5 2
-1 0 -3 1 2
5 3
1 -1 -5 2 4
Output
4 0 1
4 1 0
Sample test case explanation
In the first test case,
K=2, the baskets with quality factor smaller than K are [1,2,3,4], there is no basket which has quality factor more than K and there is one basket [5] which have quality factor equal to K.
My solution
#include <bits/stdc++.h>
typedef long long ll;
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
ll n, k;
cin >> n >> k;
ll arr[n];
for (ll i = 0; i < n; i++) {
cin >> arr[i];
}
int less = 0, more = 0, equal = 0;
for (ll i = 0; i < n; i++) {
if (arr[i] < k) {
less++;
} else if (arr[i] > k) {
more++;
} else {
equal++;
}
cout << less << " " << more << " " << equal << " ";
}
cout << endl;
}
return 0;
}
Input
2
5 2
-1 0 -3 1 2
5 3
1 -1 -5 2 4
Output
1 0 0 2 0 0 3 0 0 4 0 0 4 0 1
1 0 0 2 0 0 3 0 0 4 0 0 4 1 0
Why am I getting additional numbers like 1 0 0 2 0 0 3 0 0 4 0 0 along with my answer.How to correct this?? Please help
The error in your code was quiet simple, and easy to debug. You were printing the output every run through the array, thus, getting all these extra prints.
How does it become easy to debug? Reorganizing the code so it will be more readable, made it quiet possible. Actually, the fix was moving the line:
cout<<less<<" "<<more<<" "<<equal<<" ";
Two line lower than it was.
In order to demonstrate it, here is the code fixed and organized:
#include <iostream>
#include <vector>
#include <cstdint>
int main()
{
int t;
std::cin >> t;
while(t--)
{
std::int64_t n,k;
std::cin >> n >> k;
std::vector<int> vec{n};
for(std::size_t i = 0; i < n; ++i)
{
std::cin >> vec[i];
}
int less=0, more=0, equal=0;
for (std::size_t i = 0; i < n; i++)
{
if (vec[i] < k)
{
less++;
}
else if (vec[i] > k)
{
more++;
}
else
{
equal++;
}
// The next output line was here, under the for loop!!!
}
std::cout << less << " " << more<< " " << equal << " "; // this is its place!
std::cout << std::endl;
}
return 0;
}
I have made only 3 changes:
Removed the using namespace std; and #include <bit/stdc++.h>.
Realigned the code according to its logical order - each new scope has its own indentation level, showing which command runs in which scope, revealing the mistake.
Used proper types to each thing: In C++ there are no dynamic arrays in the format arr[n], thus, you need to use std::vector. Also, there are fixed size lengths in cstdint, and you should use those to ensure you are using the right type. Also, prefer using unsigned values when possible, for example, when indexing, use either std::size_t, std::uint32_t or std::uint64_t.
This code worked fine for me
#include <bits/stdc++.h>
using namespace std;
int main()
{
int T,N,K,arr[N];
cin>>T;
while(T--)
{
cin>>N;
cin>>K;
for(int i=0;i<N;i++)
{
cin>>arr[i];
}
int L=0,M=0,E=0;
for(int i=0;i<N;i++)
{
if(arr[i]<K){
L++;
}
else if(arr[i]>K)
{
M++;
}
else{
E++;
}
}
cout<<L<<" "<<M<<" "<<E<<endl;
}
return 0;
}

How to compare numbers from a stream if the same number repeats

I am trying to get the same numbers that repeat to be writen to a different stream
the function void lygink
void lygink (int s,int e,int n,int a , int m,info K[],int &sk)
{
a=0;
for (int i=1; i<=m; i++)
{
if(K[i].j==K[i].l) ;
else {
e=K[i].j;
s=K[i].j;
if (e==s) {
cout << e<< endl;
}
}
}
}
The whole code is as follows:
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
struct info
{
int jurg,lin,k;
};
void skaityk(int &n,int &m,int lin, int jurg, info K[])
{
{
ifstream fd ;
fd.open ("U2duom.txt");
fd >> n >> m;
for (int i=1; i<=n; i++)
{
fd>>K[i].lin ;
cout<<fixed<<setprecision(2)<<" " <<K[i].lin;
}
cout << " "<< endl;
for (int i=1; i<=m; i++)
{
fd>>K[i].jurg ;
cout<<fixed<<setprecision(2)<<" " <<K[i].jurg;
}
cout << " "<< endl;
fd.close();
}
}
void lygink (int s,int e,int n,int a , int m,info K[],int &k)
{
a=0;
for (int i=1; i<=m; i++)
{
if(K[i].jurg==K[i].lin) ;
else {
e=K[i].jurg;
s=K[i].jurg;
if (e==s) {
cout << e<< endl;
}
}
}
}
int main()
{
int n,e,m,a,lin,jurg,s,k;
s=22;
info K[500];
skaityk(n, m,lin, jurg, K);
lygink(s,e,n,a,m,K,k);
int i;
return 0;
}
and the file is
8 14
5 6 6 9 14 25 8 26
5 20 6 7 13 7 9 10 12 20 15 16 21 5
It should only give me 7 and 20 but it gives all that are not the same and I can't figure out how to extract those numbers I need to eliminate the numbers that do not repeat or somehow get the numbers that repeat
I would do the job somewhat differently. As a first attempt at things, I'd probably do something on this general order:
#include <iostream>
#include <set>
#include <sstream>
int main() {
std::istringstream input(R"(
8 14
5 6 6 9 14 25 8 26
5 20 6 7 13 7 9 10 12 20 15 16 21 5
)");
std::set<int> numbers;
int n;
while (input >> n)
if (!numbers.insert(n).second)
std::cout << n << "\n";
}
This produces more output than just 7 and 20, but hand inspection seems to confirm that everything it says is a duplicate actually is.
Use std::sort to sort the array and std::adjacent_find to find duplicates. A good programmer uses the available tools and doesn't reinvent the wheel every time.
std::unordered_set<int> unique(std::vector v) {
std::sort(std::begin(v), std::end(v));
auto it = std::adjacent_find(std::begin(v), std::end(v));
std::unordered_set<int> ret;
while (it != std::end(v)) {
ret.insert(*it);
std::advance(it, 2);
it = std::adjacent_find(it, std::end(v));
}
return ret;
}

C++: Segmentation Fault, malloc.c: No such file or directory

I was solving a programming problem in C++ which requires examining all the 9! permutation of the 3 X 3 matrix
1 2 3
4 5 6
7 8 9
I think, I have written the correct logic, and infact tested it on a 2 X 2 matrix(by tweaking the code for 2 X 2 from 3 X 3, ofcourse.), which results into the correct output being printed. But when I run the program for the actual constraint(ie. the 3 X 3 matirx), the program terminates with a Segmentation fault. Oddly when debuugged with GDB, it prints out
Program received signal SIGSEGV, Segmentation fault.
0x00007ffff74f6bbc in _int_malloc (av=av#entry=0x7ffff7839b20 <main_arena>,
bytes=bytes#entry=12) at malloc.c:3353
3353 malloc.c: No such file or directory.
Here is the C++ code that I wrote:
#include <bits/stdc++.h>
using namespace std;
int min_count;
map<string, bool> mp;
vector<vector<int>>vec(3, vector<int>(3, 0));
// n <= 17
bool isPrime(int n) {
return n == 2 or n == 3 or n == 5 or n == 7 or n == 11 or n == 13 or n == 17;
}
// get a String representation of the matrix vec
string getStringRepresentation(vector<vector<int>> vec) {
string str = "";
for(auto i : vec) {
for(auto j : i)
str += ('0' + j);
}
return str;
}
void printRecursive(vector<vector<int>> &vec, map<string, bool> &mp, int count) {
string str = getStringRepresentation(vec);
if(str == "123456789" and count <= min_count)
min_count = count;
//cout << str << " " << count << endl;
if(mp[str])
return;
mp[str] = true;
for(int i = 0; i < vec.size(); ++i) {
for(int j = 0; j < vec[i].size(); ++j) {
if(j != vec[i].size() - 1 and isPrime(vec[i][j] + vec[i][j+1])) {
swap(vec[i][j], vec[i][j+1]);
printRecursive(vec, mp, count + 1);
swap(vec[i][j], vec[i][j+1]);
}
if(i != vec.size() - 1 and isPrime(vec[i][j] + vec[i+1][j])) {
swap(vec[i][j], vec[i+1][j]);
printRecursive(vec, mp, count + 1);
swap(vec[i][j], vec[i+1][j]);
}
}
}
}
// solve for each test case
void solve() {
for(auto &i : vec) {
for(auto &j : i) {
cin >> j;
}
}
//cout << getStringRepresentation(vec) << endl;
min_count = INT_MAX;
printRecursive(vec, mp, 0); // recursively examine all possible states.
// if min_count is not changed(i.e. reamains equal to INT_MAX then the required state is unreachable, print -1 to indicate)
cout << (min_count == INT_MAX ? -1 : min_count) << endl;
}
int main() {
int test; // test are the number of test cases, each will invoke the solve() function.
cin >> test;
while(test--)
solve();
}
For a input
1
7 3 2
4 1 5
6 8 9
The program should have been outputting 6 but results in SIGSEGV as mentioned. What am I doing wrong?
Try using debugging print lines to see where the segmentation fault happens. Also, try to store the matrix as an array of 9 elements rather than a matrix.

How to find indexes from vector1 in vector2 in c++

i was envolving about a week with this issue, i have two vector for example vec1 and vec2, i want after search and find values from vec1 in vec2 return their indexes where only found for example:
vector<int>vec2 = { 1, 2, 2, 4 };
vector<int>vec1 = { 1, 2, 4 };
i want somthing like this pseudo code and this result:
pseudo code:
for i = 0 to vec2.size() do
return vec1 indexes in vec2;
end
result:
pass1:
1 0 0 0
pass2:
0 1 1 0
pass3:
0 0 0 1
final resault:
0 0 0 1
My code (it does not compile):
My code:
#include <vector>
#include <iostream>
using namespace std;
vector<int> find_index(vector<int>vec2, vector<int>vec1)
{
std::vector<double> tmp;
for (int i = 0; i<vec2.size(); i++)
{
for (int j = 0; j<vec2.size(); j++)
{
if (vec2[i] == vec1[j])
{
tmp.push_back(i);
}
}
}
return tmp;
}
int main()
{
vector<int>vec2 = { 1, 2, 2, 4 };
vector<int>vec1 = { 1, 2, 4 };
cout << find_index(vec2, vec1);
getchar();
return 0;
}
The code you have fails to compile for two reasons:
Using double item type for the tmp vector. A vector<double> does not convert implicitly to the required function result type vector<int>.
The standard library does not define output of vectors, so the cout << a vector in main doesn't compile.
To output the vector you can define function like this:
void write_to( ostream& stream, vector<int> const& v )
{
for( int i = 0; i < int( v.size() ); ++i )
{
stream << (i > 0? " " : "") << v[i];
}
}
and call it like this:
write_to( cout, find_index(vec2, vec1) );
cout << "\n";
It's also possible to write a little glue code that would enable the cout << notation, i.e. that would make it use the write_to function, but that is maybe just complication now.
With these changes your code compiles and outputs
0 1 2 3