best fit algorithm inplementation in overloaded new operator - c++

I'm practising on how to implement the best fit algorithm by overloading the operator new.
#include<iostream>
#include<malloc.h>
using namespace std;
#define SUCCESS 0
#define FAILURE -1
#define MAX_PARTITION_SIZE 1000
int *avail_space,*needed_space,*used_space,*done_space,*free_space;
int index,j,k,partitions,nop,flag,total_avail;
int *ptr[10];
int no_obj;
class memory{
private:
public:
void set_data();
void create_mem();
int create_partitions();
int alloc_space();
int showdata();
int bestfit_search(int* index);
void* operator new(size_t size);
void operator delete(void* p);
};
void* memory :: operator new(size_t size){
void* p;
int index_no;
memory obj;
int i = 0;
cout << "In Overloaded new" << endl;
cout << "Size : - " << size << endl;
for(i = 0; i < no_obj; i++){
cout << "address :" << ptr[i] << endl;
}
cout << "Size : " << sizeof(memory) << endl;
needed_space[index] = sizeof(memory);
obj.bestfit_search(&index_no); // I guess the problem is in this function where I need to call a non-static member function.
cout << "Index_no - " << index_no << endl;
return ptr[index_no];
}
void memory :: operator delete(void* p){
cout << "In Overloaded delete" << endl;
free(p);
}
void memory :: set_data(){
total_avail = MAX_PARTITION_SIZE;
index = partitions = nop = flag = j = k = 0;
}
void memory :: create_mem(){
memory* obj[10];
int index;
cout << "Enter the no of objects : " << endl;
cin >> no_obj;
for(index = 0; index < no_obj; index++){
cout << "Creating obj : - " << index << endl;
obj[index] = new memory();
}
}
/* Allocate memory to all the pointer variables based on the no of partitions */
int memory :: alloc_space(){
avail_space = new int[partitions];
needed_space = new int[partitions];
used_space = new int[partitions];
done_space = new int[partitions];
free_space = new int[partitions];
if((NULL == avail_space) || (NULL == needed_space) || (NULL == used_space) || (NULL == done_space) || (NULL == free_space)){
return FAILURE;
}
return SUCCESS;
}
/* Get the no of partitions and the space needed for each of the partition */
int memory :: create_partitions(){
cout << "Enter the No of partitions to be created : " << endl;
cin >> partitions;
cout << endl;
/* allocate the space for the pointers */
if(FAILURE == alloc_space()){
return FAILURE;
}
/* Get the size of each partition and update the freespace*/
cout << "Enter the space for each of the partitions : " << endl;
for(index = 0; index < partitions; index++){
cout << "Partition : " << index << "\t";
cin >> avail_space[index];
free_space[index] = avail_space[index];
ptr[index] =(int*)malloc(avail_space[index]);
if(ptr[index] == NULL){
cout << "Memory allocation failed!" << endl;
return FAILURE;
}
cout << "ptr : [" << index << "] - " << ptr[index] << endl;
}
cout << endl;
return SUCCESS;
}
/* Display the available, used and free space*/
int memory :: showdata(){
cout << "Available space "<< "Used space "<<"Free space " <<"Done space "<<endl;
for(index = 0; index < partitions; index++){
cout << avail_space[index]<<"\t\t"<<used_space[index]<<"\t\t"<<free_space[index]<<"\t\t"<<done_space[index]<<endl;
}
return SUCCESS;
}
/* Algorithm to search for the best fit memory */
int memory :: bestfit_search(int* index_no){
if(NULL == index_no){
cout << "Invalid parameter!" << endl;
return FAILURE;
}
int space = 0;
for(index = 0; index < nop; index++){
space = needed_space[index];
flag = 0;
for(k = space; k < MAX_PARTITION_SIZE; k++){ // MAX_PARTITION_SIZE - 1000
for(j = 0; j < partitions; j++){
if((space == avail_space[j]) && (done_space[j] != 1) && (flag != 1)){
used_space[j] = needed_space[index];
free_space[j] = avail_space[j] - needed_space[index];
done_space[j] = 1;
cout << "Used space" <<used_space[j] << " freespace" << free_space[index] <<"done space " << done_space[index] <<endl;
flag = 1;
*index_no = j;
break;
}
}
if(flag == 1){
break;
}
space++;
}
}
showdata();
return SUCCESS;
}
/* Main */
int main(){
memory obj;
obj.set_data();
obj.create_partitions();
obj.create_mem();
return SUCCESS;
}
Program run:
Enter the No of partitions to be created :
5
Enter the space for each of the partitions :
Partition : 0 2
ptr : [0] - 0x9e62080
Partition : 1 7
ptr : [1] - 0x9e62090
Partition : 2 3
ptr : [2] - 0x9e620a0
Partition : 3 10
ptr : [3] - 0x9e620b0
Partition : 4 25
ptr : [4] - 0x9e620c0
Enter the no of objects :
2
Creating obj :
In Overloaded new
Size : 1
address :0x9e62080
address :0x9e62090
Size : 1
Available space Used space Free space Done space
2 0 2 0
7 0 7 0
3 0 3 0
10 0 10 0
25 0 25 0
Index_no - 0
Creating obj :
In Overloaded new
Size : 1
address :0x9e62080
address :0x9e62090
Size : 1
Available space Used space Free space Done space
2 0 2 0
7 0 7 0
3 0 3 0
10 0 10 0
25 0 25 0
Index_no - 1
I'm getting an wrong output as the available space 2 and 3 has to be occupied with used space as 1.

