Debug on Program about Permutation - c++

Recently I am writing a program to generate a fixed number of permutation of alphabets inputted. For example, I inputted 3, 3, ABC, the program will output ABC, ACB, BAC, according to lexicographical order. But the program cannot get through all the test case and i cant find out where is the bug. Please help.
#include <iostream>
using namespace std;
int used[26], cou = 0, k, n, i;
string output;
string sorting(string x, int y)
{
char temp;
int i, j;
for (i = 0; i < y; ++i)
{
for (j = 0; j < y-1; ++j)
{
if (x[j]-'0' > x[j+1]-'0')
{
temp = x[j];
x[j] = x[j+1];
x[j+1] = temp;
}
}
}
return x;
}
void out(int x, string y)
{
int i;
if (cou == k)
{
return;
}
if (x == n+1)
{
cout << output << endl;
++cou;
}
else
{
for (i = 0; i < n; ++i)
{
if (used[i] == 0)
{
used[i] = 1;
output[x-1] = y[i];
out(x+1, y);
used[i] = 0;
}
}
}
}
int main()
{
char inpi;
string inp, ha;
cin >> n >> k >> inp;
output.resize(n);
for (i = 0; i < 26; ++i)
{
used[i] = 0;
}
inp = sorting(inp, n);
out(1, inp);
}

I am not sure that I understood the question.
Leaving the algorithm aside, you should know that a standard string is able to tell how long is. Therefore the y parameter in sorting is redundant. Use x.size() to find the size.
Another problem is output[x] = y[i];. You did not set output's size: it is zero. Since you are looking for permutations, I assume its size must equal y's size: output.resize( y.size() );.
One last thing: use meaningful identifiers. y may be good for a compiler; for a human, it may define a bad day.

There doesn't seem to be a need to create a global as you have done
string output;
Create a string to capture the output either within main() and pass it by reference to the functions which need them, in this case fill()
or
create it within fill() and return it by value once its populated

Related

Why does function return garbage values including the real output and how to clear that garbage?

I have written a substring function that takes a value char array, initial value, and length and then return a substring
char* substring(char t[],int i,int l){
int k=0;
char* subs=new char[l];
while(t[k]!=0){
if(k==i){
int a=i;
int j=0;
// for (int j=0;j<l;j++)
while(j<l)
{
subs[j]=t[a];
a++;
j++;
}
if(subs!=0){
break;
}
}
k++;
}
return subs;
}
// CHECKING
int main(){
char t[20]="this is a string";
cout<<substring(t,0,4);
}
//OUTPUT
thisâ””
everything is working properly getting exact output which I want but at the end of the output value it also return a unexpected value such as symbols and random alphabets don't know how to get rid of it
**NOTE I don't want to use strings or anything else just want to clear the problem which in this programme
This is about the smallest change to fix your function -- changing the allocation size, and terminating the substring. You might want to consider whether the outer loop is worthwhile -- shouldn't you return an empty string rather than an uninitialized one if the substring starts after the end of the string? Or should you return a null to signify the error?
It is a matter of style, but the inner loop might be easier to read as:
for (j = 0; j < l; j++) { subs[j] = t[i+j]; }.
char* substring(char t[], int i, int l)
{
int k = 0;
char* subs = new char[l + 1];
while (t[k] != 0) {
if (k == i) {
int a = i;
int j = 0;
// for (int j=0;j<l;j++)
while (j < l) {
subs[j] = t[a];
a++;
j++;
}
subs[j] = '\0';
break;
}
k++;
}
return subs;
}
// CHECKING
int main()
{
char t[20] = "this is a string";
cout << substring(t, 0, 4);
}

Computing square-root with bit shifting algorithm always outputs the same number

