C++ stacks and 2D array - c++

I have been working on a Project that is suppose to simulate link list by using 2D array for stacks. I have the code but I can not figure out how to make the Random numbers work. I have looked online but online doesn't explain how to make the random function work with the simulation. Here is my code below:
`#include <iostream>
#include <stdlib.h>
using namespace std;
int myTop = -1;
int index = -1;
int next = -1;
int tt[25][2];
void construct()
{
tt[25][2];
}
void empty()
{
if (myTop == -1)
cout << "Empty Stack";
else
cout << "Full Stack";
}
void push(int x)
{
if (myTop < 24)
{
myTop++;
tt[myTop] = x;
}
else
cout << "The stack is full.";
}
void top()
{
if (myTop != -1)
cout << "Top Value is: " << tt[myTop];
else
cout << "Empty Stack";
}
int pop()
{
int x;
if(myTop<=0)
{
cout<<"stack is empty"<<endl;
return 0;
}
else
{
x=tt[myTop];
myTop--;
}
return(x);
}
void display()
{
for (int row=0; row<25; row++)
{
for (int column=0; column<3; column++)
{
cout << tt[row][column] << "\t";
if (column == 2)
cout << endl;
}
}
cout << endl;
}
int main()
{
push(rand() % 25);
display();
push(rand() % 25);
display();
push(rand() % 25);
display();
push(rand() % 25);
display();
top();
pop();
display();
top();
pop();
display();
top();
pop();
display();
}

You haven`t initialized the random number generator (this is called "seeding").
Add the following to your code.
#include <time.h>
srand (time(0));
And on another note, I prefer using ctime and cstdlib as those are c++ headers (although this can be debated). Also, look into the random header if you have access to an up-to-date compiler.

Rand():
http://www.cplusplus.com/reference/clibrary/cstdlib/rand/
Srand():
http://www.cplusplus.com/reference/clibrary/cstdlib/srand/

Here is how to use random numbers in C++
#include <cstdlib>
#include <ctime>
int main ()
{
srand(time(NULL));
number = rand() % 10 + 1; # Random number between 1 and 10
}

Related

Tried making a hash table, can't map all keys, also program crashes

I have to make a program with a hash table that maps single random characters into the table. The program kind of works but sometimes it crashes, also it doesn't map every element. Some of them just won't get inside the table and there are always spare spaces in the table. I don't know what to do to solve these 2 problems. I used 3 versions of open adressing and each of them causes the same 2 problems. Sorry for my bad English. Thank you in advance.
Edited. Of course, I forgot about dynamic allocation. But the problem isn't solved.
#include <time.h>
#include <string>
#include <cstdlib>
using namespace std;
int Liniowo(int i, int proby, int rozmiar) // (open adressing, Linear probing)
{
if(i+proby<rozmiar)
return i+proby;
else
{
return -1;
}
}
int Kwadratowo(int i, int proby, int rozmiar) // (open adressing, Quadratic probing)
{
if (i+proby*proby<rozmiar)
return i+proby*proby;
else
{
return -1;
}
}
int Podwojnie(int i, int proby, int rozmiar, char klucz) // (open adressing, Double hashing)
{
if (i*(klucz*(701%klucz)-klucz%13)<rozmiar&&i*(klucz*(701%klucz)-klucz%13)>0)
return i*(klucz*(701%klucz)-klucz%13);
else
{
return -1;
}
}
int modularnie(char c,int rozmiar) // modular
{
return c%rozmiar;
}
void dodaj(char *tab,int max, char c) // add an element
{
int i=modularnie(c, max);
if (tab[i]== '\0')
tab[i]=c;
else
{
int u=0;
int h;
while (tab[i]!= '\0'&&h!=-1)
{
u++;
// h=Kwadratowo(i, u, max);
h=Podwojnie(i,u,max,c);
}
if (h!=-1)
tab[h]=c;
else
cout << "no niestety, nie udalo sie wstawic " <<endl; //"I couldn't map the element"
}
}
int wyszukaj(char *tab,int max, char c) // search an element
{
int i=modularnie(c, max);
int j=i;
if (tab[i]== '\0')
return -1;
while (tab[i]==c)
{
i=(i+1)%max;
if((i==j)||(tab[i]== '\0'))
return -1;
}
return i;
}
int usun(char *tab,int max, char c) // remove an element
{
int r,j,i=wyszukaj(tab,max,c);
j=i;
if (i==-1)
return -1;
tab[i]= '\0';
while (tab[(++i)%max]!= '\0')
{
i%=max;
r=modularnie(tab[i],max);
if (((i<r)&&(r<=j)) || ((r<=j)&&(j<i)) || ((j<i)&&(i<r)))
{
tab[j]=tab[i];
tab[i]= '\0';
j=i;
continue;
}
}
return 0;
}
int main()
{
srand( time( NULL ) );
int ile;
cout << "podaj wielkosc tablicy: "; //"Type the size of the table"
cin >> ile;
char* tab; // EDITED
tab=new char(ile);
for (int n=0; n<ile; n++)
{
tab[n]= '\0';
}
char e;
for (int i=0; i<ile; i++)
{
e='!'+rand()%127;
dodaj(tab, ile, e);
}
for(int j=0; j<ile; j++)
{
cout << j << ", " << tab[j] << endl;
}
return 0;
}

