C++ Instances of value in array? (Histogram) - c++

I was wondering if it was possible in C++ to parse through an array and retrieve the amount of times an integer appears in the array. I'm trying to make a histogram of the values, but currently am stuck as to how to continue.
It is a one-dimensional array if that matters and I am using this function to print the array:
void print(int a[], int n)
{
int j = 1;
cout << endl;
for(int i=0; i < n; i++)
{
if(!(j%6))
{
j=1; cout << endl << endl;
}
cout << right << setw(2) << a[i] << " ";
++j;
}
}
Which is giving me correct output in this screenshot:
http://i.imgur.com/P8Jzj1V.png
However, once I go to my histogram function (which I know is coded incorrectly) I am getting the following output:
http://i.imgur.com/WJtBjoF.png
Because with my current code it is printing asterisks based on a value taken from the array:
for (int i = 0; i < size; i++)
{
cout << a[i] << ":" << bar(a[i-1]);
cout << endl;
}
P.S. - The "bar" function just returns a string with a specified amount of '*' based on the number given to it.
I know the last bit is incorrect, but that's what I'm trying to fix.

There are two easy ways to go:
sort+count
Sort the array
Iterate through them all, and print summaries on encountering a different element / the end.
unordered_map
Create an std::unordered_map<int,int>
Iterate through the array incrementing the count for each encountered element when you encounter it.
Print the summary.
An array of size 2**sizeof(int)*CHAR_BIT is prohibitively big.

Let's see. You can keep a map with the counts of each element, being each element a key to the map:
for (int i = 0; i < size; i++)
{
int current = a[i];
//if it doesn't find it it returns
if (countMap.find(current) != countMap.end())end()
{
countMap[current]++;
} else
{
countMap[current] = 1;
}
}
I don't know if the syntax is totally correct, but something like this will get you what you want.

Figured it out.
int tempVal = 0;
int tempTwo = 0;
int counter = 0;
for (int i = 0; i < size; i++) // Checks for histogram output
{
tempVal = a[i];
for (int j = 0; j < size; j++)
{
if(a[j] == tempVal)
{
counter += 1;
}
}
if(tempVal != tempTwo)
cout << setw(3) << tempVal << " : " << bar(counter) << endl;
tempTwo = tempVal;
counter = 0;
}

Related

C++: Console outputting weird numbers when printing array [duplicate]