Related

Bubble Sort Function not working (getting garbage value for one index of the array) in C++

following is my code.. I have implemented Process class and taking in input in an array of Process objects.
Then, in my Priority_Scheduling Class, I am calling a sorting function for Priority sort that sorts the array according to the value of priority of all the Process objects...
Interestingly, I am getting garbage value for obj[3] but for all other indexes (1 - 4), it gives a valid value. Due to this garbage value, priority sort performs an abnormal sorting and code doesn't work. Can anyone help identify the error, please?
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
class Process;
class Priority_Scheduling;
struct node
{
int data;
node* next;
};
struct Process_Type // To store average times for all the processes.
{
string process_name;
float avg_turnaround_time;
float avg_waiting_time;
};
class Queue
{
node* front;
node* rear;
public:
Queue();
bool isEmpty();
void dequeue();
void enqueue(int &);
int peek();
};
class Process
{
int id;
static int count; // Count will maintain the record of total processes created.
int burst_time;
int stored_burst_time; // To keep the original value of burst time intact.
int arrival_time;
int completion_time;
int turnaround_time;
int waiting_time;
int priority;
bool has_finished; // To check whether process has finished execution or not
public:
friend class Priority_Scheduling;
Process() :id(count) { completion_time = turnaround_time = waiting_time = 0; count++; has_finished = false; priority = 0; }
// Every process will have a unique Process ID as assigned by count...
void input();
// Set and Get Functions.
int get_t() { return turnaround_time; }
int get_w() { return waiting_time; }
int getid() { return id; }
int get_bt() { return burst_time; }
int get_ct() { return completion_time; }
int get_at() { return arrival_time; }
int get_sbt() { return stored_burst_time; }
void set_bt(int &a) { burst_time = a; }
void set_at(int &a) { arrival_time = a; }
void set_ct(int &a) { completion_time = a; }
void set_t(int &a) { turnaround_time = a; }
void set_w(int &a) { waiting_time = a; }
bool get_finished() { return has_finished; }
void set_finished(bool a) { has_finished = a; }
int get_priority() { return priority; }
void Display();
void Display_Before();
Process(const Process &);
};
class Priority_Scheduling
{
int total_time;
public:
void sort();
bool check();
void priority_sort();
void Calculate(Queue &);
void algorithm();
};
int Process::count = 0;
int time_slice, num;
Process_Type p_type[4];
Process *obj = NULL;
Queue Ready_Queue[4];
void input();
int main()
{
input();
Priority_Scheduling sjf;
cout << endl << endl << setw(15) << "Process ID" << setw(15) << "Arrival Time" << setw(15) << "Burst Time" << setw(15) << "Priority" << endl
<< "------------------------------------------------------------------" << endl;
for (int i = 0; i < num; i++)
obj[i].Display_Before();
sjf.algorithm();
// Round Robin Algorithm is used as a driver algorithm for the implementation of question.
// Printing Before Calculation
// Printing After Calculation
cout << endl << endl << setw(15) << "Process ID" << setw(15) << "Arrival Time" << setw(15) << "Burst Time" << setw(15) << "Turnaround" << setw(15) << "Waiting Time" << endl
<< "------------------------------------------------------------------" << endl;
for (int i = 1; i < num; ++i)
{
for (int j = 0; j < num - i; ++j)
if (obj[j].getid() > obj[j + 1].getid())
swap(obj[j], obj[j + 1]);
}
for (int i = 0; i < num; i++)
obj[i].Display();
cout << endl << endl;
cout << endl;
system("pause");
return 0;
}
void input()
{
do
{
cout << "Enter Number of Processes: ";
cin >> num;
} while (num < 1);
obj = new Process[num];
for (int i = 0; i < num; i++)
obj[i].input();
}
void Process::Display()
{
cout << setw(15) << id << setw(15) << arrival_time << setw(15) << stored_burst_time << setw(15) << turnaround_time << setw(15) << waiting_time;
cout << endl;
}
void Process::Display_Before()
{
cout << setw(15) << id << setw(15) << arrival_time << setw(15) << stored_burst_time << setw(15) << priority << endl;
}
void Process::input()
{
cout << "Process: " << id << endl
<< "Enter Arrival Time: "; cin >> arrival_time;
cout << "Enter Burst Time: "; cin >> burst_time;
stored_burst_time = burst_time;
cout << "Enter Priority: "; cin >> priority;
}
// --------------------Priority CLASS ------------------------------------
void Priority_Scheduling::sort()
{
int j;
for (int i = 1; i < num; ++i)
{
for (j = 0; j < num - i; ++j)
if (obj[j].get_at() > obj[j + 1].get_at())
swap(obj[j], obj[j + 1]);
}
}
void Priority_Scheduling::priority_sort()
{
cout << "Enter" << endl; // Checking if the program has entered or not.
int j;
for (int i = 1; i < num; ++i)
{
for (j = 0; j < num - 1; ++j)
{
cout << "j: " << j << " obj[j].p: " << obj[j].priority << endl
<< "j+1: " << j << " obj[j+1].p: " << obj[j + 1].priority << endl; // Printing out values of j and j+1
if (obj[j].priority > obj[j + 1].priority)
swap(obj[j], obj[j + 1]);
}
}
}
bool Priority_Scheduling::check()
{
for (int i = 0; i < num; i++)
if (obj[i].get_finished() == false)
return false;
return true;
}
void Priority_Scheduling::algorithm()
{
for (int i = 0; i < num; i++)
cout << obj[i].getid() << " "; // PRINTING OUT IDS OF ALL PROCESSES AS TEST
total_time = 0;
cout << endl;
sort();
priority_sort();
for (int i = 0; i < num; i++)
cout << obj[i].priority << " "; // Printing out values of Priority of all processes after sorting. This gives garbage values
while (!check())
{
for (int i = 0; i < num; i++)
{
if (obj[i].get_at() <= total_time) // Initially, only those processes are inserted whose arrival time is zero.
if (obj[i].get_finished() == false)
Ready_Queue[2].enqueue(i); // Inserting Process IDs into the Queue for Priority_Scheduling
}
if (!(Ready_Queue[2].isEmpty()))
Calculate(Ready_Queue[2]);
}
for (int i = 0; i < num; i++)
{
p_type[2].avg_turnaround_time += obj[i].get_t();
p_type[2].avg_waiting_time += obj[i].get_w();
}
p_type[2].avg_turnaround_time = p_type[2].avg_turnaround_time / num;
p_type[2].avg_waiting_time = p_type[2].avg_waiting_time / num;
cout << "Average Turnaround Time: " << p_type[2].avg_turnaround_time << endl
<< "Average Waiting Time: " << p_type[2].avg_waiting_time << endl;
}
void Priority_Scheduling::Calculate(Queue &Ready_Queue)
{
int temp = Ready_Queue.peek();
Ready_Queue.dequeue();
int b = total_time + obj[temp].get_sbt();
obj[temp].set_ct(b);
total_time += obj[temp].get_sbt();
b = obj[temp].get_ct() - obj[temp].get_at();
obj[temp].set_t(b);
b = obj[temp].get_t() - obj[temp].get_sbt();
obj[temp].set_w(b);
obj[temp].set_finished(true);
while (!(Ready_Queue.isEmpty()))
Ready_Queue.dequeue();
}
// ------------------- QUEUE CLASS IMPLEMENTATION ---------------------------
Queue::Queue() { front = NULL; rear = NULL; }
bool Queue::isEmpty()
{
if (!front)
return true;
return false;
}
int Queue::peek() { return front->data; }
void Queue::enqueue(int &d)
{
node* temp = new node;
temp->data = d;
temp->next = NULL;
if (isEmpty())
{
front = temp;
rear = temp;
return;
}
rear->next = temp;
rear = temp;
}
void Queue::dequeue()
{
if (isEmpty())
{
cout << "Nothing to delete";
return;
}
node* temp = front;
front = front->next;
free(temp);
}
Process::Process(const Process &Process_obj)
{
this->arrival_time = Process_obj.arrival_time;
this->burst_time = Process_obj.burst_time;
this->completion_time = Process_obj.completion_time;
this->id = Process_obj.id;
this->stored_burst_time = Process_obj.stored_burst_time;
this->turnaround_time = Process_obj.turnaround_time;
this->waiting_time = Process_obj.waiting_time;
this->has_finished = Process_obj.has_finished;
}
Following is a sample inputs I gave to my code.. and this is what I got,
Enter Number of Processes: 5
Process: 0
Enter Arrival Time: 0
Enter Burst Time: 3
Enter Priority: 3
Process: 1
Enter Arrival Time: 1
Enter Burst Time: 6
Enter Priority: 4
Process: 2
Enter Arrival Time: 3
Enter Burst Time: 1
Enter Priority: 9
Process: 3
Enter Arrival Time: 2
Enter Burst Time: 2
Enter Priority: 7
Process: 4
Enter Arrival Time: 4
Enter Burst Time: 4
Enter Priority: 8
Process ID Arrival Time Burst Time Priority
------------------------------------------------------------------
0 0 3 3
1 1 6 4
2 3 1 9
3 2 2 7
4 4 4 8
0 1 2 3 4 // Process IDs.
Enter // indication than program has entered sorting function
j: 0 obj[j].p: 3 // For obj[0], prioriy value is good
j+1: 0 obj[j+1].p: 4 // for index 1, it's also good
j: 1 obj[j].p: 4 // for index = 1, again good
j+1: 1 obj[j+1].p: 7 // for index = 2, again good
j: 2 obj[j].p: 7 // for index = 2, again good
j+1: 2 obj[j+1].p: -858993460 // NOW HERE IS THE PROBLEM, for INDEX = 3
j: 3 obj[j].p: -858993460
j+1: 3 obj[j+1].p: 8 // Interestingyly, value is good for INDEX = 4 also.
j: 0 obj[j].p: 3
j+1: 0 obj[j+1].p: 4
j: 1 obj[j].p: 4
j+1: 1 obj[j+1].p: -858993460
j: 2 obj[j].p: -858993460
j+1: 2 obj[j+1].p: -858993460
j: 3 obj[j].p: -858993460
j+1: 3 obj[j+1].p: 8
j: 0 obj[j].p: 3
j+1: 0 obj[j+1].p: -858993460
j: 1 obj[j].p: -858993460
j+1: 1 obj[j+1].p: -858993460
j: 2 obj[j].p: -858993460
j+1: 2 obj[j+1].p: -858993460
j: 3 obj[j].p: -858993460 // as a result, all values get garbaged
I have added small notes as where the actual problem is occuring in the output. Please help if you can, thank you.

