passing a double pointer boolean array to a function - c++

I have a double pointer boolean.
I would like to pass this boolean to a function
The code is used for graph theory, to create an adj matrix, check if the graph has cycles or not ...
The problem comes from the cycle function
The function doesn't like the boolean in parameter to check if a graph has a cycle.
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <vector>
#include <algorithm>
using namespace std;
int Cycle(int number_of_vertices ,bool **adj_matrix)
{
bool** adj = new bool*[number_of_vertices];
for(int i=0;i<number_of_vertices;i++)
{
adj[i] = new bool[number_of_vertices];
}
for(int i=0;i<number_of_vertices;i++)
{
for(int j=0;j<number_of_vertices;j++)
{
adj[i][j] = adj_matrix[i+1][j+1];
}
}
for(int k=0;k<number_of_vertices;k++)
{ // transitiv closure
for(int i=0;i<number_of_vertices;i++)
{
for(int j=0;j<number_of_vertices;j++)
{
if(adj[i][k]&&adj[k][j])
{
adj[i][j] = true;
}
}
}
}
int count = 0;
for(int i=0;i<number_of_vertices;i++)
{
if(adj[i][i])
{
count++;
}
}
return count;
}
int main()
{
string first_line, second_line;
int initial_extremity, final_extremity, value, number_of_vertices, nombre_arcs;
ifstream fichier("test.txt");
bool** adj_matrix;
int** val_matrix;
vector<int> vertice_names;
if (fichier.is_open())
{
getline(fichier, first_line);
number_of_vertices = atoi(first_line.c_str());
getline(fichier, second_line);
nombre_arcs = atoi(second_line.c_str());
adj_matrix = new bool*[number_of_vertices];
val_matrix = new int*[number_of_vertices];
for (int i=0; i<number_of_vertices;i++)
{
adj_matrix[i] = new bool[number_of_vertices];
val_matrix[i] = new int[number_of_vertices];
for (int j=0; j<number_of_vertices; j++)
{
adj_matrix[i][j] = false;
val_matrix[i][j] = 0;
}
}
while(fichier >> initial_extremity >> final_extremity >> value)
{
adj_matrix[initial_extremity][final_extremity] = true;
val_matrix[initial_extremity][final_extremity] = value;
int c = Cycle(number_of_vertices, adj_matrix);
printf("number of cycles: %d\n\n", c);
if(c!=0)
{
printf("%d --[%d]--> %d\n",initial_extremity,value,final_extremity);
}
else
{
printf("%d --[%d]--> %d\n",initial_extremity,value,final_extremity);
}
if ( find(vertice_names.begin(), vertice_names.end(), initial_extremity) != vertice_names.end() )
{
//nothing
}
else
{
vertice_names.push_back(initial_extremity);
}
if ( find(vertice_names.begin(), vertice_names.end(), final_extremity) != vertice_names.end() )
{
//nothing
}
else
{
vertice_names.push_back(final_extremity);
}
}
fichier.close();
}
else
{
cout << "error while opening the file" << '\n';
cin.get();
}
printf("%d arcs\n",nombre_arcs);
printf("%d vertices\n\n\n",number_of_vertices);
printf("Adj Matrix \n");
printf(" ");
for(int i = 0; i<number_of_vertices; i++)
{
printf("%3d",vertice_names.at(i));
}
printf("\n");
for (int i = 0; i<number_of_vertices; i++)
{
printf("%3d ", vertice_names.at(i));
for (int j = 0; j <number_of_vertices; j++)
{
printf("%3d",adj_matrix[i][j]);
}
printf("\n");
}
printf("\n\n");
sort(vertice_names.begin(), vertice_names.end(), less<int>());
printf("Adj and value matrix\n");
printf(" ");
for(int i = 0; i<number_of_vertices; i++)
{
printf("%3d",vertice_names.at(i));
}
printf("\n");
for (int i = 0; i<number_of_vertices; i++)
{
printf("%3d ", vertice_names.at(i));
for (int j = 0; j <number_of_vertices; j++)
{
if (adj_matrix[i][j])
{
printf("%3d",val_matrix[i][j]);
}
else
{
printf(" ");
}
}
printf("\n");
}
return 0;
}
format of the .txt file:
first line : number of vertices
second : number of arcs
the other lines : Inital Arc Final Arc Value
3
4
0 1 0
1 0 12
1 2 25
2 0 6
By the way, if someone have a better idea to check if a graph has a cycle let me know
Best regards