How to initialize the dynamic array of struct in the constructor?

This is a Stack class based on a dynamic array of struct for Depth First Search (DFS). The program is not able to run whenever it encounters the function, push(), which shows that the array is not successfully initialized in the constructor.
I have tried to look for the error and even changing the dynamic array of struct into parallel arrays but it still does not work. I apologize if the problem seems to be too simple to be solved as I do not have a strong foundation in C++.
#include <iostream>
#include <iomanip>
#ifndef HEADER_H
#define HEADER_H
using namespace std;
struct Value
{
int row; // row number of position
int col; // column number of position
//operator int() const { return row; }
};
class ArrayStack
{
public:
int top;
Value* array;
ArrayStack();
bool isEmpty();
bool isFull();
void push(int r, int c);
void pop();
int poprowvalue(int value);
int popcolvalue(int value);
int peekrow(int pos);
int peekcol(int pos);
int count();
void change(int pos, int value1, int value2);
void display();
void resize();
private:
int size;
};
ArrayStack::ArrayStack()
{
//Initialize all variablies
top = -1;
size = 10;
Value * array = new Value[size];
for (int i = 0; i < size; i++)
{
array[i].row = 0;
array[i].col = 0;
}
}
bool ArrayStack::isEmpty()
{
if (top == -1)
return true;
else
return false;
}
bool ArrayStack::isFull()
{
if (top == size - 1)
return true;
else
return false;
}
void ArrayStack::resize()
{
if (isFull())
size *= 2;
else if (top == size / 4)
size /= 2;
}
void ArrayStack::push(int r, int c)
{
if (isEmpty() == false)
resize();
array[top + 1].row = r;
array[top + 1].col = c;
top++;
}
void ArrayStack::pop()
{
int value;
if (isEmpty())
{
cout << "Stack underflow" << endl;
}
else
{
poprowvalue(array[top].row);
popcolvalue(array[top].col);
array[top].row = 0;
array[top].col = 0;
top--;
}
}
int ArrayStack::poprowvalue(int v)
{
return v;
}
int ArrayStack::popcolvalue(int v)
{
return v;
}
int ArrayStack::peekrow(int pos)
{
if (isEmpty())
cout << "Stack underflow" << endl;
else
return array[pos].row;
}
int ArrayStack::peekcol(int pos)
{
if (isEmpty())
cout << "Stack underflow" << endl;
else
return array[pos].col;
}
int ArrayStack::count()
{
return (top + 1);
}
void ArrayStack::change(int pos, int value1, int value2)
{
if (isEmpty())
cout << "Stack underflow" << endl;
else
{
array[pos].row = value1;
array[pos].col = value2;
}
}
void ArrayStack::display()
{
for (int i = size - 1; i > -1; i--)
{
cout << array[i].row << " " << array[i].col << endl;
}
}
#endif
I expect it to run well but an exception is always thrown on line 80, which is as follows:
Exception thrown at 0x00007FF6A160487C in Assignment1.exe: 0xC0000005: Access violation writing location 0x0000000000000000.
The problem is this line right here:
Value * array = new Value[size];
This declares a new array variable. You are allocating that array instead, and not your member variable array.
The answer is simple, just change it to this instead:
array = new Value[size];

