Pascals Triangle using one dimensional array c++ - c++

I am trying to figure out how to make pascals triangle with just one, one dimensional array. I have some code here that I have been working with but it gets stuck. Thanks in advance. If you need the rest of the program please let me know and ill post it.
int fillArray(int triArray[], int arrSize)
{
int last = 1;
int current = 3;
int flag = 0;
for (int x = current; x < arrSize; x++)
{
if (triArray[last] == 1 && flag == 0)
{
triArray[current] = 1;
current++;
last++;
flag++;
cout << triArray[x] << " ";
}
triArray[current] = triArray[last] + triArray[last - 1];
current++;
cout << triArray[x] << " ";
if (triArray[last] == 1)
{
triArray[current] = 1;
flag = 0;
current++;
last++;
cout << triArray[x] << endl;
}
}
return *triArray;
}

You should think of creating each row in turn, and storing them sequentially in your linear array. Build up some abstraction over the linear array to be able to access by row and column. Otherwise you will just get all tangled up in the code (as you seem to be right now).

Related

Visual studio doesn't take array: int magicSquare[n][n]?

I wrote my code and I'm ready to submit it but the teacher will be testing it on Visual studio 2015. Every time I test it, it gives me an error that this int magicSquare[n][n] is wrong and that n can't be read.
How do i revise this part to make visual studio read this array from n ?
My code:
#include <iostream>
using namespace std;
// This function is to create the requested magic squares
int main()
{
int n;
//asking for n
cout << "Please enter an odd number" << endl;
cin >> n;
//checking in case n doesnt follow rules
if (n < 3 || n % 2 == 0)
{
cout << "Invalid Entry, Please re-enter an odd number that is 3 or larger " << endl;
}
else
{
// A function to generate odd sized magic squares
int magicSquare[n][n];
// Setting every slot to 0
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
magicSquare[j][i] = 0;
}
}
// Initializing position to 1
int j = n / 2;
int i = n - 1;
// Setting each value to generate the magic square
for (int num = 1; num <= n * n; )
{
if (j == -1 && i == n)
{
i = n - 2;
j = 0;
}
else
{
//send to next number
// moving it to the right side
if (i == n)
i = 0;
//send to next number again
// moving it to the upper side
if (j < 0)
j = n - 1;
}
//second condition
if (magicSquare[j][i])
{
i -= 2;
j++;
continue;
}
else
//add the number
magicSquare[j][i] = num++;
//first condition
i++; j--;
}
//displaying sum of col/row
cout << "The sum of each row/col: " << n * (n*n + 1) / 2 << endl;
//Dispplaying magic square
for (j = 0; j<n; j++)
{
for (i = 0; i<n; i++)
cout << " " << magicSquare[i][j];
cout << "\n";
}
}
cout << endl;
//re running program
return main();
}
The standard requires the array length to be a value that is computable at compile time so that the compiler is able to allocate enough space on the stack. In your case, you are trying to set the array length to a value that is unknown at compile time. Yes, i know that it seems obvious that it should be known to the compiler, but this is not the case here. The compiler cannot make any assumptions about the contents of non-constant variables.'n' must be a constant value.
In C++, arrays that are declared that way must use an n that is known at compile time. There are various ways to construct a matrix in C++. Perhaps the simplest is to define a vector of vectors.
Change
int magicSquare[n][n];
to
std::vector<std::vector<int>> magicSquare(n);
for (auto &row : magicSquare) row.resize(n);

set 2D array as function and call it elsewhere as needed

So i have this variable I would like to pass it as function to following code down which still not working yet but any idea about it?? I would also be pleased to know if we can add ctime to track the arrival of the user thanks for your help ..
bool spt_1 [15][12] = {0}
and this is the code which I want to pass it so I can call it later on somewhere in my code
int col = 1;
int row = 1;
for (col = 1 ; row < 16 ; row ++) {
if (spot_1 [col][row] == 0) {
cout<<"There is a place reserved for you in spot, the first column , row number "<<" "<<row<<"."<<endl;
string choice;
do {
cout<<"\nDo you want to take that spot? Y/N.\n"<<endl;
cin>>choice;
cout<<"\n"<<endl;
transform(choice.begin(), choice.end(), choice.begin(), toupper);
}while (choice != "Y" && choice !="YE" && choice != "YES" && cout<<"Wrong input!\n"<<endl);
cout<<"\nHave a nice day.\n"<<endl;
break;
if (choice == "YES") {
spot_1 [col][row] = 1; // should change that specific 0 to 1 ( which means occupied )
}
else {
//it should reject count ++;
}
if (spot_1 [col][row] != 0) { // When there is no more place it should cout this and go search in a new array and do same as first one
cout<<"Sorry ,There is no more place available , But you can go to :\n"<<endl;
}
}
}
}
thanks for your suggestions .
You should probably use a 2D vector instead of that array in the first place. But if you really need to do it with an array you could define a template function like this:
template <int Row, int Col>
void some_func(bool my_array[Row][Col])
{
//do your stuff
//here just printing the array and changing a value
for (int i = 0; i < Row; i++)
{
for (int j = 0; j < Col; j++)
std::cout << my_array[i][j];
std::cout << std::endl;
}
my_array[3][4] = false;
}
and call it in you program like this:
some_func<15,12>(spt_1);
EDIT after comment:
There is always a way, but it gets dirtier.
I would consider this more a C then a C++ question and I'm not a native C speaker.
I would maybe do it this way, but there are probably better ways:
void some_func(void* my_pointer, int row, int col)
{
bool* my_pointer_arr = static_cast<bool*>(my_pointer);
for (int i = 0; i < row * col; i += col)
{
for (int j = 0; j < col; j++)
std::cout << my_pointer_arr[i + j];
std::cout << std::endl;
}
my_pointer_arr[3 * col + 4] = false;
}
Maybe just search for "C style 2D array to function" and you will get a better answer.