Trying to figure out what changes I need to make for this code to work correctly. Using Visual Studio

#include <iostream>
using namespace std;
void getMaximumPositive(int* arr, int size, int* max)
{
max = nullptr; //Set default value of max pointer
for (int i = 0; i < size; i++)
{
if (arr[i] > 0) //Only positive numbers are considered while locating the maximum
{
if (max == nullptr)
max = &arr[i];
else if (arr[i] > * max)
max = &arr[i];
}
}
}
void getMaximumNegative(int* arr, int size, int* max)
{
max = nullptr; //Set default value of max pointer
for (int i = 0; i < size; i++)
{
if (arr[i] < 0) //Only negative numbers are considered while locating the maximum
{
if (max == nullptr)
max = &arr[i];
else if (arr[i] > * max)
max = &arr[i];
}
}
}
void printArrayForwards(int* arr, int size)
{
cout << "Array contents (Forwards): " << endl;
for (int i = 0; i < size; i++)
cout << arr[i] << " : ";
cout << endl;
}
void printArrayBackwards(int* arr, int size)
{
cout << "Array contents (Backwards): " << endl;
for (int i = 0; i < size; i++)
cout << *(arr - i - 1) << " : ";
cout << endl;
}
void swapMaxtoFront(int* arr, int* max_address)
{
if (max_address == nullptr)
return; //Do nothing if max_address is null
//Print the addresses and their corresponding values of the first element and the maximum element of the array
cout << endl << "Swapping elements:" << endl;
cout << "Address 1: " << arr << " Value: " << *arr << endl;
cout << "Address 2: " << max_address << " Value: " << *max_address << endl << endl;
//Code for the swap
int temp = *arr;
*arr = *max_address;
*max_address = temp;
max_address = arr;
}
void PrintArray(int* arr, int size)
{
printArrayForwards(arr, size);
printArrayBackwards(arr, size);
}
int main()
{
//Initialize pointers to null
int* array = nullptr; //Do Not Change This Variable Definition
int* max = nullptr; //Do Not Change This Variable Definition
int arr_size;
cout << "Enter the size of your array: ";
cin >> arr_size;
array = new int[arr_size]; //Reserve memory for array of size given by user
cout << "Enter array elements: " << endl;
for (int i = 0; i < arr_size; i++)
{
cout << "Element " << i + 1 << " of " << arr_size << " : ";
cin >> *(array++);
}
PrintArray(array, arr_size);
cout << endl << endl;
cout << "-----------------------------------------------" << endl << "Finding maximum positive number in array..." << endl;
getMaximumPositive(array, arr_size, max); //Max should point to the Maximum positive value in the array
swapMaxtoFront(array, max); //Swap the maximum positive number with the first element of the array
PrintArray(array, arr_size); //Print array with swapped values.
//Print maximum positive number
cout << endl;
if (max == nullptr)
cout << "*******No positive numbers found in array" << endl;
else
cout << "*******Maximum positive number in array: " << *max << endl; //Max should point to the Maximum positive value in the array, which should now be the first element
cout << "-----------------------------------------------" << endl;
cout << endl;
cout << "-----------------------------------------------" << endl << "Finding maximum negative number in array..." << endl;
getMaximumNegative(array, arr_size, max); //Max should point to the Maximum negative value in the array
swapMaxtoFront(array, max); //Swap the maximum negative number with the first element of the array
PrintArray(array, arr_size); //Print array with swapped values.
//Print maximum negative number
cout << endl;
if (max == nullptr)
cout << "*******No negative numbers found in array" << endl;
else
cout << "*******Maximum negative number in array: " << *max << endl; //Max should point to the Maximum negative value in the array, which should now be the first element
cout << "-----------------------------------------------" << endl;
delete[] array;
delete max;
array = nullptr;
max = nullptr;
return 0;
}
Output (That I am trying to look for):
Enter the size of your array: 4
Enter array elements:
Element 1 of 4 : 2
Element 2 of 4 : 8
Element 3 of 4 : 4
Element 4 of 4 : 6
Array contents (Forwards):
2 : 8 : 4 : 6 :
Array contents (Backwards):
6: 4 : 8 : 2
Finding maximum positive number in array...
Swapping elements:
Address 1: 015E10A0 Value: 2
Address 2: 015E10A4 Value: 8
Array contents (Forwards)
8 : 2 : 4 : 6 :
Array contents (Backwards)
6 : 4 : 2 : 8 :
*******Maximum positive number in array: 8
Finding maximum negative number in array...
Array contents (Forwards):
8 : 2 : 4 : 6 :
Array contenes (Backwards):
6: 4 : 2 : 8 :
*******No negative numbers found in array
The biggest problem I noticed was what you do with array:
array = new int[arr_size];
//...
for(size_t i = 0; i < arr_size; i++) {
cin >> *(array++); // here you step array
}
// ... and you use the final pointer "array" everywhere, undefined behaviour. It
// points one element outside of the area you allocated
delete[] array; // the final nail in the coffin,
Fix:
for(int i = 0; i < arr_size; i++) {
cout << "Element " << i + 1 << " of " << arr_size << " : ";
cin >> array[i];
}
With that fixed, this becomes a problem:
void printArrayBackwards(int* arr, int size) {
cout << "Array contents (Backwards): " << endl;
// arr points at the start, so arr - 0 - 1 points before start here:
for(int i = 0; i < size; i++) cout << *(arr - i - 1) << " : ";
cout << endl;
}
Fix:
void printArrayBackwards(int* arr, int size) {
cout << "Array contents (Backwards): " << endl;
for(int i = size - 1; i >= 0; --i) cout << arr[i] << " : ";
cout << endl;
}
Another thing is the getMaximumPositive and getMaximumNegative functions. You don't return a pointer to the max value in max. I changed it to a reference to an int*:
void getMaximumPositive(int* arr, int size, int*& max) {
max = nullptr; // Set default value of max pointer
for(int i = 0; i < size; i++) {
if(arr[i] > 0)
{ // Only positive numbers are considered while locating the maximum
if(max == nullptr)
max = &arr[i];
else if(arr[i] > *max)
max = &arr[i];
}
}
}
void getMaximumNegative(int* arr, int size, int*& max) {
max = nullptr; // Set default value of max pointer
for(int i = 0; i < size; i++) {
if(arr[i] < 0)
{ // Only negative numbers are considered while locating the maximum
if(max == nullptr)
max = &arr[i];
else if(arr[i] > *max)
max = &arr[i];
}
}
}
I also removed the delete max you had. It is a pointer to an int inside the array that you delete with delete[] array. You should not delete that.
Another function where to don't return the value via the parameter is in swapMaxtoFront. I changed that to:
void swapMaxtoFront(int* arr, int*& max_address) {
//...
Full code with your input mocked with
std::istringstream cin{"4 2 8 4 6"};
You passed pointer as parameter.
To receive a pointer, you should pass pointer of pointer.
You can write as this..
void getMaximumPositive(int* arr, int size, int** max) {
...
*max = &arr[ i ];
...
}
...
getMaximumPositive( arr, 10, &max );

Arrange the array of elements 0, 1, and 2 so that the array places all 0 in the first places, then all 1s and 2 as last

I need to Write a C ++ program that prompts the user to enter 10 integers in the array.
Input numbers are: 0, 1 or 2.
The program should extract the array that is entered on the screen Arrange the array of elements 0, 1, and 2 so that the array places all 0 in the first places, then all 1s
and all 2 as the last.
Arranged array displays on the screen.
Have been struggling over this for few hours now. Im stuck and dont know how to show Output .
Input should be for example 0 0 1 0 1 2 2 2 0 1
Output 0000111222
HOW?
int main ()
{
int t [N], i, ;
cout << "Enter 10 arrays from 0-2" << endl;
cout << "Original array:";
for (i = 0; i <N; i ++)
{
cin >> t [i];
}
if (t [i]> = 0 && t [i] <= 2)
{
cout << "Rearranging elements of array:" << ? << endl;
}
cout << "End of the program!"
return 0;
}
when you do
if (t [i]> = 0 && t [i] <= 2)
i equals N so you access out of the array, and of course that does not sort the array
You do not check if cin >> t[i] success so if the user enter something else than an int all the entries from the current will not be set (they will be 0 in case you use a std::vector)
A first way is to do without taking account the range 0..2, replace int t[n] by std::vector<int> t(N) and use sort(t.begin(), t.end()) to sort your array
The complexity is O(N*log(N)) (here N is 10)
For instance :
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
#define N 10
int main ()
{
vector<int> t(N);
size_t i; // size_t the right type for an index
cout << "Enter 10 values in range 0..2" << endl;
for (i = 0; i < N; ++i)
{
for (;;) {
cout << "value #" << i << ':';
if (!(cin >> t[i])) {
cerr << "not a number" << endl;
cin.clear(); // raz error
string s;
cin >> s; // skip bad input
}
else if ((t[i] < 0) || (t[i] > 2))
cerr << "value out of range" << endl;
else
break;
}
}
cout << "Original array:";
for (i = 0; i < N; ++i) cout << ' ' << t[i]; // old way to do
cout << endl;
sort(t.begin(), t.end());
cout << "Sorted array:";
for (auto v : t) cout << ' ' << v; // new way to do
cout << endl;
cout << "End of the program!" << endl;
return 0;
}
Compilation and execution :
pi#raspberrypi:/tmp $ g++ -pedantic -Wextra -Wall s.cc
pi#raspberrypi:/tmp $ ./a.out
Enter 10 values in range 0..2
value #0:aze
not a number
value #0:-2
value out of range
value #0:3
value out of range
value #0:2
value #1:0
value #2:1
value #3:2
value #4:0
value #5:2
value #6:1
value #7:0
value #8:0
value #9:1
Original array: 2 0 1 2 0 2 1 0 0 1
Sorted array: 0 0 0 0 1 1 1 2 2 2
End of the program!
A second way considering a range [min .. max] not too large is to count the number of each value then fill the array to respect these counts
The complexity is O(2N) (here N is 10)
For instance :
#include <vector>
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
#define MIN 0
#define MAX 2
#define N 10
int main ()
{
vector<int> t(N);
size_t i; // size_t the right type for an index
cout << "Enter 10 values in range " << MIN << ".." << MAX << endl;
for (i = 0; i < N; ++i)
{
for (;;) {
cout << "value #" << i << ':';
if (!(cin >> t[i])) {
cerr << "not a number" << endl;
cin.clear(); // raz error
string s;
cin >> s; // skip bad input
}
else if ((t[i] < MIN) || (t[i] > MAX))
cerr << "value out of range" << endl;
else
break;
}
}
cout << "Original array:";
for (auto v : t) cout << ' ' << v;
cout << endl;
// count numbers
vector<size_t> counts(MAX - MIN + 1);
for (auto v : t) counts[v - MIN] += 1;
// fill again
i = 0;
for (int r = MIN; r <= MAX; ++r) {
size_t n = counts[r - MIN];
while (n--) t[i++] = r;
}
cout << "Sorted array:";
for (auto v : t) cout << ' ' << v;
cout << endl;
cout << "End of the program!" << endl;
return 0;
}
Compilation and execution :
pi#raspberrypi:/tmp $ g++ -pedantic -Wextra -Wall s2.cc
pi#raspberrypi:/tmp $ ./a.out
Enter 10 values in range 0..2
value #0:a
not a number
value #0:3
value out of range
value #0:0
value #1:2
value #2:1
value #3:1
value #4:2
value #5:2
value #6:2
value #7:0
value #8:1
value #9:2
Original array: 0 2 1 1 2 2 2 0 1 2
Sorted array: 0 0 1 1 1 2 2 2 2 2
End of the program!
Specifically for values between 0 and 2 (in fact for 3 possible values) as said in a remark by #PaulMcKenzie you can use the Dutch national flag problem and look at that question : R G B element array swap
The complexity is O(N) (here N is 10)
As a beginner, you may want to try this (this is the simplest solution I could think of without using other libraries):
int main () {
const int size = 10;
int arr[size], temp = 0;
for (int i = 0; i < size; i++) {
cin >> arr[i];
}
for (int j = 0; j < size - 1; j++) {
for (int k = 0; k < size - j - 1; k++) {
if(arr[k] > arr[k+1]) {
temp = arr[k];
arr[k] = arr[k+1];
arr[k+1] = temp;
}
else
continue;
}
}
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
return 0;
}
I hope this helps you.
1st answer is too difficult for me, im only beginner not knowing what im doing yet.
2nd answer is to that direction where it should be right but i need to put in that input cant be more than 2 or less than numeber 0, thats the problem now :D
Im sorry, i just cant get to that point where i understand that syntax.

Vertical histograms not working

I have a problem with my histogram program, I am getting it to print out the exact thing that I want it to, however it has some unusual spacing problems and I was wondering if anyone could help me out with how to avoid it.
this is what my output looks like, as you can see it has wrong spacing in all the ones before the 90-100 bracket.
What I want it to look like so there is no space at the bottom between the numbers and the asterisk:
*
*
* *
* *
* *
* *
* *
* *
* * *
* * * *
* * * *
0 1 2 3
also can anyone recommend something to use instead of system("Clear") or system("PAUSE")?
Code:
#include <iostream>
#include <iomanip>
using namespace std;
void readExamMarks(int examMarks[], int sizeOfArray, int& counter1, int& counter2, int& counter3, int& counter4,int& counter5, int& counter6,int& counter7, int& counter8, int& counter9, int& counter10){
cout << "Please enter a set of exam marks to see a histogram for:" << endl;
int x = 0;
for( int idx = 0; idx < sizeOfArray; idx++){
cin >> x;
if((x >=0) && (x <= 100)){
x = x/10;
switch(x){
case 1:
counter1++;
break;
case 2:
counter2++;
break;
case 3:
counter3++;
break;
case 4:
counter4++;
break;
case 5:
counter5++;
break;
case 6:
counter6++;
break;
case 7:
counter7++;
break;
case 8:
counter8++;
break;
case 9:
counter9++;
break;
case 10:
counter9++;
break;
}
examMarks[idx] = x;
}
else{
cout << "ERROR: Value must be in range [0...100], please enter a valid value\n";
}
}
}
void printExamMarksDecade(){
cout << setw(5) << "10-20 " << "21-30 " << "31-40 " <<"41-50 " << "51-60 " << "61-70 " << "71-80 " << "81-90 " << "91-100 ";
}
void printHisto(int examMarks[], int sizeOfArray,int counter1, int counter2, int& counter3, int& counter4,int& counter5, int& counter6,int& counter7, int& counter8, int& counter9, int& counter10){
system("cls");
while(counter1 != 0 ){
cout << setw(3) << "*" << endl;
counter1--;
}
while(counter2 != 0 ){
cout << setw(10) << "*" << endl;
counter2--;
}
while(counter3 != 0 ){
cout << setw(17) << "*" << endl;
counter3--;
}
while(counter4 != 0 ){
cout << setw(24) << "*" << endl;
counter4--;
}
while(counter5 != 0 ){
cout << setw(31) << "*" << endl;
counter5--;
}
while(counter6 != 0 ){
cout << setw(38) << "*" << endl;
counter6--;
}
while(counter7 != 0 ){
cout << setw(45) << "*" << endl;
counter7--;
}
while(counter8 != 0 ){
cout << setw(52) << "*" << endl;
counter8--;
}
while(counter9 != 0 ){
cout << setw(59) << "*" << endl;
counter9--;
}
}
int main()
{
int examMarks[30];
int counter1 = 0;
int counter2 = 0;
int counter3 = 0;
int counter4 = 0;
int counter5 = 0;
int counter6 = 0;
int counter7 = 0;
int counter8 = 0;
int counter9 = 0;
int counter10 = 0;
readExamMarks(examMarks, 30, counter1, counter2, counter3, counter4, counter5, counter6, counter7, counter8, counter9, counter10);
printHisto(examMarks, 30, counter1, counter2, counter3, counter4, counter5, counter6, counter7, counter8, counter9, counter10);
printExamMarksDecade();
system("PAUSE");
}
A variable counter for each range is not really what you want to be doing, you just want one array:
#include <iostream>
using namespace std;
int main() {
// count array for brackets 0 to 10
int *count = new int[11];
// variable to store each mark read
int mark;
// Read in marks
while (cin >> mark) {
// Increment the count for the bracket the mark falls in
count[mark/10]++;
}
for (int i=0;i<11;i++) {
cout << i << "\t| " << string(count[i],'*') << endl;
}
}
This plots a horizontal histograms but shows the much simple way it should be done.
$ ./histogram.out < marks
0 | ******
1 | *********
2 | **********
3 | ************
4 | *********
5 | *****************
6 | ********
7 | *********
8 | ***
9 | ****
10 | *
You will have less headaches modifying this code, try increasing the number of brackets to 1000 in original code!

Handling decimal values in evaluating postfix using stacks in c++

I am new to posting and relatively new to coding in c++.
My question involves:
Handling decimal values in evaluating postfix using stacks in c++. This is a homework assignment, but I have already gotten my code to work for the basic requirement. I am not asking for help with my homework. My professor wants us to brute force the assignment, so I have avoided many shortcuts using special header files such as <stack>.
I have researched the question and was not satisfied with the answers given. No one else seems to have split up their code like mine. I am having an issue passing a value from the inner loop which detects the decimal values to the rest of the main function. The code compiles and runs, but my final result is gibberish. I found a post which states multiple values cannot be passed from a function with 'return', but I do need at least two values returned from the inner decimal function. I do not understand the 'tuple' or 'pair' commands.
I know this is a wordy prelude, but I do want any readers to understand I have read pre-requisite materials and did lost of research. Personally, I hate brute force methods. I understand that a response may not be in time to help with my project, but I have been working on this for weeks. I would like to get the satisfaction of seeing this method work as conceived. Suggestions and pointers are very much welcome.
Here is the link to my code:
link
Here is my code:
//*****************************************************************************
// Postfix expression evaluation
// 11/13/2012
// by DJH
//
// all applicable copyrights apply
//
// this program evaluates an input postfix string
//
// created using Dev-C++ 5.2.0.3
//*****************************************************************************
// ----------------------------------libraries---------------------------------
#include <iostream> // For cin, cout and endl
#include <string>
#include <cctype>
#include <vector>
#include <sstream>
#include <cstdlib>
#include <cmath>
#include <iomanip>
using namespace std;
// ------------------------------ Globals -------------------------------------
string postfix;
// --------------------------- stack class ------------------------------------
class Stack {
public:
enum {MaxStack = 50};
void init() {top = -1;}
void push( double p ) {
if ( isFull() ) {
cerr << "Full Stack. DON'T PUSH\n";
return;
}
else {
arr[ ++top ] = p;
cout << "Just pushed " << p << endl;
return;}
}
int pop() {
if (isEmpty() ) {
cerr << "\tEmpty Stack. Don't Pop\n\n";
return 1;
}
else
return arr[top--];
}
bool isEmpty() {return top < 0 ? 1 : 0;}
bool isFull() {return top >= MaxStack -1 ? top : 0;}
void dump_stack() {
cout << "The Stack contents, from top to bottom, from a stack dump are: " << endl;
for (int s = top; s >= 0; s--)
cout << "\t\t" << arr[s] << endl;
}
private:
int top;
double arr[MaxStack];
} pStack;
// ------------------------------ end stack class -----------------------------
// -----------------------------function prototypes----------------------------
void evalPostfix( string);
double decimalEvaluate( string, int, double);
// ----------------------------------------------------------------------------
// -----------------------------------Main()-----------------------------------
int main() {
cout << "Enter a postfix expression\n\t (without spaces - using '_' for delimiters):\n\t";
cout << "For example: 8_5_3_+_*_2_/_5_+\n" << endl;
getline(cin, postfix);
// postfix = "7_2_*_5_+_2_*";
cout << "You entered: " << postfix << endl;
int c = 0;
while (postfix[c] != '\0') {
// this loop counts the characters in the input string including
// whitespace
++c;
}
cout << "\tThe string length is:\t" << c << endl;
evalPostfix(postfix);
int result = pStack.pop();
cout << "The result of the postfix expression is: " << result << endl;
/*
stack commands:
Stack a_stack; // creates new stack
a_stack.init(); // initializes top element
a_stack.pop(); // pops top of stack
a_stack.push(n); // push element to top of stack
a_stack.dump_stack(); // displays the contents of the stack from top to bottom
*/
return 0;
cin.get();
}
// --------------------------------end of Main()-------------------------------
// ------------------------------functions follow------------------------------
void evalPostfix( string) {
double ch = 0, dc = 0, b = 0, a = 0, d = 0;
double tempDC = 0;
double tempDCD = 0;
char op;
int i = 0, j = 0, k = 0, m = 0, n = 0, q = 0;
while (postfix[i] != '\0') {
if (postfix[i] == '_') {
i++;
} else if (isdigit(postfix[i])) {
ch = postfix[i] - '0'; // for numbers only
j = i + 1;
while (postfix[j] != '_') {
if (isdigit(postfix[j])) {
ch = ch * 10 + (postfix[j] - '0');
k = j + 1;
// this accounts for decimals by skipping the '.' and
// conducting operations on trailing numbers
if (postfix[k] == '.') {
dc = 0;
decimalEvaluate(postfix, k, dc);
dc = tempDC / tempDCD;
d = ch + dc;
k++;
}
j = k - 1;
j++;
}
}
cout << "Post decimal function k: " << k << endl;
cout << "Post decimal function dc: " << setprecision(12) << dc
<< endl;
cout << "Post decimal function d: " << d << endl;
pStack.push(d);
i = j - 1;
i++;
} else if (postfix[i] == '+' || postfix[i] == '-' || postfix[i] == '*'
|| postfix[i] == '/' || postfix[i] == '^') {
b = pStack.pop();
a = pStack.pop();
op = postfix[i]; // for operators only
switch (op) {
case '+':
pStack.push(a + b);
break;
case '-':
pStack.push(a - b);
break;
case '*':
pStack.push(a * b);
break;
case '^':
pStack.push(pow(a, b));
break;
case '/':
if (b == 0) {
cout << "Division by zero not allowed!" << endl;
cin.get();
exit(0);
}
pStack.push(a / b);
default:
cout << "Invalid Operation" << endl;
}
i++;
}
}
}
// ----------------------------------------------------------------------------
double decimalEvaluate(string postfix, int k, double dc) {
dc = 0;
double tempDC = 0;
double tempDCD = 0;
int n = 0, m = 0, lenDC = 0;
n = k;
while (postfix[n] != '_') {
if ((isdigit(postfix[n])) == false) {
n++;
}
cout << "This step (1) n: " << n << endl;
if (isdigit(postfix[n])) {
m = n;
// assumes characters between a '.' and '_' are all digits
// (may need to check)
while (postfix[m] != '_') {
lenDC++;
// this loop counts the digits in the input trailing a decimal
// point
m++;
}
cout << "This step (2) m: " << m << endl;
cout << "This step (2) lenDC: " << lenDC << endl;
while ((postfix[n]) != '_') {
tempDC = tempDC * 10 + (postfix[n]) - '0';
n++;
}
cout << "This step (3) n: " << n << endl;
cout << "This step (3) tempDC: " << tempDC << endl;
}
k = n;
tempDCD = pow(10, lenDC);
dc = tempDC / tempDCD;
cout << "This step (4) k: " << k << endl;
cout << "This step (4) tempDCD: " << tempDCD << endl;
cout << "This step (4) tempDC: " << tempDC << endl;
cout << "This step (4) dc: " << dc << endl;
}
return dc, k, tempDC, tempDCD;
}
Pass the variables by reference:
void decimalEvaluate (string postfix, int& k, double& dc, double& tempDC, double& tempDCD)
{
tempDC = 0.0;
//...
}