This question already has answers here:
Uninitialized variable behaviour in C++
(4 answers)
What happens when I print an uninitialized variable in C++? [duplicate]
(4 answers)
Closed 4 months ago.
I'm beginning to learn about C++. I've been putting it off for a long time and I decided to start learning it.
Currently, I'm having trouble finding the issue with my program. My program is supposed to take integers from the input, insert it into an array, and then sort it. Everything is working correctly-- even the sorting... most of the time...
Sometimes the sorting works as intended. Sometimes it spits the numbers out in random orders. Sometimes it output really weird negative and positive integers that are very close to the upper and minimum bounds that integers can go. After hours of trying to figure out something about this, I just can't figure it out. I've been thinking that it has something with the pointers for the array? But I'm unsure because I barely know how pointers work.
I've tried setting the array to hard-coded values and sorting with different algorithms, none of which helped whatsoever.
#include <iostream>
/*Sorting program*/
using namespace std;
int* sortArray(int* array, int size) {
for (int i = 0; i < size; i++) {
int lowest;
for (int k = i; k < size; k++) {
if (array[k] < array[i] && array[k] < array[lowest]) {
cout << array[k] << " is less than " << array[i] << endl;
lowest = k;
}
}
int temp = array[lowest];
array[lowest] = array[i];
array[i] = temp;
}
return array;
}
int main() {
int low, high, target, size;
cout << "Enter size of array : ";
cin >> size;
int *array = new int[size];
for (int i = 0; i < size; i++) {
cout << "Enter array[" << i << "] : " << endl;
int entry;
cin >> entry;
array[i] = entry;
}
/* */
array = sortArray(array, size);
for (int i = 0; i < size; i++) {
cout << "array[" << i << "] = " << array[i] << endl;
}
return 1;
}
Output
>>OutputFile.exe
Enter size of array : 4
Enter array[0] :
3
Enter array[1] :
4
Enter array[2] :
7
Enter array[3] :
4
array[0] = 2059292487
array[1] = 3
array[2] = 4
array[3] = 7
Output (program ran again, nothing changed)
>>OutputFile.exe
Enter size of array : 8
Enter array[0] :
3
Enter array[1] :
4
Enter array[2] :
8
Enter array[3] :
1
Enter array[4] :
88
Enter array[5] :
4
Enter array[6] :
5
Enter array[7] :
6
array[0] = 1
array[1] = 3
array[2] = 4
array[3] = 4
array[4] = 5
array[5] = 6
array[6] = 8
array[7] = 88
In your sorting algorithm,
if (array[k] < array[i] && array[k] < array[lowest]) {
cout << array[k] << " is less than " << array[i] << "\n";
lowest = k;
}
Changes to lowest index to k every time that k < i.
This means that even if the array has smaller values in k, the last value in the list that happened to be smaller than i will be swapped with i.
This is why your list is being answered back strangely.
To fix it, you need to have the smallest value of the list (or part being checked) change each iteration of the loop.
int *sortArray(int *array, int size) {
int lowest_index; //initialized variable(s)
//bubble-sort algorithm from front to back, smallest to largest
for (int i = 0; i < size-1; i++) { //go through entire array (except the first since it is being compared as the "smallest" for the moment)
int lowest_index = i; //initialize as something within the [part of the] array [being analyzed], they may all be equal.
for (int j = i+1; j < size; j++) { //go through each remaining element of the array
if (array[j] < array[lowest_index]) { //comparison to smallest found element
cout << array[j] << " is less than " << array[i] << "\n";
lowest_index /*for this loop*/ = j;
}
}
//swap front item (i) with smallest found in previous loop
int temp = array[lowest_index];
array[lowest_index] = array[i];
array[i] = temp;
}
return array;
}
So, the good news is that you're learning the language itself just fine; keep at it!
I assume as selection sort algorithm.
/*Sorting program*/
using namespace std;
int *sortArray(int *array, int size) {
for (int i = 0; i < size; i++) {
int lowest = i;
for (int k = i; k < size; k++) {
if (array[k] < array[i] && array[k] < array[lowest]) {
cout << array[k] << " is less than " << array[i] << endl;
lowest = k;
}
}
int temp = array[lowest];
array[lowest] = array[i];
array[i] = temp;
}
return array;
}
int main() {
int low, high, target, size;
cout << "Enter size of array : ";
cin >> size;
int *array = new int[size];
for (int i = 0; i < size; i++) {
cout << "Enter array[" << i << "] : " << endl;
int entry;
cin >> entry;
array[i] = entry;
}
/* */
array = sortArray(array, size);
for (int i = 0; i < size; i++) {
cout << "array[" << i << "] = " << array[i] << endl;
}
return 1;
}
int lowest = i;

Why is my insertion sort algorithm altering numbers in the given array? (C++)

I have a C++n insertion sort function template, and it works fine when I give the function an array of integers, but when I give the function an array of doubles, although the array is indeed sorted afterwards, for some reason it alters the numbers in the sorted array.
The code:
#include <iostream>
#include <stdlib.h>
using namespace std;
template <typename T>
void insertionSort(T ary[10], int size)
{
// Printing unsorted array
cout << "Array before sorting: [";
for (int i = 0; i < size; i++)
{
cout << ary[i] << ", ";
}
cout << "]" << endl;
// Beginning of sorting
int j, t;
for(int i = 1; i < size; i++)
{
for (int i = 0; i < size; i++)
{
j = i;
while(j > 0 && ary[j] < ary[j-1])
{
t = ary[j];
ary[j] = ary[j-1];
ary[j-1] = t;
j--;
}
}
}
// Printing sorted array
cout << "Array after sorting: [" ;
for (int i = 0; i < size; i++)
{
cout << ary[i] << ", ";
}
cout << "]\n" << endl;
}
int main()
{
cout << "*** INTEGER ARRAY INSERTION SORT ***" << endl;
int intAry[10] = {0};
for (int i = 0; i<= 9; i++)
{
intAry[i] = rand() % 100;
}
insertionSort(intAry, 10);
cout << "*** DOUBLE ARRAY INSERTION SORT ***" << endl;
double dAry[10] = {0};
for(int i = 0; i<=9; i++)
{
dAry[i] = (double)rand() / RAND_MAX * 100;
}
insertionSort(dAry, 10);
return 0;
}
The output:
You can see here that it changes the number in the array of doubles, like 14.1603 to 14.
Thank you for any help!
The problem is, you want to compare the double numbers, but when you're going through the loop, you use the int i and int j variables. Result is incorrect due to incompatible data type.
if you covert "double" the "int" data types, your problem will be solved.
Also you must change your array type to double.

deleting and sorting elements of a vector in C++