C++ Vector Subscript out of Range Error 1221

I am trying to make a program that recieves numbers from the user, and then rearranges the from least to greatest. I am using vectors (which I just learned about), and it gives me a subscript out of range error. I am not able to find what part of the code gives me this error, so hopefully someone more knowledgeable on vector and c++ can find it:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void order(int a, int b);
void orderRev(int a, int b);
int main() {
vector<int> num;
bool going = true;
do {
cout << "\nEnter a number or type 'x' to order:" << endl;
string reply;
getline(cin, reply);
if (reply != "x") {
int a = atoi(reply.c_str());
num.push_back(a);
cout << "\nYou currently have " << num.size() << " numbers added." << endl;
}
else {
going = false;
}
} while (going);
for (int i = 0; i < num.size(); i++) {
order(num[i], num[i + 1]);
}
for (int i = num.size() - 1; i >= 0; i--) {
orderRev(num[i + 1], num[i]);
}
cout << "\nThe number you entered in order from least to greatest are: " << endl;
for (int i = 0; i < num.size(); i++) {
cout << num[i] << " ";
}
void order(int a, int b) {
if (a > b) {
int c = b;
b = a;
a = c;
}
}
void orderRev(int a, int b) {
if (a < b) {
int c = b;
b = a;
a = c;
}
}
Fix these lines to this:
// added the -1 as this will now go up to the 2nd to last element
// for `n`, and the last element for `n+1`
for (int i = 0; i < num.size() - 1; i++) {
order(num[i], num[i + 1]);
}
// changed the starting number to size -2 (for the same reasoning)
for (int i = num.size() - 2; i >= 0; i--) {
orderRev(num[i + 1], num[i]);
}
Why does this need to be this way? Think about how indices in C++ work. They are zero-indexed! That means that if you want both the element and the one in front of it, you must go up to the size of the vector minus 1. Hence, for a vector of 10 items (size 10), at i == 9 your code will work like this:
for (int i = 0; i < num.size(); i++) {
// i = 9
order(num[9], num[9+1]);// index 10 does not exist! Hence, you really need to go up to num.size() - 1!
}
Vectors index start with 0. index will be 0 to n-1 , if you use num[i + 1] it will exceed the vector size, if you don't check in loop condition.
Your code has more than one flaw. The output will be same as the input , hint: know the difference between pass by reference and pass by value and after that check some sorting algorithms.

Bubble sort issue

Currently studying software engineering at college (first year) and made a program where the user enters how many entries there will be and then they input the times for each entry and it is sorted in descending order.
The problem I am having is when I enter a large number for the first input it doesn't sort correctly but the rest do. It would be great if someone could help me out with this and sorry for the noob question:P
The entire code:
#include "stdafx.h"
#include <iostream>
using namespace std;
int TotalSize = 0;
void getSpeed(int *CalculationTime, int NoOfCalculations)
{
for (int i = 0; i < NoOfCalculations; i++)
{
cout << "Please enter the speed of calculation " << i + 1 << "(Ms): "; cin >> CalculationTime[i];
}
}
void sort_speeds(int *CalculationTime, int NoOfCalculations)
{
// Sorting speeds in decending order
bool swapped = true;
int i, j = 0;
int temp;
while (swapped)
{
swapped = false;
j++;
for (i = 1; i < NoOfCalculations - j; i++)
{
if (CalculationTime[i] > CalculationTime[i + 1])
{
temp = CalculationTime[i];
CalculationTime[i] = CalculationTime[i + 1];
CalculationTime[i + 1] = temp;
swapped = true;
}
}
}
// Output times decending order
for (int i = 0; i < NoOfCalculations; i++)
{
cout << CalculationTime[i] << "\n";
}
}
int main()
{
// Declaring & Initializing variables
int NoOfCalculations = 0;
int *CalculationTime = new int[NoOfCalculations];
// Getting user input
cout << "How many calculations are there? "; cin >> NoOfCalculations;
getSpeed(CalculationTime, NoOfCalculations);
// Sorting and displaying times
sort_speeds(CalculationTime, NoOfCalculations);
system("pause");
return 0;
}
You've never compare first element of your array with anything - for (i = 1; i < NoOfCalculations - j; i++) should be for (i = 0; i < NoOfCalculations - j; i++)
The issue is for (i = 1; i < NoOfCalculations - j; i++) You are starting at position 1, start at position 0 and it fixes the problem. for (i = 0; i < NoOfCalculations - j; i++)
// Declaring & Initializing variables
int NoOfCalculations = 0;
int *CalculationTime = new int[NoOfCalculations];
// Getting user input
cout << "How many calculations are there? "; cin >> NoOfCalculations;
Bzzzt. You allocate a zero-element array, and then don't reallocate it. I bet if you entered a large enough number for your number of calculations, your program would crash.
Really, you want to be using std::vector, an extremely useful datastructure, the use of which is a bit outside of the scope of this answer. Basically, you can do stuff like this:
std::vector<int> getSpeeds(int NoOfCalculations)
{
std::vector<int> speeds;
for (int i = 0; i < NoOfCalculations; i++)
{
int speed;
std::cout << "Please enter the speed of calculation " << i + 1 << "(Ms): ";
std::cin >> speed;
speeds.push_back(speed);
}
return speeds;
}
You can use the returned vector almost exactly as if it were an array:
std::vector<int> speeds = getSpeeds(10);;
if (CalculationTime[3] > CalculationTime[4])
// do something
Often, in a C++ application, the explicit use of pointers is a sign that you're not using the standard library, and as a result making life much, much harder for yourself.
Oh, and also:
for (i = 1; i < NoOfCalculations - j; i++)
You never look at NoOfCalculations[0] or NoOfCalculations[i - 1], so you never touch the first element.
while (swapped)
{
swapped = false;
j++;
for (i = 0; i < NoOfCalculations - j; i++) //try and start i from 0. I think you are missing the first element to check
{
if (CalculationTime[i] > CalculationTime[i + 1])
{
temp = CalculationTime[i];
CalculationTime[i] = CalculationTime[i + 1];
CalculationTime[i + 1] = temp;
swapped = true;
}
}
}

Can't find logic error, and need a second pair of eyes

Hi I'm working on this acm problem, and I can't seem to figure out why my algorithm isn't working.
https://icpcarchive.ecs.baylor.edu/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=482
My sillySort function is supposed to be finding all the different subarrays, and then minimizing the sum of the swapped values.
My output is very close to their output, but I'm not sure what's wrong. I have sat down and even written the problem out on a whiteboard. Can anyone spot it?
#include <iostream>
void swap(int* array, int index1, int index2)
{
int temp;
temp = array[index1];
array[index1] = array[index2];
array[index2] = temp;
}
void printArray(int* array, int size)
{
for(int i = 0; i < size; i++)
{
std::cout << array[i] << " ";
}
std::cout << "\n";
}
int sillySort(int* array, int size)
{
int minSum = 0;
bool firstSwap = true;
printArray(array, size);
for(int i = 0; i < size; i++)
{
for(int i2 = i + 1; i2 < size; i2++)
{
//Found a swappable pair
if(array[i] > array[i2])
{
int sum = array[i] + array[i2];
std::cout << "Swapping: " << array[i] << " and " << array[i2] << " (" << sum << ")" << std::endl;
//Temporary swap the array to call silly on it
swap(array, i, i2);
//Calculate silly on new array
int minSilly = sillySort(array, size);
//Found a new minimum
if((minSilly + sum) < minSum || firstSwap)
{
firstSwap = false;
minSum = minSilly + sum;
}
//Move array back into position
swap(array, i, i2);
}
}
}
std::cout << "Returning: " << minSum << std::endl;
return minSum;
}
int main()
{
const int arraySize = 6;
int array[arraySize];
array[0] = 8;
array[1] = 4;
array[2] = 5;
array[3] = 3;
array[4] = 2;
array[5] = 7;
std::cout << sillySort(array, arraySize) << std::endl;
return 0;
}
That was an interesting problem!
Consider the second sample case: the 4-element array is 8124. (It was easier to solve for a 4-element array than a 7-element array; and your program didn't get the best answer on that one either.)
The correct answer of the best cost is 17. Here is a sequence of moves (and I'm sure it's unique, but haven't proved it) that will get you a sorted list with a cost of 17.
Swap 1 and 2. Cost is 3. New sequence is 8214.
Swap 1 and 4. Cost is 5. New sequence is 8241.
Swap 1 and 8. Cost is 9. New sequence is 1248 (sorted).
Total cost is 17.
Your program can't get there because it only swaps elements when they are in the wrong order. My first swap moved 1 to appear after 2, which changed them from the right order to the wrong order... but that move is on the way to the right, and minimal-cost, solution.
So the solution is to relax the assumption that you must only swap things that are out of order. (You'll also need to restructure your algorithm, since that assumption is currently the only thing that prevents infinite recursion.)