Looks to me like you are stepping out of bounds in the Cycle function:
for(int i=0;i<number_of_vertices;i++)
{
for(int j=0;j<number_of_vertices;j++)
{
adj[i][j] = adj_matrix[i+1][j+1]; // i + 1 and j + 1 go out of bounds
}
}
Suppose number_of_vertices is 3. Then the index of the last element is 2. When i = 2, then i + 1 = 3. Out of bounds.

Related

Memory leak without allocating any memory?

I'm working on a coding assignment for a C++ class. When I run my program I seem to be dealing with a memory leakage issue, which is weird since I am NOT explicitly allocating any memory in my code. I ran the program under gdb, and it seems as though the program crashes when running the destructor for a Deck object. I tried stepping through the code, but I when I do so I end up in a host of .h files related to vectors. Then suddenly, it stops. I tried going to a TA for some help, but they seem to be as perplexed as I am on the issue.
# include <stdlib.h>
# include <time.h>
# include <iostream>
# include <vector>
# include <stdio.h>
using namespace std;
//function signatures
float bustProbability (const int);
class Deck
{
public:
//data members
vector <int> cardArray;
vector <int> wasteCards;
//constructor
Deck();
//methods
void shuffleDeck();
void populateDeckWithCards();
void removeCopyCards();
int dealCard();
int remainingCards();
void showCards();
};
void Deck::removeCopyCards() {
for (unsigned int i = 0; i < wasteCards.size(); i++) {
bool removedCopy = false;
for (unsigned int j = 0; j < cardArray.size() && removedCopy == false; j++) {
if (cardArray[j] == wasteCards[i]) {
cardArray.erase (cardArray.begin() + j - 1);
removedCopy = true;
}
}
}
}
int Deck::dealCard() {
if (remainingCards() > 0) {
int tmp = cardArray.back();
wasteCards.push_back(tmp);
cardArray.pop_back();
return tmp;
}
else {
populateDeckWithCards();
removeCopyCards();
shuffleDeck();
//shuffle method
int tmp = cardArray.back();
cardArray.pop_back();
return tmp;
}
}
void Deck::populateDeckWithCards() {
//populate regular cards into array
for (int i = 2; i <= 10; i++) {
for (int j = 0; j < 4; j++) {
cardArray.push_back(i);
}
}
//populate J, Q, K into array
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
cardArray.push_back(10);
}
}
//populating array with Aces... treating them as special case '100'
for (int i = 0; i < 4; i++) {
cardArray.push_back(100);
}
return;
}
void Deck::showCards() {
for (unsigned int i = 0; i < cardArray.size(); i++) {
cout << cardArray[i] << endl;
}
}
Deck::Deck() {
wasteCards.clear();
cardArray.clear();
populateDeckWithCards();
shuffleDeck();
}
void Deck::shuffleDeck() {
int n = cardArray.size();
for(int a = n-1; a > 0; a--) {
int min = 0;
int max = a;
int j = min + rand() / (RAND_MAX / (max-min + 1) + 1);
int tmp = cardArray[a];
cardArray[a] = cardArray[j];
cardArray[j] = tmp;
}
return;
}
int Deck::remainingCards() {
return cardArray.size();
}
class Player {
public:
//data members
vector <int> playerHand;
//constructor
Player();
//methods
bool isBust();
int count();
void hit(Deck&);
void stand();
bool muckHand();
void showHand();
};
Player::Player() {
playerHand.clear();
}
void Player::showHand() {
for (unsigned int i = 0; i < playerHand.size(); i++) {
cout << playerHand[i] << endl;
}
return;
}
int Player::count() {
int handCount = 0;
for (unsigned int i = 0; i < playerHand.size(); i++) {
if (playerHand[i] != 100)
handCount += playerHand[i];
else {
if (playerHand[i] == 100) {
if ((handCount) > 11) {
handCount += 1;
}
else
handCount += 10;
}
}
}
return handCount;
}
bool Player::isBust() {
if (count() > 21)
return true;
else
return false;
}
void Player::hit(Deck& d) {
playerHand.push_back(d.dealCard());
}
void Player::stand() {
return;
}
bool Player::muckHand() {
playerHand.clear();
return true;
}
float bustProbability (const int threshHold) {
int threshHoldReached = 0;
Deck myDeck;
Player myPlayer;
Player dealer;
for (int i = 0; i < 10000; i++) {
myPlayer.hit(myDeck);
dealer.hit(myDeck);
myPlayer.hit(myDeck);
dealer.hit(myDeck);
while (myPlayer.count() < threshHold) {
myPlayer.hit(myDeck);
}
if (!(myPlayer.isBust())) {
++threshHoldReached;
}
myDeck.wasteCards.clear();
myPlayer.muckHand();
dealer.muckHand();
}
float bustFraction = float(threshHoldReached)/float(10000);
return bustFraction;
}
int main () {
cout << "blackjack simulation" << endl;
srand((unsigned int)time(NULL));
cout << bustProbability(19);
return 0;
}
I'm incredibly sorry for just posting my code, but I've spend 4 days on this issue, and I can't even begin to figure out what the problem is.
There is at least the line
cardArray.erase (cardArray.begin() + j - 1);
which seems to be dubious in case of j = 0

