My code is generating duplicates (3) to be precise and I don't know why, could anyone help out?
I've tried searching for a problem, but to my eyes it seems the same as other premutation codes on the internet.
I was thinking it could've been a miss-use of the loop but I don't see why it's giving me 9 answers instead of 6.
#include <iostream>
using namespace std;
void swap(char *a, int x, int y);
void print(char *a, int n);
void permute(char *a, int n, int index);
int grabSize(char a[]);
int main() {
char array[] = {'a', 'b', 'c'}; // PLACE COMPONENTS HERE
int n = grabSize(array);
//
cout << "[" << endl;
cout << " ";
permute(array, n, 0);
cout << endl << "]";
}
int grabSize(char a[]) {
int i = 0;
while (a[i] != '\0') {
i++;
}
return i;
}
void swap(char *a, int x, int y) {
char aux;
aux = a[x];
a[x] = a[y];
a[y] = aux;
}
void permute(char *a, int n, int index) {
if (index == n-1) {
print(a, n);
return;
}
for (int i = 0; i < n; i++) {
swap(a, i, index);
permute(a, n, index+1);
swap(a, i, index);
}
}
void print(char *a, int n) {
cout << " [ ";
for (int i = 0; i < n; i++) {
cout << a[i];
}
cout << " ] ";
}
You are getting 9 combinations of string because, in permute(), the for loop variable i initialised with 0:
for (int i = 0; i < n; i++) {
^^^
Note that you are calling permute() function recursively to generate the permutations of string and, in every recursive call, the index is incremented by 1 while passing to permute() function but the for loop , in permute() function, starts with 0 and iterate till < n. Hence you are getting n*n combinations of string in output. Instead, the for loop variable i should be initialised with index:
for (int i = index; i < n; i++) {
^^^^^
Other problems in your code:
This
char array[] = {'a', 'b', 'c'};
is array of 3 characters. Note that there is no terminating null character in array array. Passing it to grabSize() function and checking for '\0' character in it will lead to UB as grabSize() function will end up accessing array array beyond its size while looking for null terminating character. To get the size of array, you can simply do sizeof(array)/sizeof(array[0]) in main() function and do away with grabSize() function.
If you are inclined to use grabSize() function then either add null terminating character manually
char array[] = {'a', 'b', 'c', '\0'};
or initialise array array with string, like this
char array[] = "abc";
and then pass it to grabSize() function.
Suggestion:
In C++, the use of plain C style array is discouraged. C++ has Containers Library, go through it. The sequence container array and vector will be of your interest.
Related
My teacher has me complete this(the main is hidden) and i wonder why i got an infinite loop with this solution.
Task:
Complete this function:
void pad_left(char *a, int n) {
}
// if length of a greater than n, do nothing
// else insert '_' util a 's length is n
Some case i got an segmentfault
I try realloc but it return new ptr
My solution
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
void printChar(char *a) {
int i = 0;
while(a[i] != '\0') cout << a[i];
cout << endl;
}
void insert_begin(char *a, int n) {
for(int i = n; i > 0; i--) {
a[i] = a[i-1];
}
a[n+1] = '\0';
}
void pad_left(char *a, int n) {
int len = n - strlen(a);
for(int i = 0; i < len; i++) {
insert_begin(a, strlen(a));
}
}
Here is full code
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
void printChar(char *a) {
int i = 0;
while(a[i] != '\0') cout << a[i];
cout << endl;
}
void insert_begin(char *a, int n) {
for(int i = n; i > 0; i--) {
a[i] = a[i-1];
}
a[n+1] = '\0';
}
void pad_left(char *a, int n) {
int len = n - strlen(a);
for(int i = 0; i < len; i++) {
insert_begin(a, strlen(a));
}
}
int main() {
ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
char a[5] = "test";
pad_left(a, 10);
printChar(a);
return 0;
}
Okay, you need some background information.
void pad_left(char *a, int n) {
}
char a[5] = "test";
pad_left(a, 10);
This is going to be a significant problem. First, you can't realloc for two reasons. First, char a[5] is a fixed array -- not an allocated array. When you pass it to pad_left, that doesn't change. realloc() does a free of the old pointer, but you can't do that, and it will cause problems. So you cannot use realloc in your solution unless you make sure the strings came from allocated memory. And you can't assume that.
So put realloc aside. You can't use that.
Next, char a[5] only allocates 5 bytes. If you start writing beyond that range (by passing in 10 to your method), you're going to step on other places. This is absolutely bad.
So... Without testing it, the rest of your code seems reasonable. You can probably get a good test if you do this:
char a[100] = "test";
pad_left(a, 10);
You'll have allocated plenty of space for padding. Try this and see if you get further.
I am supposed to be creating a program that asks a user to populate an array of size 10. There are three functions which by their name are self-explanatory; one fills up the array with elements, the second one displays the array horizontally, and the third function checks to see if a number entered by the user is an element in the array.
#include<iostream>
#include<iomanip>
void fillUpArray(int array[], int size);
void displayArray(int array[], int size);
bool isNumberPresent(int array[], int size, int SearchNum);
int main(){
int s = 10; //size of array
int A[s]; //array A with size s
int num; //search number
fillUpArray(A, s);
std::cout <<"\n";
displayArray(A, s);
std::cout << "\n";
std::cout << "Enter a number to check if it is in the array:\n";
std::cin >> num;
std::cout << std::boolalpha << isNumberPresent(A, s, num) << std::endl;
return 0;
}
void fillUpArray(int array[], int size)
{
std::cout << "Enter 10 integers to fill up an array, press enter after every number:\n";
for(int i = 0; i < size; i++){
std::cin >> array[i];
}
}
void displayArray(int array[], int size)
{
for(int j = 0; j < size; j++){
std::cout << array[j] << "\t";
}
}
bool isNumberPresent(int array[], int size, int SearchNum)
{
bool isPresent;
for(int k = 0; k < size; k++){
if(array[k] == SearchNum)
isPresent = true;
else
isPresent = false;
}
return isPresent;
}
That last function, which is a bool function, is not performing the way I thought it would. I thought by doing array[k] whatever index k is then it should spit out the element in the array and then with the expression if(array[k] == SearchNum) it should then work as if(element == SearchNum) but that doesn't seem to be the case and the output is always false.
The for loop in your isNumberPresent function will run to the end of the array (until k equals size) unconditionally; in each run of that loop, you set the value of the isPresent variable according to whether or not the current element is a match for searchNum, overwriting the previous value. So, the function, as it stands, will simply return whether or not the last element in the array is the same as the given test number.
You can simplify that function and remove the need for the local variable: if you find a match, then return true immediately; if the loop ends without finding a match, then return false:
bool isNumberPresent(int array[], int size, int SearchNum)
{
for(int k = 0; k < size; k++){
if(array[k] == SearchNum) return true; // Found a match - we can return immediately
}
return false; // We didn't find a match
}
Note, also, that Variable Length Arrays (VLAs) are not part of Standard C++, though some compilers (like GNU g++) support them (they are part of the C language according to the C99 Standard). In your program, as you only use one (fixed) value for the array size, you can conform to Standard C++ simply by qualifying that s is a const:
int main()
{
const int s = 10; //size of array - make this a "const" be 'proper' C++
int A[s]; //array A with size s
//...
my code is not working it is producing unexpected results.the code is about array rotation by using a temp array . function "rotate" rotates the array , while function printArray prints the array .in the main function both functions are called. then there is cout with "hello". the overall output if "ellolloloohello". why am i getting this output.thanks
#include<iostream>
using namespace std;
void rotate(int arr[],int d, int n){
int temp[d];
for(int i =0;i<d;i++){
temp[i]=arr[i];
}
for(int i = 0;i<n-d;i++){
arr[i] = arr[i+d];
}
for(int i =0 ;i < d;i++)
{
temp[i]= arr[n-d+i];
}
}
void printArray(int arr[],int size){
for(int i =0;i<size;i++)
{
cout<<arr[i]+" " ;
}
}
int main()
{
int arr[10] = {0,1,2,3,4,5,6,7,8,9};
rotate(arr,3,10);
printArray(arr,10);
cout <<"hello";
}
;
the output is "ellolloloohello" instead of "hello". whats happening here?????
For starters the variable length arrays
void rotate(int arr[],int d, int n){
int temp[d];
//...
is not a standard C++ feature. Either use an auxiliary standard container as for example std::vector or std::list or you should dynamically allocate an array.
In the last loop of the function
void rotate(int arr[],int d, int n){
int temp[d];
for(int i =0;i<d;i++){
temp[i]=arr[i];
}
for(int i = 0;i<n-d;i++){
arr[i] = arr[i+d];
}
for(int i =0 ;i < d;i++)
{
temp[i]= arr[n-d+i];
}
}
you are overwriting the array temp instead of the array arr.
And in the function printArray in this statement
cout<<arr[i]+" " ;
in the expression
arr[i]+" "
there is used the pointer arithmetic. That is the string literal " " is implicitly converted to pointer to its first element and the numeric value arr[i] is used as an offset for this pointer. Instead write
cout<<arr[i] << " " ;
Change cout<<arr[i]+" " ; to cout << arr[i] << ' ';
And please use std::vector. int arr[d] is no c++ :(
I need some help here please.
I just started learning C++ (coming from Python background).
I'm trying to familiarize myself with arrays and functions. Wrote a bunch of functions to do as stated, above each one.
However, the function which is supposed to sum elements in an array and return their sum, seem to be adding 10 to the result, no matter the argument supplied as input. What am I doing wrong please, as I can't seem to find this out. Any help on general layout of my code also would be appreciated.
// WORKING WITH ARRAYS AND FUNCTIONS
#include<iostream>
using namespace std;
// FUNCTION TO INSTANTIATE ARRAY INT OF LENGTH N.
int* array_creator(int n)
{
static int ary_of_ten[10]; //declare array
for (int i=0; i<n; i++) //use loop to fill it up
{
ary_of_ten[i] = i+1;
}
return ary_of_ten;
}
//FUNCTION TO PRINT ARRAY ELEMENTS
void* array_printer(int arr[], int array_lenght)
{
for (int i=0; i<array_lenght-1; i++)
{
cout << arr[i] << " ";
}
cout << arr[array_lenght-1] << endl;
}
//FUNCTION ACCEPTS INT ARRAYS AND RETURNS ARRAY OF SQUARE OF EACH ELEMENT
int* square_array(int *p, int array_length)
{
const int ary_sz(array_length);
static int sqd_values[10];
for (int i=0; i<ary_sz; i++)
{
*(sqd_values + i) = *(p+i) * *(p+i);
}
return sqd_values;
}
//FUNCTION ACCEPTS INT ARRAYS AND RETURNS SUM OF ITS ELEMENTS
int sum_array(int *arry, int array_length)
{
int summation;
for(int i=0; i<array_length; i++)
{
summation += *(arry + i);
}
return summation;
}
int main()
{
cout << sum_array(array_creator(10), 3) << endl;
array_printer(array_creator(10), 10); //print array of 1-10 elements
array_printer(square_array(array_creator(10), 10), 10); //prt arry of sqrd values
return 0;
}
summation shuld be initialized to 0.
int summation=0;
Hello im trying to write this program which replace each negative number with -1 and positive with 1
but an error :
[Error] cannot convert 'int ()[3]' to 'int ()[100]' for argument '1' to 'void replace(int (*)[100], int, int)'
what does that mean ??
#include<iostream>
using namespace std;
void replace(int Arr[][100],int rsize, int csize)
{
for(int r=0;r<rsize;r++)
{
for (int c=0;c<csize;c++)
{
if (Arr[r][c]>0) Arr[r][c]=1;
else if (Arr[r][c]<0) Arr[r][c]=-1;
else Arr[r][c]=0;
}
}
}
int main()
{
int a[4][3]={
{2,0,-5},
{-8,-9,0},
{0,5,-6},
{1,2,3}};
replace(a,4,3);
for(int i=0;i<4;i++)
for (int j=0;j<3;j++)
cout<<a[i][j]<<" ";}cout<<endl;
system ("pause");
return 0;
}
You declared function void replace(int Arr[][100],int rsize, int csize) - it expects 2D array, with 'inner' dimension being 100.
Then you pass to it int a[4][3] which has 'inner' dimension 3. Compiler can't convert it. Those dimensions are used to calculate memory position shift when using Arr[x][y] (it is equivalent to *(Arr + x * 100 + y). That's why compiler can't assign array with 3 to array with 100.
If you want your replace to work with any dimension change it to:
void replace(int* Arr,int rsize, int csize). Then use *(Arr + r*csize + c) to access fields instead of Arr[r][c]
Even better solution: you tagged this question as C++ - use C++ library :) - std::vector<std::vector<int> > or std::array (C++11)
Well you declare a function which takes int[][100], then you pass it an int[4][3]. C++ doesn't work like this. In fact, you can't actually pass arrays by value at all; they decay to pointers implicitly.
If you want your function to take arbitrarily sized arrays, you could just make it take pointers to pointers instead:
void replace(int** Arr,int rsize, int csize)
Then you should throw your code away and use std::vector instead:
void replace(std::vector<std::vector<int>> &Arr)
If you want some compile-time constraints on the size of the array, you could do something like:
template <std::size_t X, std::size_t Y>
void replace (std::array<std::array<int,Y>,X>& Arr)
{
static_assert (Y <= 100, "Inner array is too large");
}
The issue is that you're declaring your argument (Arr[][100]) as having 100 elements. But it's not 100 elements, it's three in your code. I'm assuming what you really want is to be able to pass different sized arrays, and specify the array dimensions in the other arguments. If that's the case, you can just declare the array as an int *. So something like the following will work:
#include "stdafx.h"
#include<iostream>
using namespace std;
void replace(int *Arr, int rsize, int csize);
void print(int *Arr, int rsize, int csize);
int _tmain(int argc, _TCHAR* argv[])
{
int a[4][3] = {
{ 2, 0, -5 },
{ -8, -9, 0 },
{ 0, 5, -6 },
{ 1, 2, 3 } };
print((int *)a, 4, 3);
replace((int *)a, 4, 3);
for (int i = 0; i<4; i++)
{
for (int j = 0; j<3; j++)
{
cout << a[i][j] << " ";
}cout << endl;
}
system("pause");
return 0;
}
void replace(int *Arr, int rsize, int csize)
{
for (int r = 0; r<rsize; r++)
{
for (int c = 0; c<csize; c++)
{
int index = (r * (rsize - 1)) + c;
if (Arr[index] > 0)
{
Arr[index] = 1;
}
else if (Arr[index] < 0)
{
Arr[index] = -1;
}
else
{
Arr[index] = 0;
}
}
}
}
void print(int *Arr, int rsize, int csize)
{
char str[256];
for (int r = 0; r<rsize; r++)
{
sprintf(str, "");
for (int c = 0; c<csize; c++)
{
int index = (r * (rsize - 1)) + c;
if (strlen(str) > 0)
{
sprintf(str, "%s, ", str);
}
sprintf(str, "%s%d", str, Arr[index]);
}
cout << str;
cout << endl;
}
}
Don't follow my example of using the unsafe string functions.
The reason this works is that a two-dimensional int array is just a bunch of one dimensional arrays stacked together. So an int[4][3] is just 12 ints in memory. That's functionally identical to an int[12]. If you declare the input to the function as an int *, then it's a pointer to a block of memory that contains ints, doesn't matter how many. So you can avoid the type cast errors you were getting.
There's lots of risk with doing this if you don't make sure your parameters are correct. For example, if you call the same replace function with the same input array, but claim it has 5 rows, then you'll start reading uninitialized memory. (Possibly uninitialized...more accurately, you'll at least be reading memory that is not what you think it is.) Of course, you can do the same thing without the pointer, that's the whole fun part of C++.