I'm struggling with the bit shifting algorithm for computing the square root of big numbers. I've got arrays of 32bit words and doesn't matter the input, the output is always the same number. Previously the algorithm worked with 1 bit per array cell, but when I switched to words in cells it doesn't work anymore.
I wrote methods that work perfectly separately (adding words, subtracting words, shifting bits to the right) but the whole program doesn't give what I expect.
When the input number has 0 in it's first position, the output is 0, when it has any number but the 1st cell of the array isn't 0, the output is always the same.
The variables:
uint32_t var[4] = {0,0,0,0};
uint32_t w_number[word_len] = {1, 0,0,234324};
uint32_t one[word_len] = {0,0,0,0};
uint32_t var[word_len] = {0,0,0,0};
uint32_t buff[word_len] = {0,0,0,0};
uint32_t result[word_len] = {0,0,0,0};
The code:
one[0] = 1L << 30;
while (isBigger(one, input))
{
shiftR_word(one);
shiftR_word(one);
}
while (!isZero(one))
{
add_word(result, one, var); //the result of one+result is put in Var.
if ((isBigger(input, var) || equals(input, var))) // if (input >= var)
{
subtract_word(input, var, input); // input-=var
shiftR_word(result);
add_word(result, one, result);
}
else
{
shiftR_word(result);
}
shiftR_word(one);
shiftR_word(one);
}
std::cout << "\nOut: ";
printAsBit(result);
std::cout << std::endl;
Here's the shifting algorithm I'm using that may cause the problems.
void shiftR_word(uint32_t w_number[], int n=4)
{
// n - how many words
//(n*32b word) >> 1
bool* odd = new bool[n];
for (int i = 0; i < n; i++)
{
if( w_number[i] & 1 )
odd[i]=true;
else
odd[i]=false;
}
for (int i = 0; i < n; i++)
w_number[i] >>= 1;
for (int i = 0; i <= n-1; i++)
{
if(odd[i])
{
w_number[i+1] = w_number[i+1] | 1 << 31;
}
}
delete[] odd;
}
The add function:
void add_word(uint32_t a[], uint32_t b[], uint32_t result[], int len=4)
{
int carry=0;
for (int i = len-1; i >=0; i--)
{
result[i]=a[i]+b[i]+carry;
carry = (a[i]>result[i] || b[i]>result[i]) ? 1 : 0;
}
}
isBigger method:
bool isBigger(uint32_t a[],uint32_t b[] ,int len=4)
{
for (int i = 0; i < len; i++)
{
if (a[i]>b[i])
{
return true;
}
}
return false;
}
I am unable to spot the error in the code, especially that all of the methods seem to work when I test them separately.
isBigger does not work. If you have (length 2) values of {2, 5} for a and {6, 3} for b it will return true when it should return false. Inside the loop, you want to return false if a[i] < b[i], and only check the next value if the two values are equal.
bool isBigger(const uint32_t a[], const uint32_t b[], int len = 4)
{
for (int i = 0; i < len; i++)
{
if (a[i] > b[i])
return true;
if (a[i] < b[i])
return false;
}
// Only get here if `a` and `b` are equal
return false;
}
Additionally, shiftR_word has Undefined Behavior, because w_number[i+1] can be past the end of the array (when i == n-1, you'll access w_number[n - 1 + 1] or w_number[n]). Your loop condition in this instance should be i < n-1. However, that function is rather inefficient. It can be rewritten to only need one loop and no memory allocation, but that's left as an exercise for the reader.

Infinite run time

For the code below in Ubuntu 16.04
For custom testcase
4 3
1 2 3 7
My runtime is infinite and there is no output. (No output means that 'a' is also not printed on console). However when I comment the function call foo
// int temp = foo(ab, 0, n-1);
I get output
a##
What can be the reason of infinite run time and no output that I am missing?
#include<bits/stdc++.h>
using namespace std;
int a[1000000];
int foo(int x, int f, int l)
{
int m = (f+l)/2;
while(f<=l)
{
if(a[m]==x)
return 1;
else if(a[m]<x)
f = m+1;
else if(a[m]>x)
l = m-1;
}
return 0;
}
int main()
{
int n, x;
cin >> n;
cin >> x;
int i=0;
for (i = 0; i < n; i++)
{
cin >> a[i];
}
cout<<'a';
sort(a,a+n);
for(i=0; i<n-1; i++)
{
if(a[i]==a[i+1])
{
cout << 0;
return 0;
}
}
cout<<'#';
int ab = a[i];
int temp = foo(ab, 0, n-1);
cout<<'#';
return 0;
}
The reason you're not getting any output (not even the 'a') is that stdout is buffered. Typically it is line-buffered, meaning it will only be printed when a new line is written.
You can force whatever's in the buffer to print out immediately by doing std::cout << std::flush;, or for example in your case, std::cout << 'a' << std::flush; would work.
The reason of infinite loop is that your f and l values are updated at most once. initially m points to the middle of array (i.e. (n-1)/2) and from that moment,
-if the element a[m] is less than x, you infinitely assign m+1 i.e. (n-1)/2 + 1to f
-if the element a[m] is larger than x, you infinitely assign (n-1)/2 - 1 to l
In either case, f never gets larger than l and l never gets smaller than f (unless array has a single element or it has two elements and x<a[0])
Try updating the function in the following way:
int foo(int x, int f, int l)
{
int m = (f+l)/2;
while(f<=l)
{
if(a[m]==x)
return 1;
else if(a[m]<x)
{
f = m+1; m = f;
}
else if(a[m]>x)
{
l = m-1; m = l;
}
}
return 0;
}

The most occuring number in structure(array)

I cant find out whats wrong with this part of my program, i want to find out most occuring number in my structure(array), but it finds only the last number :/
void Daugiausiai(int n)
{
int max = 0;
int sk;
for(int i = 0; i < n; i++){
int kiek = 0;
for(int j=0; j < n; j++){
if(A[i].datamet == A[j].datamet){
kiek++;
if(kiek > max){
max = kiek;
sk = A[i].datamet;
}
}
}
}
}
ps. its only a part of my code
You haven't shown us enough of your code, but it is likely that you are not looking at the real result of your function. The result, sk is local to the function and you don't return it. If you have global variable that is also named sk, it will not be touched by Daugiausiai.
In the same way, you pass the number of elements in your struct array, but work on a global struct. It is good practice to "encapsulate" functions so that they receive the data they work on as arguments and return a result. Your function should therefore pass both array length and array and return the result.
(Such an encapsulation doesn't work in all cases, but here, it has the benefit that you can use the same function for many different arrays of the same structure tape.)
It is also enough to test whether the current number of elements is more than the maximum so far after your counting loop.
Putting all this together:
struct Data {
int datamet;
};
int Daugiausiai(const struct Data A[], int n)
{
int max = 0;
int sk;
for (int i = 0; i < n; i++){
int kiek = 0;
// Count occurrences
for(int j = 0; j < n; j++){
if(A[i].datamet == A[j].datamet) kiek++;
}
// Check for maximum
if (kiek > max) {
max = kiek;
sk = A[i].datamet;
}
}
return sk;
}
And you call it like this:
struct Data A[6] = {{1}, {2}, {1}, {4}, {1}, {2}};
int n = Daugiausiai(A, 6);
printf("%d\n", n); // 1
It would be nice if you had english variable names, so I could read them a bit better ^^. What should your paramter n do? Is that the array-length? And what should yout funtion do? It has no return value or something.
int getMostOccuring(int array[], int length)
{
int current_number;
int current_count = 0;
int most_occuring_number;
int most_occuring_count = 0;
for (int i = 0; i < length; i++)
{
current_number = array[i];
current_count = 0;
for (int j = i; j < length; j++)
{
int test_number = array[j];
if (test_number == current_number)
{
current_count ++;
if (current_count > most_occuring_count)
{
most_occuring_number = current_number;
most_occuring_count = current_count;
}
}
}
}
return most_occuring_number;
}
this should work and return the most occuring number in the given array (it has a bad runtime, but is very simple and good to understand).

C++ does not want a return value

I'm trying some exercise to learn the use of pointers with arrays and functions.
So I tried to code a "strange way" to find out primes within a certain range.
The problem is that the output always add the return value of the function with the algorithm for the primes. if I omit it, it shows is '32767', if I write return *pt, it adds the last number of the range, even if it's not a prime!
Just tried it with number 6: it's not a prime but it pops up!
#include <iostream>
int show_primes(const int * begin, const int * end);
int main()
{
using namespace std;
int i = 0;
int End_Array = 0;
cout << "Write the last number in your range (it always start from number 2)";
cin >> End_Array;
i=End_Array;
int cookies[i];
for(i=-1; i<End_Array; i++)
cookies[i] = i+1;
cout << show_primes(cookies, cookies + End_Array-1);
}
int show_primes (const int * begin, const int * end)
{
using namespace std;
const int * pt;
int z = 0;
for (pt = begin; pt < end; pt++, z=0)
{
for (int n=2; n<=*pt; n++)
if ( *pt%n == 0 )
++z;
if (z==1)
cout << *pt <<endl;
}
return *pt ;
}
Your loop is accessing a value at negative index.
cookies[i] = i+1; //For first iteration, value of i is -1
So for(i=-1; i<End_Array; i++) should be changed to for(i=0; i<End_Array; i++)
Also, you do not need to return from the function as you are printing the values within itself
Although you are using pointers for your learning, a more simpler implementation would be:
#include <iostream>
using namespace std;
void show_primes(int num)
{
bool flag = false;
for (int pt = 2; pt < num; pt++)
{
if ( num%pt == 0 )
{
flag = true;
break;
}
}
if(!flag)
{
cout<<num<<' ';
}
}
int main()
{
int End_Array = 0;
cout << "Write the last number in your range(>2)";
cin >> End_Array;
for(int i=2; i<End_Array; i++)
{
show_primes(i);
}
}
P.S.: Can someone please highlight that is it a bad practice to include std namespace in every functional block as OP has done.(I think it is)
for(i=0; i<End_Array; i++) // Start from zero
cookies[i] = i; //Use i
// Don't use cout
show_primes(cookies, cookies + End_Array-1);