Parsing an array from recursion function C++ - c++

So I a little new to C++ and discovery what I can and can't do in comparison to python. Basically I have a function and inside that function I want to parse through an array and some integers run it, and return the output number. But it seems to prove a little tricky. Wondering where I am messing up.
Since the function it contains in is dominated by recursion I can't just make it a global variable where the array values are static.
So here is an outline of the code
void sequenceAlignment(int iStart,int jStart,int kStart, int seqLen1Size, int seqLen2Size, int seqLen3Size) {
int lengthi = seqLen1Size - iStart;
int lengthj = seqLen2Size - jStart;
int lengthk = seqLen3Size - kStart;
/* Sets it as a floor */
int midpoint = (seqLen1Size + iStart) / 2;
/*End the recursion*/
if (lengthi <= 1)
return;
/*We set two scoring arrays and intialize the XY Plane in the 3D */
int forwardScore[2][lengthj + 1][lengthk + 1];
int backwardsScore[2][lengthj + 1][lengthk + 1];
/* Some code */ and then to this
forwardSubscoringCalculation(multidimensionalarray, int, int, int, int, int, int)
The Function that is being called
void forwardSubscoringCalculation(int forwardScore, int scorei, int scorej, int scorek, int scoredArrayi, int scoredArrayj, int scoredArrayk) {
int tempValueHolder = 0;
int subscore[3] = {-10000, -10000, -10000};
subscore[0] = forwardScore[scorei][scorej][scorek] + scoredArray[scoredArrayi][scoredArrayj][scoredArrayk];
}
I am wondering how can I exactly do this. I thought by setting up the array it also acts like a pointer and be passed through but I might screwing that up. Is it possible in this code or can it be quite tricky?
EDIT Minimal Code
void score(int, int, int, int, int, int, int);
void function(int, int ,int, int, int, int)
void function(int i, int j, int k, int l, int m, int n) {
int forward[Number][Number][Number];
for (x = 0; x >= l; x++){
score(forward, i + x, j, k l, m n)
}
}
void score(int array, value1, value2, value3, value4, value 5, value6){
/* Do some stuff with the array */
}

Related

C++ combination function always resulting 0

can anybody tell me why my Combination function is always resulting 0 ?
I also tried to make it calculate the combination without the use of the permutation function but the factorial and still the result is 0;
#include <iostream>
#include <cmath>
using namespace std;
int factorial(int& n)
{
if (n <= 1)
{
return 1;
}
else
{
n = n-1;
return (n+1) * factorial(n);
}
}
int permutation(int& a, int& b)
{
int x = a-b;
return factorial(a) / factorial(x);
}
int Combination(int& a, int& b)
{
return permutation(a,b) / factorial(b);
}
int main()
{
int f, s;
cin >> f >> s;
cout << permutation(f,s) << endl;
cout << Combination(f,s);
return 0;
}
Your immediate problem is that that you pass a modifiable reference to your function. This means that you have Undefined Behaviour here:
return (n+1) * factorial(n);
// ^^^ ^^^
because factorial(n) modifies n, and is indeterminately sequenced with (n+1). A similar problem exists in Combination(), where b is modified twice in the same expression:
return permutation(a,b) / factorial(b);
// ^^^ ^^^
You will get correct results if you pass n, a and b by value, like this:
int factorial(int n)
Now, factorial() gets its own copy of n, and doesn't affect the n+1 you're multiplying it with.
While we're here, I should point out some other flaws in the code.
Avoid using namespace std; - it has traps for the unwary (and even for the wary!).
You can write factorial() without modifying n once you pass by value (rather than by reference):
int factorial(const int n)
{
if (n <= 1) {
return 1;
} else {
return n * factorial(n-1);
}
}
Consider using iterative code to compute factorial.
We should probably be using unsigned int, since the operations are meaningless for negative numbers. You might consider unsigned long or unsigned long long for greater range.
Computing one factorial and dividing by another is not only inefficient, it also risks unnecessary overflow (when a is as low as 13, with 32-bit int). Instead, we can multiply just down to the other number:
unsigned int permutation(const unsigned int a, const unsigned int b)
{
if (a < b) return 0;
unsigned int permutations = 1;
for (unsigned int i = a; i > a-b; --i) {
permutations *= i;
}
return permutations;
}
This works with much higher a, when b is small.
We didn't need the <cmath> header for anything.
Suggested fixed code:
unsigned int factorial(const unsigned int n)
{
unsigned int result = 1;
for (unsigned int i = 2; i <= n; ++i) {
result *= i;
}
return result;
}
unsigned int permutation(const unsigned int a, const unsigned int b)
{
if (a < b) return 0;
unsigned int result = 1;
for (unsigned int i = a; i > a-b; --i) {
result *= i;
}
return result;
}
unsigned int combination(const unsigned int a, const unsigned int b)
{
// C(a, b) == C(a, a - b), but it's faster to compute with small b
if (b > a - b) {
return combination(a, a - b);
}
return permutation(a,b) / factorial(b);
}
You dont calculate with the pointer value you calculate withe the pointer address.

C++ adding two array items and other errors on run

When I compile and run this program, I get different errors mostly regarding the calling of the function and the sum of arrays - I have tried fixing them myself but whenever I fix one problem I seem to never be able to fix them all as more come in then leave.
/*
Even Fibonacci numbers
Problem 2
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
*/
#include <iostream>
#include <string>
using namespace std;
int increaseArray(int array, int currentPointer, int maxNumber, int arraySize, bool stop, int total);
int main () {
int arraySize = 2;
int maxNumber = 4000000;
int currentPointer = 1;
int array[2] = {1, 2};
int total = 0;
bool stop = false;
while (not stop) {
increaseArray(array, currentPointer, maxNumber, arraySize, stop, total);
}
}
int increaseArray(int array, int currentPointer, int maxNumber, int arraySize, bool stop, int total) {
int newValue = array[currentPointer - 1] + array[currentPointer - 2];
while (newValue < maxNumber) {
arraySize++;
int *array = new int[arraySize];
array[arraySize] = newValue;
if (newValue % 2 == 0) {
total += newValue;
increaseArray(array, currentPointer, maxNumber, arraySize, stop, total);
}
stop = true;
return total;
}
};
Here are the errors that I am getting:-
error: no matching function for call to 'increaseArray'
increaseArray(array, currentPointer, maxNumber, arraySize, stop, total);
^~~
note: candidate function not viable: no known conversion from 'int [2]' to 'int' for 1st argument
int increaseArray(int array, int currentPointer, int maxNumber, int arraySize, bool stop, int total);
^
error: subscripted value is not an array, pointer, or vector
int newValue = array[currentPointer - 1] + array[currentPointer - 2];
~^~~~~
error: subscripted value is not an array, pointer, or vector
int newValue = array[currentPointer - 1] + array[currentPointer - 2];
~^~~~~
error: no matching function for call to 'increaseArray'
increaseArray(array, currentPointer, maxNumber, arraySize, stop, total);
^~~
note: candidate function not viable: no known conversion from 'int ' to 'int' for 1st argument; dereference the argument with
int increaseArray(int array, int currentPointer, int maxNumber, int arraySize, bool stop, int total) {
^
4 errors generated.
The problem is in the declaration of increaseArray function.
You want to pass as an argument a whole array, but you declare that the first argument is just an integer.
One solution to the problem would be:
int increaseArray(int * array,....).
I would strongly recommend to learn more about passing arrays to functions.
A good place to start would be: https://www.tutorialspoint.com/cplusplus/cpp_passing_arrays_to_functions.htm
I hope that helps!

Why would this code give a segfault only for some cases?

I am trying to code a Word-RAM version of the subset sum. (It is a basic dp algorithm, and the algo itself should not be important to determine the problem with the code). This is the minimum code needed to reproduce the error I think:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
// get bit #bitno from num. 0 is most significant.
unsigned int getbit(unsigned int num, int bitno){
unsigned int w = sizeof(int)*8; //for regular word.
int shiftno = w-bitno-1;
unsigned int mask = 1<<shiftno;
unsigned int maskedn = num&mask;
unsigned int thebit = maskedn>>shiftno;
return thebit;
}
/* No boundary array right shift */
unsigned int* nbars(unsigned int orig[], unsigned int x){
int alength = sizeof(orig)/sizeof(orig[0]);
unsigned int b_s = sizeof(int)*8;
unsigned int * shifted;
shifted = new unsigned int[alength];
int i;
for(i=0;i<alength;i++){
shifted[i] = 0;
}
unsigned int aux1 = 0;
unsigned int aux2 = 0;
int bts = floor(x/b_s);
int split = x%b_s;
i = bts;
int j = 0;
while(i<alength){
aux1 = orig[j]>>split;
shifted[i] = aux1|aux2;
aux2 = orig[j]<<(b_s-split);
i++;j++;
}
return shifted;
}
/* Returns true if there is a subset of set[] with sum equal to t */
bool isSubsetSum(int set[],int n, int t){
unsigned int w = sizeof(int)*8; //for regular word.
unsigned int wordsneeded = ceil(double(t+1)/w);
unsigned int elements = n;
//Create table
unsigned int table[elements][wordsneeded];
int c,i;
//Initialize first row
for(i=0;i<wordsneeded;i++){
table[0][i] = 0;
}
table[0][0] = 1<<(w-1);
//Fill the table in bottom up manner
int es,ss,ai;
for(c=1;c<=elements; c++){
unsigned int *aux = nbars(table[c-1],set[c-1]);
for(i=0;i<wordsneeded;i++){
table[c][i] = table[c-1][i]|aux[i];
}
}
if((table[elements][wordsneeded-1]>>((w*wordsneeded)-t-1))&1 ==1){
return true;
}return false;
}
int main(){
int set[] = {81,80,43,40,30,26,12,11,9};
//int sum = 63;
int sum = 1000;
int n = sizeof(set)/sizeof(set[0]);
if (isSubsetSum(set,n,sum) == true)
printf("\nFound a subset with given sum\n");
else
printf("\nNo subset with given sum\n");
return 0;
}
Ok. so If I run the example with a target sum of 63, it works just fine. gives the right answer , True, and if I run code to print the subset it prints the right subset. however, if I change the sum to a larger one, say 1000 like in the code, I get the following error:
Program received signal SIGSEGV, Segmentation fault.
0x0000000000400af1 in isSubsetSum (set=0x0, n=0, t=0) at redss.cpp:63
63 unsigned int *aux = nbars(table[c-1],set[c-1]);
from gdb. I really don't understand why it would fail only for larger sums, since the process should be the same... am I missing something obvious? Any help would be great!!!

Bitwise arithmetic on an integer return value

Here we have a function fire() which accepts two arguments:
A capital letter (char) in the range of 'A' .. 'A'+BS_GRID_ROWS-1 that indicates the row in your grid to attack.
An integer (int) in the range of 1 .. BS_GRID_COLS that indicates the column of your grid to attack.
The return code will be:
0 if there is only open water.
The bit BS_SHIP_HIT will be set, or both BS_SHIP_HIT and BS_SHIP_SANK will be set. In addition, the ship that was hit will be indicated in the lowest four bits of the return code. You may use BS_SHIP_MASK to help extract the number for the ship type.
semi-pseudocode interpretation:
//r is A ... (A + BS_GRID_ROWS - 1)
//c is 1 ... BS_GRID_COLS
fire(char r, int c) {
//some set of commands
if(miss) {
return 0;
else if(sink) {
return hit + sunk + size;
else if(hit) {
return hit;
else {
return miss;
}
}
I am uncertain of exactly how I might go about extracting these individual values (hit, sunk, size) from the return value.
The actual .h file and it's relevant const values are seen here:
#ifndef BATTLESHIP
#define BATTLESHIP
const int BS_SHIP_HIT = 0x10; // Ship is hit, or
const int BS_SHIP_SANK = 0x20; // sank (must also | BS_SHIP_HIT)
const int BS_CARRIER = 1;
const int BS_BATTLESHIP= 2;
const int BS_CRUISER = 3;
const int BS_DESTROYER = 4;
const int BS_SUBMARINE = 5;
const int BS_SHIP_COUNT = 5;
const int BS_SHIP_MASK = 0x0F;
const int BS_CARRIER_SIZE = 5;
const int BS_BATTLESHIP_SIZE= 4;
const int BS_CRUISER_SIZE = 3;
const int BS_DESTROYER_SIZE = 2;
const int BS_SUBMARINE_SIZE = 3;
const int BS_MODE_NEW_GAME = 1;
const int BS_MODE_CONTINUE_GAME = 2;
const int BS_GRID_ROWS = 10; // letters A to J
const int BS_GRID_COLS = 10; // numbers 1 to 10
const int MaxPlayerCount = 65; // Maximum size for following arrays
extern int userIncoming(char, int);
extern int userBattle(int, int);
extern int incomingStub(char, int);
extern int battleStub(int, int);
extern int (*fire[])(char, int);
extern int (*battleship[])(int, int);
extern char const *playerName[];
#endif
Something like this perhaps?
int result = fire(r, c);
if (result & BS_SHIP_HIT)
{
std::cout << "Ship of size " << result & BS_SHIP_MASK << " hit\n";
}
If the BS_SHIP_HIT bit is set in result, the the result of result & BIT_SHIP_HIT will be equal to BS_SHIP_HIT otherwise the result will be zero (which is equivalent to false).
The result of result & BS_SHIP_MASK will be the low four bits in result.
Or lets look at it using the actual bits:
BS_SHIP_HIT is equal to the binary value 00010000 and BS_SHIT_MASK equal 00001111. Lets assume that fire returns 00010101 (BS_SHIP_HIT set and size 5), then the if condition will be
00010000
& 00010101
----------
= 00010000
Then for the printing, the expression will be
00010101
& 00001111
----------
= 00000101

Why can't I use this function with inside a function with const?

I'm creating a bit array using unsigned chars for an assignment in my object oriented programming course. I was given the basic layout of what function we need. One was our Query function which is const.
this is my member data:
unsigned char* barray; // pointer to the bit array
unsigned int arraySize;
static const unsigned int charSize = (sizeof(unsigned char) * 8);
and this is the function I'm having issues with:
bool BitArray::Query(unsigned int index)const{
unsigned int i = (Index(index)),
p = Position(index);
unsigned int check = 1;
check = Move(check, p);
if ((check & barray[i]) == 0)
return false;
else
return true;
}
This function as well as an operator<< overload (also uses const keyword) get pissed off at me when I use my other functions in them (Index, Position, Move).
"IntelliSense: the object has type qualifiers that are not compatible with the member function "BitArray::Index" object type is const BitArray"
What is going on?
/* determine which element in array of chars to use */
unsigned int BitArray::Index(unsigned int n){
unsigned int index = (n / charSize);
if (((n % charSize) == 0) && (index < 0)){
index -= 1;
}
return index;
}
/* determine index of bit of the particular char */
unsigned int BitArray::Position(unsigned int n){
unsigned int position = n;
position -= ((n / charSize) * charSize);
if (position == 0)
position = charSize - 1;
else
position--;
return position;
}
unsigned int BitArray::Move(unsigned int n, unsigned int m){
return n << m;
}
Using Microsoft Visual Studio Express 2013
Those other functions need to be marked const as well. If they're not const, then you have no business calling them from a const function.