c++ - Segmentation fault for class function of vector of custom class

I am using following code to run kmeans algorithm on Iris flower dataset- https://github.com/marcoscastro/kmeans/blob/master/kmeans.cpp
I have modified the above code to read input from files. Below is my code -
#include <iostream>
#include <vector>
#include <math.h>
#include <stdlib.h>
#include <time.h>
#include <algorithm>
#include <fstream>
using namespace std;
class Point
{
private:
int id_point, id_cluster;
vector<double> values;
int total_values;
string name;
public:
Point(int id_point, vector<double>& values, string name = "")
{
this->id_point = id_point;
total_values = values.size();
for(int i = 0; i < total_values; i++)
this->values.push_back(values[i]);
this->name = name;
this->id_cluster = -1;
}
int getID()
{
return id_point;
}
void setCluster(int id_cluster)
{
this->id_cluster = id_cluster;
}
int getCluster()
{
return id_cluster;
}
double getValue(int index)
{
return values[index];
}
int getTotalValues()
{
return total_values;
}
void addValue(double value)
{
values.push_back(value);
}
string getName()
{
return name;
}
};
class Cluster
{
private:
int id_cluster;
vector<double> central_values;
vector<Point> points;
public:
Cluster(int id_cluster, Point point)
{
this->id_cluster = id_cluster;
int total_values = point.getTotalValues();
for(int i = 0; i < total_values; i++)
central_values.push_back(point.getValue(i));
points.push_back(point);
}
void addPoint(Point point)
{
points.push_back(point);
}
bool removePoint(int id_point)
{
int total_points = points.size();
for(int i = 0; i < total_points; i++)
{
if(points[i].getID() == id_point)
{
points.erase(points.begin() + i);
return true;
}
}
return false;
}
double getCentralValue(int index)
{
return central_values[index];
}
void setCentralValue(int index, double value)
{
central_values[index] = value;
}
Point getPoint(int index)
{
return points[index];
}
int getTotalPoints()
{
return points.size();
}
int getID()
{
return id_cluster;
}
};
class KMeans
{
private:
int K; // number of clusters
int total_values, total_points, max_iterations;
vector<Cluster> clusters;
// return ID of nearest center (uses euclidean distance)
int getIDNearestCenter(Point point)
{
double sum = 0.0, min_dist;
int id_cluster_center = 0;
for(int i = 0; i < total_values; i++)
{
sum += pow(clusters[0].getCentralValue(i) -
point.getValue(i), 2.0);
}
min_dist = sqrt(sum);
for(int i = 1; i < K; i++)
{
double dist;
sum = 0.0;
for(int j = 0; j < total_values; j++)
{
sum += pow(clusters[i].getCentralValue(j) -
point.getValue(j), 2.0);
}
dist = sqrt(sum);
if(dist < min_dist)
{
min_dist = dist;
id_cluster_center = i;
}
}
return id_cluster_center;
}
public:
KMeans(int K, int total_points, int total_values, int max_iterations)
{
this->K = K;
this->total_points = total_points;
this->total_values = total_values;
this->max_iterations = max_iterations;
}
void run(vector<Point> & points)
{
if(K > total_points)
return;
vector<int> prohibited_indexes;
printf("Inside run \n");
// choose K distinct values for the centers of the clusters
printf(" K distinct cluster\n");
for(int i = 0; i < K; i++)
{
while(true)
{
int index_point = rand() % total_points;
if(find(prohibited_indexes.begin(), prohibited_indexes.end(),
index_point) == prohibited_indexes.end())
{
printf("i= %d\n",i);
prohibited_indexes.push_back(index_point);
points[index_point].setCluster(i);
Cluster cluster(i, points[index_point]);
clusters.push_back(cluster);
break;
}
}
}
int iter = 1;
printf(" Each point to nearest cluster\n");
while(true)
{
bool done = true;
// associates each point to the nearest center
for(int i = 0; i < total_points; i++)
{
int id_old_cluster = points[i].getCluster();
int id_nearest_center = getIDNearestCenter(points[i]);
if(id_old_cluster != id_nearest_center)
{
if(id_old_cluster != -1)
clusters[id_old_cluster].removePoint(points[i].getID());
points[i].setCluster(id_nearest_center);
clusters[id_nearest_center].addPoint(points[i]);
done = false;
}
}
// recalculating the center of each cluster
for(int i = 0; i < K; i++)
{
for(int j = 0; j < total_values; j++)
{
int total_points_cluster = clusters[i].getTotalPoints();
double sum = 0.0;
if(total_points_cluster > 0)
{
for(int p = 0; p < total_points_cluster; p++)
sum += clusters[i].getPoint(p).getValue(j);
clusters[i].setCentralValue(j, sum / total_points_cluster);
}
}
}
if(done == true || iter >= max_iterations)
{
cout << "Break in iteration " << iter << "\n\n";
break;
}
iter++;
}
// shows elements of clusters
for(int i = 0; i < K; i++)
{
int total_points_cluster = clusters[i].getTotalPoints();
cout << "Cluster " << clusters[i].getID() + 1 << endl;
for(int j = 0; j < total_points_cluster; j++)
{
cout << "Point " << clusters[i].getPoint(j).getID() + 1 << ": ";
for(int p = 0; p < total_values; p++)
cout << clusters[i].getPoint(j).getValue(p) << " ";
string point_name = clusters[i].getPoint(j).getName();
if(point_name != "")
cout << "- " << point_name;
cout << endl;
}
cout << "Cluster values: ";
for(int j = 0; j < total_values; j++)
cout << clusters[i].getCentralValue(j) << " ";
cout << "\n\n";
}
}
};
int main(int argc, char *argv[])
{
srand(time(NULL));
int total_points, total_values, K, max_iterations, has_name;
ifstream inFile("datafile.txt");
if (!inFile) {
cerr << "Unable to open file datafile.txt";
exit(1); // call system to stop
}
inFile >> total_points >> total_values >> K >> max_iterations >> has_name;
cout << "Details- \n";
vector<Point> points;
string point_name,str;
int i=0;
while(inFile.eof())
{
string temp;
vector<double> values;
for(int j = 0; j < total_values; j++)
{
double value;
inFile >> value;
values.push_back(value);
}
if(has_name)
{
inFile >> point_name;
Point p(i, values, point_name);
points.push_back(p);
i++;
}
else
{
inFile >> temp;
Point p(i, values);
points.push_back(p);
i++;
}
}
inFile.close();
KMeans kmeans(K, total_points, total_values, max_iterations);
kmeans.run(points);
return 0;
}
Output of code is -
Details-
15043100000Inside run
K distinct cluster i= 0
Segmentation fault
When I run it in gdb, the error shown is -
Program received signal SIGSEGV, Segmentation fault.
0x0000000000401db6 in Point::setCluster (this=0x540, id_cluster=0)
at kmeans.cpp:41
41 this->id_cluster = id_cluster;
I am stuck at this as I cannot find the cause for this segmentation fault.
My dataset file looks like -
150 4 3 10000 1
5.1,3.5,1.4,0.2,Iris-setosa
4.9,3.0,1.4,0.2,Iris-setosa
4.7,3.2,1.3,0.2,Iris-setosa
. . .
7.0,3.2,4.7,1.4,Iris-versicolor
6.4,3.2,4.5,1.5,Iris-versicolor
6.9,3.1,4.9,1.5,Iris-versicolor
5.5,2.3,4.0,1.3,Iris-versicolor
6.5,2.8,4.6,1.5,Iris-versicolor
. . .
in KMeans::run(vector<Point>&) you call points[index_point].setCluster(i); without any guarantee that index_point is within bounds.
index_point is determined by int index_point = rand() % total_points;, and total_points is retrieved from the input file "datafile.txt" which could be anything. It certainly does not have to match points.size(), but it should. Make sure it does, or just use points.size() instead.
A bit offtopic, but using rand() and only using modulo is almost always wrong. If you use C++11 or newer, please consider using std::uniform_int_distribution.
points[index_point].setCluster(i); could be accessing the vector out of bounds. The code you quoted actually always sets a number of total_points in the vector points before calling run, while your modified code just reads until end of file and has no guarantees that the number of total points passed to the constructor of KMeans matches the value of entries in points. Either fix your file I/O or fix the logic of bounds checking.