C++ implementation of stack using array

I have studied the algorithm from Introduction to Algorithm and then
I have written this code. But in my output another value is showing for index 0. and when I use pop function it display 1 instead of 3
#include <iostream>
int top;
void initialise_top(){
top = -1;
}
bool stack_empty(int a[]){
if(top == -1)
return true;
else
return false;
}
void push(int a[], int x, int s){
if(top < s - 1){
top = top + 1;
a[top] = x;
}
else
std::cout << "overflow" << "\n";
}
int pop(int a[]){
if (stack_empty(a) == true)
std::cout << "Underflow" << "\n";
else{
--top;
return a[top+1];
}
}
void display(int a[]){
for(int i = 0;i <= top; i++){
std::cout << a[i] << " ";
}
}
int main()
{
int arr[7];
push(arr,15,7);
push(arr,6,7);
push(arr,2,7);
push(arr,9,7);
push(arr,17,7);
push(arr,3,7);
display(arr);
std::cout << "\n";
int out = pop(arr);
std::cout << pop << "\n";
return 0;
}
Here is the snapshot of the output
enter image description here
In your implementatiton you have "initialise_top()" function.
void initialise_top(){
top=-1;
}
But you don't call it in main function. If you don't call it you can't initialize "top" variable and "top" variable will hold garbage value.
You can read details in here :
Default variable value
And also in theese lines you have some mistakes:
int out=pop(arr);
std::cout<<pop<<"\n";
you must print "out" variable :
std::cout << out << "\n";
You can look to corrected code for your implementation in here :
https://repl.it/JaOd/0
I have this stack array code in C. You can use it as your guide in implementing it to C++.
#include <stdio.h>
#include <stdlib.h>
void push(void);
void pop(void);
int a[5];
int top = -1;
int counter = 0;
int choice;
main() {
do{
printf("*********************************************\nSTACK\nPress the
corresponding button you desire.\n\nPress 1 to push a number to
stack.\nPress 2 to display the current stack.\nPress 3 to pop the current
stack.\nPress 0 to exit.\n\n");
scanf("%d", &choice);
if(choice == 0){
choice = 0;
}
else if(choice == 1){
push();
}
else if(choice == 2){
int i;
printf("Current Stack:\n");
for(i = 0;i <= 4;i++){
printf("%d", a[i]);
}
printf("\n\n");
}
else if(choice == 3){
pop();
}
}while(choice != 0);
}
void push(){
if(top <= 3){
int input;
printf("Enter number to push: ");
scanf("%d", &input);
top = top + 1;
a[top] = input;
int i;
printf("Current Stack:\n");
for(i = 0;i <= 4;i++){
printf("%d", a[i]);
}
printf("\n\n");
}else{
printf("Out of Bounds\n\n");
exit(0);
}
}
void pop(){
if(top >= 0){
printf("You just popped: ");
printf("%d \n\n", a[top]);
a[top] = 0;
printf("Current Stack:\n");
int i;
for(i = 0;i <= 4;i++){
printf("%d", a[i]);
}
printf("\n\n");
top = top - 1;
}else{
printf("Out of Bounds\n\n");
exit(0);
}
}
#include <iostream>
int top;
void initialise_top(){
top=-1;}
bool stack_empty(int a[]){
if(top==-1)
return true;
else
return false;
}
void push(int a[],int x,int s){
if(top<s-1){
top=top+1;
a[top]=x;
}
else
std::cout<<"overflow"<<"\n";
}
int pop(int a[]){
if (stack_empty(a)==true)
std::cout<<"Underflow"<<"\n";
else{
--top;
return a[top+1];
}
}
void display(int a[]){
for(int i=0;i<=top;i++){
std::cout<<a[i]<<" ";
}
}
int main()
{
**initialise_top();**//this statement initialises top=-1
int arr[7];
//std::cout<<stack_empty(arr)<<"\n";
push(arr,15,7);
push(arr,6,7);
push(arr,2,7);
push(arr,9,7);
push(arr,17,7);
push(arr,3,7);
display(arr);
std::cout<<"\n";
int out=pop(arr);
std::cout<<**out**<<"\n";
return 0;
}
1.In your program the value of top=1 when the first element 15 is inserted. due
to this another value is shown for index 0.
So to have top=0, call the function initialise_top(); in main function.
2.To display 3 instead of 1 use
std::cout<<out<<"\n";
Modifications in the program are bold.
I have tried to improve my code. Please tell me if can improve.
#include <iostream>
#define max 1000
class Stack{
int top;
public:
int a[max];
Stack(){
top=-1;
}
bool stack_empty();
void push(int x);
int pop();
void display();
};
bool Stack::stack_empty(){
if(top==-1)
return true;
else
return false;
}
void Stack::push(int x){
int s=max-1;
if(top<s){
top=top+1;
a[top]=x;
}
else
std::cout<<"overflow"<<"\n";
}
int Stack::pop(){
if (stack_empty()==true)
std::cout<<"Underflow"<<"\n";
else{
--top;
return a[top+1];
}
}
void Stack::display(){
for(int i=0;i<=top;i++){
std::cout<<a[i]<<" ";
}
}
int main()
{
Stack stack1;
stack1.push(15);
stack1.push(6);
stack1.push(2);
stack1.push(9);
stack1.push(3);
stack1.display();
std::cout<<"\n";
std::cout<<stack1.pop()<<"\n";
stack1.display();
return 0;
}

C++ Creating Lottery Guessing Program

Okay so the project is to create a lottery number composed of 10 random positive integers and the user is suppose to guess it until the user guesses the correct number. All of my code looks good but when I run the program and enter in a number it gives me this MSVS Runtime Library error? I dont even know what it means as I am fairly new to programming. Help would be very appreciated!
Main.cpp
#include <iostream>
#include <cmath>
#include <ctime>
#include "Lottery.h"
using namespace std;
int main() {
const int size = 9; //declare variables
int win[size];
int g;
srand(time(NULL));
assign(win, size);
draw(win, size);
g = entry();
if (check(win,size,g) == true) {
cout << "Congradulations! You have won the lottery!" << endl;
}
else {
cout << "Try again!" << endl;
}
printOut(g);
}
Lottery.cpp
#include <iostream>
#include <cmath>
#include "Lottery.h"
using namespace std;
int entry() {
int guess;
cout << "Enter a number from 0 to 99." << endl;
cin >> guess;
return guess;
}
void assign(int w[], int s) {
for (int i = 0; i < s; i++) {
w[s] = -1;
}
}
bool check(int w[], int s, int g) {
for (int i = 0; i < s; i++) {
if (g == w[i]) {
return true;
}
}
return false;
}
void draw(int w[], int s) {
for (int i = 0; i < s; i++) {
int tmp = rand() % 100;
if (check(w, s, tmp)) {
i--;
}
else
w[i] = tmp;
}
}
void printOut(int g) {
cout << "Numbers you have chosen:" << " " << g << endl;
}
Lottery.h
#ifndef LOTTERY_INCLUDED
#define LOTTERY_INCLUDED
void assign(int[], int);
bool check(int[], int, int);
void draw(int[], int);
int entry();
void printOut(int);
#endif //LOTTERY
Debugging tutorials are available elsewhere. But if something bad happens, don't panic and look for instructions.
First, your runtime error:
This has a link "Break and open exception settings" link or a "Break" button. Break which will take you to the end of main if you click it.
The details say we did something bad near win.
Look at this:
void assign(int w[], int s) {
for (int i = 0; i < s; i++) {
w[s] = -1; //<------Oh oops!
}
}
We know the length of the array is s i.e. 9, and are using w[s] where we clearly meant w[i].
The extra details in the error are telling you a possible place to look.

Trouble with Array Lists And Using the Insert and Retrieve Functions Given (Segment Core Dump)

I am having difficuly implementing a few functions in my array list.
I want to use the predefined function "insert" to insert a value into the list. I then want to use the retrieve function to print out the values of the entire list.
However, when I test my function, the program exits with a segmentation core dump after the last value is inserted
Any help would be appreciated.
Header:
/** #file ListA.h */
#include <string>
using namespace std;
const int MAX_LIST = 0;
typedef string ListItemType;
class List
{
public:
List();
bool isEmpty() const;
int getLength() const;
void insert(int index, const ListItemType& newItem, bool& success);
void retrieve(int index, ListItemType& dataItem, bool & success) const;
void remove(int index, bool& success);
List selectionSort(List selectList);
private:
ListItemType items[];
int size;
int translate(int index) const;
};
Implementation:
/** #file ListA.cpp */
#include "ArrayList.h" // header file
#include <iostream>
#include <fstream>
List::List() : size()
{
}
bool List::isEmpty() const
{
return size == 0;
}
int List::getLength() const
{
return size;
}
void List::insert(int index, const ListItemType& newItem, bool& success)
{
success = (index >= 1) &&
(index <= size + 1) &&
(size < MAX_LIST);
if (success)
{
for (int pos = size; pos >= index; --pos)
items[translate(pos + 1)] = items[translate(pos)];
items[translate(index)] = newItem;
++size;
}
}
void List::remove(int index, bool& success)
{
success = (index >= 1) && (index <= size);
if (success)
{
for (int fromPosition = index + 1;
fromPosition <= size;
++fromPosition)
items[translate(fromPosition - 1)] = items[translate(fromPosition)];
--size; // decrease the size of the list by one
} // end if
} // end remove
void List::retrieve(int index, ListItemType& dataItem,
bool& success) const
{
success = (index >= 1) && (index <= size);
if (success)
dataItem = items[translate(index)];
}
int List::translate(int index) const
{
return index - 1;
}
List List::selectionSort(List selectList)
{
return selectList;
}
int main()
{
ListItemType insertType = "listItem1";
ListItemType retrieveType = "listitem2";
int numberofitems;
cout << "Please enter the number of data items:" << endl;
cin >> numberofitems;
cout << endl;
cout << "Please enter the data items, one per line:" << endl;
int listofitems[numberofitems];
List myArrayList;
cout << myArrayList.getLength() << endl;
if (myArrayList.isEmpty()) // tests before
{
cout << "This list is empty \n" << endl;
}
else
{
cout << "List is not empty! \n"<< endl;
}
bool mainsucc = true;
for (int i = 0; i<numberofitems; i++)
{
cout << "Enter number " << i + 1 << " : " << endl;
cin >> listofitems[i];
}
for (int i =0; i <numberofitems; i++){
myArrayList.insert(listofitems[i], insertType, mainsucc);}
cout << "Size of the list is : " << myArrayList.getLength() << endl;
/*for (int i=0; i<mainarraylistsize; i++)
{
cout << myArrayList.retrieve(listofitems[i], retrieveType, mainsucc);
}*/
if (myArrayList.isEmpty()) // tests after
{
cout << "This list is empty \n" << endl;
}
else
{
cout << "List is not empty! \n"<< endl;
}
return 1;
}
have MAX_LIST == 0 means that success will always be false in your insert function.