Permutations of a specific set of numbers from n to m - c++

#include <iostream>
using namespace std;
int n, m, x[20], p[20];
void display(){
for(int i = 1 ; i <= n; ++i)
cout << x[i] << ' ';
cout << "\n";
}
void bkt(int k){
for(int i = n; i <= m; ++i)
if(!p[i]){
x[k] = i;
p[i] = 1;
if(k<n)
bkt(k+1);
else
display();
p[i] = 0;
}
}
int main()
{ cin >> n >> m;
bkt(1);
return 0;
}
This code should do the permutations from n to m, but it doesn't work and I don't know what I did wrong. I tried a set of examples like 4 and 6, and it should show
4 5 6
4 6 5
5 4 6
5 6 4
6 4 5
6 5 4
but it doesn't show anything in the console, just returns 0.

There's a number of issues with the code, but you can solve the problem in the following way:
cin >> n >> m; // get range
Then create a vector of the appropriate size
std::vector<int> v(m - n + 1);
and then fill it with the needed values
std::iota(std::begin(v), std::end(v), n);
and then generate all permutations in a loop
do {
// ...
} while(std::next_permuation(std::begin(v), std::end(v));

Related

Binary Search with Duplicates

I am doing this particular exercise where I have to implement the Binary Search algorithm which returns the index of the first occurence of an element in a sorted array, if it contains duplicates. Since I am primarily working on my algorithmic skills in C++, I am only trying to do it in C++. Here is my code:
#include <iostream>
#include <cassert>
#include <vector>
using std::vector;
int binary_search(const vector<int> &a, int x, int n) {
int left = 0, right = n-1;
while(left<= right){
int mid = left + (right-left)/2;
if(x== a[mid]){
return mid;
}else if(a[mid]>x){
right = mid-1;
}else{
left = mid+1;
}
}
return -1;
}
int first_occurence(const vector<int>&a, int x, int n) {
int out = binary_search(a, x, n);
if(out !=-1){
for(int i = out;i>0&& a[i]==x;--i ){
out = i;
}
}
return out;
}
int main() {
int n;
std::cin >> n;
vector<int> a(n);
for (size_t i = 0; i < a.size(); i++) {
std::cin >> a[i];
}
int m;
std::cin >> m;
vector<int> b(m);
for (int i = 0; i < m; ++i) {
std::cin >> b[i];
}
for (int i = 0; i < m; ++i) {
std::cout << first_occurence(a, b[i], n) << ' ';
}
}
The first input to the program tells how many items the array should contain, the second is the enumeration of these elements, third line tells how many keys to search for and the final line are the individual keys. The output is the indices for the key or -1 when no such key is found.
My strategy is to use a function to find the index of a key. If it is found, then in case of duplicates, the first occurrence has to have a lower index. That is what the first_occurence() method does; keep looping back till the first occurence is found.
For the following input:
10
1 5 4 4 7 7 7 3 2 2
5
4 7 2 0 6
The output is:
-1 4 -1 -1 -1
Which is only correct for the key 7. I have been trying to debug this for quite some time but I can not figure out the problem.
returns the index of the first occurence of an element in a sorted array,
Your binary search algorithm requires that the data is sorted before you call it.
Example:
#include <algorithm>
#include <sstream>
int main() {
std::istringstream in(R"aw(10
1 5 4 4 7 7 7 3 2 2
5
4 7 2 0 6
)aw");
int n;
in >> n;
vector<int> a(n);
for (auto& v : a) {
in >> v;
}
std::sort(a.begin(), a.end()); // <- add this
// display the sorted result:
for (auto v : a) std::cout << v << ' ';
std::cout << '\n';
int m;
in >> m;
vector<int> b(m);
for (auto& v : b) {
in >> v;
}
for (auto v : b) {
std::cout << v << ' ' << first_occurence(a, v, n) << '\n';
}
}

How Vector allocation using push_back() and pop_back operation gives garbage values

I am solving a problem in which I have to find those element from the array whose total gives maximum sum. But there is a condition that no two adjacent element can be the part of that max subarray. Here is my code using simple brute Force solution-
#include <bits/stdc++.h>
using namespace std;
int main()
{
int t;
cin >> t;
while (t != 0)
{
int n, i, s, k = 0, m = -1001;
vector< int > a;
cin >> n;
a.resize(n, 0);
vector< int > b;
for (i = 0; i < n; i++)
{
cin >> a[i];
m = max(m, a[i]);
if (a[i] < 0)
{
a[i] = 0;
++k;
}
}
if (k == n)
cout << m;
else
{
k = 0;
s = a[0];
b.push_back(a[0]);
for (i = 1; i < n; i++)
{
if (i != k + 1)
{
if (a[i])
{
s += a[i];
b.push_back(a[i]);
k = i;
}
}
else
{
if (s - a[i - 1] + a[i] > s)
{
b.pop_back();
s -= a[i - 1];
s += a[i];
b.push_back(a[i]);
++k;
}
}
}
}
cout << endl;
for (i = n; i >= 0; i--)
{
if (b[i])
cout << b[i] << " ";
}
cout << endl;
--t;
}
return 0;
}
Here is input to code-
First line represent no. of test cases,
Second line represent size of array
And the next line shows array elements.m
5
5
-1 7 8 -5 4
4
3 2 1 -1
4
11 12 -2 -1
4
4 5 4 3
4
5 10 4 -1
Output-
4 8
32 32607 -787829912 1 3
32 32607 -787829912 12
3 5
10
Expected output-
4 8
1 3
12
3 5
10
So, there are 5 test cases. For the first test case and last two test case output is correct. But for second and third test case it is giving garbage value. What is the problem, that for some test cases it is giving garbage value, and for other not.
for (i = n; i >= 0; i--)
{
if (b[i])
cout << b[i] << " ";
}
This prints out n+1 values in b. But even in the best case, b only has n values (for n=1). And for n>1, b.size() is less than n, so you are reading garbage from outside the vector's storage (this is undefined behavior). Just use the correct bound:
for (i = b.size() - 1; i >= 0; ++i)
I think I found your (first) problem:
if(k==n)
cout<<m;
When all numbers are negative this outputs the largest of them.
But the empty array has a sum of 0 and is larger than a negative number and has no 2 adjacent members in it. So clearly the right answer should be 0, not m.

c++ how to print 1-10 after that if i input one of them the number will be dissapear

how to print 1-10 after that if i input one of them the number will be disappear.
ex:
Output: 1 2 3 4 5 6 7 8 9 10
Input:1
Output:2 3 4 5 6 7 8 9 10
Input:5
Output:2 3 4 6 7 8 9 10
(only using while or do-while or for)->(not using array)
//let's say that the variable x contains the inputted number, 5 in this case
for (int i = 1; i <= 10; i++){
if (i != x)
printf("%d ", i);
}
The output will be:
1 2 3 4 6 7 8 9 10
#include <bitset>
#include <iostream>
...
constexpr int N = 10;
std::bitset<N+1> mask {-1ul};
while (true) {
int inp;
cin >> inp;
if (inp < 1 || inp > N)
continue;
mask.reset(inp);
for (int i = 1; i < N; ++i) {
if (mask.test(i)) {
std::cout << i << '\n';
}
}
}
I have tested this code on VS2017. I believe you will get an idea of how to do it. Of course, you can improve the efficiency of the source code.
#include "stdafx.h"
#include <iostream>
#include <bitset>
using namespace std;
int main()
{
constexpr int iBitNum = 10;
std::bitset<iBitNum + 1> mask;
mask.set();
int _size = mask.count();
for (int i = 0; i < _size; ++i)
{
mask[i] = 0;
}
int inp = 0;
int b = 0;
while (true)
{
cout << "Enter the number which you do not want to display" << endl;
cin >> inp;
cout << "Here is the result" << endl;
for (size_t i = 0; i < iBitNum; i++)
{
if (i+1==inp)
{
continue;
}
b = mask[i] | i+1;
cout << b << " ";
}
cout << endl;
}
return 0;
}

Can't get my sort function to use print method to show iterations

I want displayArray on line 69 to work every time it iterates to show the changes of the insertion sort. I haven't been able to get it to work and have been spinning my wheels for a bit. Please help/explain. Thank you in advance.
This is what my output should look like:
Expected Output:
Enter up to 20 nonnegative whole numbers.
Mark the end of the list with a negative number.
3 7 4 9 5 2 6 1 -1
3 7 4 9 5 2 6 1
3 4 7 9 5 2 6 1
3 4 7 9 5 2 6 1
3 4 5 7 9 2 6 1
2 3 4 5 7 9 6 1
2 3 4 5 6 7 9 1
1 2 3 4 5 6 7 9
In sorted order the numbers are:
1 2 3 4 5 6 7 9
Code:
#include <iostream>
using namespace std;
const int MAX_SIZE = 20;
// Fills the array a[] with data from the user for a[0] through a[numberUsed -1].
// Since the user will not necessarily use up all the allocated entries in the array,
// the function will set the actual number of entries used in the "numberUsed"
// reference variable.
void fillArray(int a[], int arraySize, int& numberUsed);
// Sorts the array a[] such that a[0] <= a[1] <= ... <= a[numberUsed - 1].
void insert_sort(int a[], int numberUsed);
// Interchanges the values of v1 and v2.
void swapValues(int& v1, int& v2);
// Displays the contents of the array
void displayArray(const int a[], int numberUsed);
int main( )
{
cout << "This program sorts numbers from lowest to highest.\n";
int sampleArray[MAX_SIZE] = {0};
int numberUsed = 0;
fillArray(sampleArray, MAX_SIZE, numberUsed);
insert_sort(sampleArray, numberUsed);
cout << "In sorted order the numbers are:\n";
displayArray(sampleArray, numberUsed);
return 0;
}
void fillArray(int a[], int arraySize, int& numberUsed)
{
cout << "Enter up to " << arraySize << " nonnegative whole numbers.\n"
<< "Mark the end of the list with a negative number.\n";
int next = 0;
int index = 0;
cin >> next;
while ((next >= 0) && (index < arraySize))
{
a[index] = next;
index++;
cin >> next;
}
numberUsed = index;
}
void insertion_sort (int a[], int numberUsed){
int j, temp;
for (int i = 0; i < numberUsed; i++){
j = i;
while (j > 0 && a[j] < a[j-1]){
temp = a[j];
a[j] = a[j-1];
a[j-1] = temp;
j--;
}
displayArray(a,numberUsed);
}
}
void swapValues(int& v1, int& v2)
{
int temp;
temp = v1;
v1 = v2;
v2 = temp;
}
void displayArray(const int a[], int numberUsed)
{
for (int index = 0; index < numberUsed; index++)
{
cout << a[index] << " ";
}
cout << endl;
}

Finding how many a specific digit appears in array of numbers (C++)

I'm doing an online challenge and the challenge is the following:
"Kids are playing a game called "Counting digits". For given numbers S and K, they firstly write all numbers between those numbers and then count how many times each digit appears (0,1,2,3,4,5,6,7,8,9). For example, S=767, K=772, numbers will be: 767,768,769,770,771,772
So, 0 will show once (in 770), 1 will show once (in 771) and so on..
Basically, my program have to do the following (given example):
Input:
1 9
(These are numbers 1,2,3,4,5,6,7,8,9)
Output:
0 1 1 1 1 1 1 1 1 1
(0 doesn't show, other numbers show once)."
I'm stuck on this code... out of ideas.
#include <iostream>
using namespace std;
int main()
{
int s,k;
int array[10];
int c0=0,c1=0,c2=0,c3=0,c4=0,c5=0,c6=0,c7=0,c8=0,c9=0;
cin >> s >> k;
int saves = s;
int savek = k;
cout << s%10;
for(int i=s;i<=k;i++)
{
int savei=i;
while(savei!=0)
{
savei=savei%10;
}
}
Any pseudo code/snippet/code/hint is appreciated.
Purely numeric solution to a purely numeric problem:
#include <iostream>
int main()
{
int s, k, i, tmp;
std::cin >> s >> k;
int count[10] = { 0 };
for (i = s; i <= k; i++) {
tmp = i;
do {
count[tmp % 10]++;
tmp /= 10;
} while(tmp);
}
for (i = 0; i < 10; i++) {
std::cout << i << " appears " << count[i] << " times" << std::endl;
}
return 0;
}
My solution is like this:
int main(){
int s,k;
cin >> s >> k;
int numbers[10]={0};
string sum;
for(int i=s;i<=k;i++)
{
sum=to_string(i);
for(int i=0;i<sum.length();i++){
numbers[(int)sum.at(i)-48]++;
}
}
for(int i=0;i<10;i++){
cout<<numbers[i]<<endl;
}
return 0;
}
public static void getDigitsInBook(int n) {
for(int i=0;i<10;i++) {
int x = n,val=0,k=1;
while(x!=0) {
int left = x/10;
int num = x%10;
int right = n%k;
if(i == 0) {
val = val+ (left*k);
}
else if(i<num) {
val = val + ((left+1)*k);
}
else if(i==num) {
val = val + (left*k) + right+1;
}
else {
val = val+ (left*k);
}
k=k*10;
x = n/k;
}
System.out.println(val);
}
}
What you usually do with such tasks is calculating the number between 0 and S and between 0 and K and subtracting those.
How many are between 0 and 767? First count the numbers of the last digit. There are 77 times 0, 1, 2, 3, 4, 5, 6, 7 each and 76 times 8 and 9. More formally, 767/10+1 between 0 and 767%10 and 767/10+1 on the rest. Then calculate the number of occurences of the last digit for 767/10=76, multiply by 10, add 7 times 7 and 6 (for the error on the last one) and do the same for the remaining digits, here 76/10=7. Finally, add the results up.
This solves the problem in O(log_10 K).
try this code:
for(int n=s ; n<=k ; n++)
{
tempN = abs(n);
while(tempN > 0)
{
tempDigit = tempN % 10;
tempN /= 10;
//count tempDigit here
}
}
assuming your variables are ints, "tempN /= 10;" should be no problem.