Intersection of 2 sets

I wrote a function in C++ for finding an intersection and union of 2 sets.
I tried this following function:
intersection function:
bool member (int x[10],int s[10])
{
bool result=false;
for (int i=0; i<10; i++)
for (int j=0 ; j<10;j++)
if (x[i]==s[j])
result=true;
return result;
}
int intersection(int s1[10],int s2[10],int s3[10])
{
for ( int i=0 ; i<10 ; i++)
{
if (member(s1,s2)==true)
s3[i]=s1[i];
}
return 0;
}
You can try union and intersection of two sets of user input size as below :
#include<stdio.h>
#include<malloc.h>
void main()
{
int *a, *b, *c, *d, n1, n2, i, j, k=0, l=0, flag=0;
printf("Enter number of elements in A and B : ");
scanf("%d %d",&n1,&n2);
a = (int *)malloc(sizeof(int)*n1);
b = (int *)malloc(sizeof(int)*n2);
c = (int *)malloc(sizeof(int)*((n1>n2)?n1:n2));
d = (int *)malloc(sizeof(int)*(n1+n2));
printf("\nEnter element in set A : ");
for(i=0;i<n1;i++)
{
printf("\nEnter element : ");
scanf("%d",&a[i]);
}
printf("\nEnter elements in set B : ");
for(i=0;i<n2;i++)
{
printf("\nEnter element : ");
scanf("%d",&b[i]);
}
for(i=0;i<n1;i++)
{
for(j=0;j<n2;j++)
{
if(a[i]==b[j])
{
c[l++]=a[i];
j=0;
break;
}
}
}
for(i=0;i<n2;i++)
d[k++]=a[i];
for(i=0;i<n1;i++)
{
flag=0;
for(j=0;j<n2;j++)
{
if(b[i]==a[j])
{
flag=1;
break;
}
}
if(!flag)
d[k++]=b[i];
}
printf("\n\t A = {");
for(i=0;i<n1;i++)
{
printf("%d",a[i]);
}
printf("}");
printf("\n\t B = {");
for(i=0;i<n2;i++)
{
printf("%d",b[i]);
}
printf("}");
printf("\n\t A U B = {");
for(i=0;i<k;i++)
{
printf("%d",d[i]);
}
printf("}");
printf("\n\t A n B = {");
for(i=0;i<l;i++)
{
printf("%d",c[i]);
}
printf("}");
}
You're copying s1 in s3, one item at a time, if member(s1, s2) return true, that is if it's an intersection between s1 and s2
You should rewrite in this way (caution: not tested)
bool member (int x, int s[10])
{
bool result=false;
for (int j=0 ; (! result) && (j<10);j++)
if (x==s[j])
result=true;
return result;
}
int intersection(int s1[10],int s2[10],int s3[10])
{
int j = -1;
for ( int i=0 ; i<10 ; i++)
{
if (member(s1[i],s2)==true)
s3[++j]=s1[i];
}
// what about other places of s3?
return 0;
}