I have made this simple code to delete and sort elements of a vector. I have checked it many times, both sorting and deletion algorithm is correct when I run them individually, but there is a problem, when I delete an element then sort the vector in descending order the program puts a garbage a value at '0' index, but works fine if I do sorting in ascending order.
Any help would be appreciated. Thank you.
Here is the image of a sample run of the program 1
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main()
{
bool flag = 1;
int size = 5,delind;
vector <int> v1;
v1.resize(size);
for(int i = 0; i<size; i++)
{
cout<<"\nenter a no. ";
cin>>v1[i];
}
// index of the element to be deleted
cout << "\nEnter the index of no. to delete: ";
cin >> delind;
for(int i = delind; i < size; i++)
{
v1[i] = v1[i+1];
}
--size;
v1.erase(v1.begin()+size);
for(int i =0; i < size; i++)
{
cout << endl << endl << v1[i];
}
cout << "\n sorting";
// sorting
while (flag == 1)
{
flag = 0;
for(int i = 0; i < size; i++)
{
if(v1[i] < v1[i+1]) // works fine with if(v1[i]>v1[i+1])
{
flag = 1;
swap(v1[i],v1[i+1]);
}
}
}
for(int i = 0; i < size; i++)
{
cout << endl << endl << v1[i];
}
return 0;
}
You have an off by one error with your sorting portion. In the following lines:
for(int i = 0;i<size;i++)
{
if(v1[i]<v1[i+1]) // works fine with if(v1[i]>v1[i+1])
{
flag = 1;
swap(v1[i],v1[i+1]);
}
}
At this point size is 4, and v1.size() is also 4. In the for-loop i goes from 0 to 3 like usual. But you are using v1[i+1], so your loop will try to access v1[4], which is out of bounds and gives you the garbage value that you are seeing.
To fix it, just fix your loop bounds:
for (int i = 0; i < size - 1; i++)

When printing out double dimensional array to console, values are being set randomly

Let's say I create a double dimensional array in main fuction:
int board[8][8] = {0};
When I am printing it out to console with a simple FOR LOOP in MAIN everything works fine and console shows that all elements have been set to 0.
However, when I am trying to pass this array as an argument to the print function like shown below, some elements are set correctly to 0, whereas the rest become random values :
void print_board (int (*array)[8][8]);
int main (){
int board[8][8] = {0};
print_board(&board);
return 0;
}
void print_board (int (*array)[8][8]){
for (int i = 0; i < 8; i++){
for (int j = 0; j < 8; j++){
cout << *array[i][j] << " ";
}
cout << endl;
}
}
I played with pointers and ampersands, and tried to google, but guess I am missing something.
Would be very grateful for your help!
According to the Operator Precedence, operator[] has higher precedence than operator*. So *array[i][j] is equivalent to *(array[i][j]). And array is a pointer (to array), and array[i] might cause UB when i >= 1.
You should change it to
cout << (*array)[i][j] << " ";
You can change your output to std::cout << (*array)[i][j] or make things simpler:
void print_board(int array[8][8]){
for (int i = 0; i < 8; i++){
for (int j = 0; j < 8; j++){
std::cout << array[i][j] << " ";
}
std::cout << std::endl;
}
}
int main (){
int board[8][8] = {0};
print_board(board);
}

How to add up a certain group of number in an array?

Hey so I have function that needs to add up a certain number of even numbers in an array based off user input. Here's my approach so far:
function call:
cout << "The sum of the first " << userSum << " even numbers is: " <<
SumEvens(list, SIZE, userSum);
function definition:
int SumEvens(int arr[], const int size, int evensAdd)
{
int sum = 0;
for (int i = 0; i <= size; i++){
for (int j = 0; j <= evensAdd; j++){
if (arr[i] % 2 == 0)
sum += arr[i];
}
}
return sum;
}
I'm Not sure if i need the double for loop here, but it seems necessary so that i can go through every number and then only select the ones that i need.
Now whenever I run this program and tell it to add up the numbers it spits out garbage, so I was seeing if you guys could point out any glaring flaws in the code. Thanks!
Your implementation is incorrect:
int SumEvens(int arr[], const int size, int evensAdd)
{
for(int i= 0; i < size; i++){
std::cout << arr[i] << " ";
}
std::cout << std::endl;
std::cout << size << " " << evensAdd << std::endl;
int sum = 0;
for (int i = 0; i <= size; i++){
if(evensAdd==0) return sum
if (arr[i] % 2 == 0){
sum += arr[i];
evensAdd--;
}
}
}
return sum;
}
This doesn't break on evenAdd > size