Program crashed after end of scope

I was confused from this following codes, it's creating crash that I fully don't understand.
#include <stdio.h>
#include <string.h>
#include <vector>
using namespace std;
struct Store
{
int pos;
char character;
};
vector<struct Store> v_store;
void swap_inside_vector(vector<struct Store> &v_store, int a, int b)
{
struct Store tmp = v_store[b];
v_store[b] = v_store[a];
v_store[a] = tmp;
}
int find_inside_vector(vector<struct Store> &v_store, int pos)
{
for(int i = 0; i < v_store.size(); i++)
{
if(v_store[i].pos == pos)
return i;
}
return -1;
}
void swap_most_right_to_most_left(vector<struct Store> &v_store)
{
struct Store tmp = v_store[v_store.size() - 1];
for(int i = v_store.size(); i > 0; i--)
{
v_store[i] = v_store[i-1];
}
v_store[0] = tmp;
}
void print_char_inside_vector(vector<struct Store> &v) // used for debugging
{
for(int i = 0; i < v.size(); i++)
{
printf("%C", v[i].character);
}
}
int check_vector_original_state(vector<struct Store> &v_store)
{
for(int i = 1; i <= v_store.size(); i++)
{
if(v_store[i-1].pos != i)
return 0;
}
return 1;
}
int main()
{
int n;
char input_str[100];
for(int q = 1; scanf("\n%d", &n), n; q++)
{
scanf("%s", input_str);
vector<struct Store> original_store, tmp_origin_store, v_store;
vector<vector<struct Store> > store_vector;
original_store.clear();
tmp_origin_store.clear();
v_store.clear();
store_vector.clear();
for(int i = 1; i <= strlen(input_str); i++)
{
struct Store s = {.pos = i, .character = input_str[i-1]};
original_store.push_back(s);
}
tmp_origin_store = original_store;
v_store = tmp_origin_store;
for(int i = 1, current_pos = 0; i <= n; i++, current_pos++)
{
int vector_index = find_inside_vector(v_store, tmp_origin_store[current_pos].pos);
//printf("Processing -> [%d], Current Pos -> [%d]\n", i, current_pos);
for(int z = 0; z < (current_pos + 1); z++)
{
if(vector_index == (v_store.size() - 1))
{
swap_most_right_to_most_left(v_store);
vector_index = 0;
}
else
{
swap_inside_vector(v_store, vector_index, vector_index + 1);
vector_index++;
}
//print_char_inside_vector(v_store);
//puts("");
}
//puts("");
store_vector.push_back(v_store);
if(check_vector_original_state(v_store))
{
store_vector.push_back(v_store);
break;
}
if(current_pos == (v_store.size() - 1))
{
tmp_origin_store = v_store;
current_pos = -1;
}
}
// debugging
/*for(int x = 0; x < store_vector.size(); x++)
{
printf("[%d] -> ", x + 1);
print_char_inside_vector(store_vector[x]);
puts("");
}*/
int target_pos;
if(store_vector.size() < n)
{
target_pos = n % store_vector.size();
}
else
{
target_pos = store_vector.size();
}
if(target_pos == 0)
{
printf("%d. ", q);
print_char_inside_vector(store_vector[0]);
puts("");
}
else
{
printf("%d. ", q);
print_char_inside_vector(store_vector[target_pos - 1]);
puts("");
}
}
}
What this program does is accepting input from STDIN, process it, and output it on STDOUT.
My expecting input is
3 ABCD
13 ACM
3 DAEQD
4 FAEQS
Expected output is
1. CABD
2. CAM
3. DAQDE
4. FQASE
My problem is, after inputing fourth input into STDIN, and after output is being shown, crash occured.
C:\Study>h.exe
3 ABCD
1. CABD
13 ACM
2. CAM
3 DAEQD
3. DAQDE
4 FAEQS
4. FQASE
0 [main] h 9092 cygwin_exception::open_stackdumpfile: Dumping stack trace to h.exe.stackdump
From my observation, I think the problem is at the vector, but it's just a guess.
Your code didn't compile :
//struct Store s = { .pos = i, .character = input_str[i - 1] }; // syntax not recongnized
Store s = { i, input_str[i - 1] }; // replaced with this.
After fixing this, the debugging immediatly identified an out of bound problem on a vector, which could lead to memory corruption issue. It's in swap_most_right_to_most_left():
for (int i = v_store.size(); i > 0; i--) { // you start with i=v_store.size()
v_store[i] = v_store[i - 1]; // and you immediately get out of bounds !
}
If you correct this instruction to :
for (int i = v_store.size()-1; i > 0; i--) {
v_store[i] = v_store[i - 1];
}
you'll get the expected output for the given input.

Histogram Calculating program

#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int arraylength;
int lastbig = 0;
int lastsmall = 0;
int temp = 0;
int numofgroups = 0;
double gg = 0;
cout<<"Enter the number of numbers you are going to enter "<<endl;
cin>>arraylength;
int data[arraylength];
for(int ahmet = 0;ahmet < arraylength;ahmet++)
{
cout<<"Enter the num no."<<ahmet+1<<endl;
cin>>data[ahmet];
}
for(int bbm = 0;bbm < arraylength;bbm++)
{
if(data[bbm]>lastbig)
{
lastbig = data[bbm];
}
}
cout<<"Biggest "<<lastbig<<endl;
for(int ddr = 0;ddr < arraylength;ddr++)
{
if(data[ddr]<lastbig && lastsmall == 0)
{
lastsmall = data[ddr];
}
else if(data[ddr]<lastsmall)
{
lastsmall = data[ddr];
}
}
cout<<"smallest "<<lastsmall<<endl;
temp = lastbig-lastsmall;
cout<<"Enter the number of groups you want"<<endl;
cin>>numofgroups;
gg = (double)temp/numofgroups;
cout<<"gg ="<<gg;
gg = ceil(gg);
cout<<"gg ="<<gg<<endl;
int z = 0;
int lastnumleft = 0;
struct groups {
int min;
int max;
int membercount;
}group[numofgroups];
int tmp = lastsmall;
for(int dinghy = 0;dinghy<numofgroups;dinghy++)
{
if(dinghy == 0)
{
group[dinghy].min = tmp;
group[dinghy].max = tmp + ((int)gg - 1);
tmp = tmp + (int)gg;
}
else{
group[dinghy].min = tmp;
group[dinghy].max = tmp+((int)gg-1);
tmp = tmp + (int)gg;
}
}
for(int jpn = 0;jpn<numofgroups;jpn++)
{
for(int mtr = 0;mtr<arraylength;mtr++)
{
if(data[mtr]>group[jpn].min&&data[mtr]<group[jpn].max)
{
group[jpn].membercount++;
}
}
}
for(int dingil = 0;dingil<numofgroups;dingil++)
{
if(!group[dingil].membercount){
group[dingil].membercount = 0;
}
}
for(int xyz = 0;xyz<numofgroups;xyz++)
{
cout<<group[xyz].min<<" - "<<group[xyz].max<<" "<<group[xyz].membercount<<endl;
}
cin.ignore();
cin.get();
return 0;
}
This program actually does the calculations needed for making a histogram member count of groups and min max of numbers but i cant group the numbers can you help me :)
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int arraylength;
int lastbig = 0;
int lastsmall = 0;
int temp = 0;
int numofgroups = 0;
double gg = 0;
cout<<"Enter the number of numbers you are going to enter "<<endl;
cin>>arraylength;
int *data = new int[arraylength];
for(int ahmet = 0;ahmet < arraylength;ahmet++)
{
cout<<"Enter the num no."<<ahmet+1<<endl;
cin>>data[ahmet];
}
for(int bbm = 0;bbm < arraylength;bbm++)
{
if(data[bbm]>lastbig)
{
lastbig = data[bbm];
}
}
cout<<"Biggest "<<lastbig<<endl;
for(int ddr = 0;ddr < arraylength;ddr++)
{
if(data[ddr]<lastbig && lastsmall == 0)
{
lastsmall = data[ddr];
}
else if(data[ddr]<lastsmall)
{
lastsmall = data[ddr];
}
}
cout<<"smallest "<<lastsmall<<endl;
temp = lastbig-lastsmall;
cout<<"Enter the number of groups you want"<<endl;
cin>>numofgroups;
gg = (double)temp/numofgroups;
cout<<"gg ="<<gg;
gg = ceil(gg);
cout<<"gg ="<<gg<<endl;
int z = 0;
int lastnumleft = 0;
struct groups {
int min;
int max;
int membercount;
}*group;
group = new groups[numofgroups];
int tmp = lastsmall;
for(int dinghy = 0;dinghy<numofgroups;dinghy++)
{
if(dinghy == 0)
{
group[dinghy].min = tmp;
group[dinghy].max = tmp + ((int)gg - 1);
tmp = tmp + (int)gg;
}
else
{
group[dinghy].min = tmp;
group[dinghy].max = tmp+((int)gg-1);
tmp = tmp + (int)gg;
}
}
for(int jpn = 0;jpn<numofgroups;jpn++)
{
//need to initialize as it has some garbage value and that is what it is printing out.
group[jpn].membercount = 0;
for(int mtr = 0;mtr<arraylength;mtr++)
{
// note the equalities as you need to include the first and the last numbers
if(data[mtr]>=group[jpn].min&&data[mtr]<=group[jpn].max)
{
group[jpn].membercount++;
}
}
}
for(int dingil = 0;dingil<numofgroups;dingil++)
{
if(!group[dingil].membercount){
group[dingil].membercount = 0;
}
}
for(int xyz = 0;xyz<numofgroups;xyz++)
{
cout<<group[xyz].min<<" - "<<group[xyz].max<<" "<<group[xyz].membercount<<endl;
}
cin.ignore();
cin.get();
return 0;
}
It'll work fine now :)