Filling an 1D array in C++ - c++

I have an integer array:
int listint[10] = {1,2,2,2,4,4,5,5,7,7,};
What I want to do is to create another array in terms of the multiplicity. So I define another array by:
int multi[7]={0};
the first index of the multi array multi[0] will tell us the number of multiplicity of the array listint that has zero. We can easily see that, there is no zero in the array listint, therefore the first member would be 0. Second would be 1 spice there are only 1 member in the array. Similarly multi[2] position is the multiplicity of 2 in the listint, which would be 3, since there are three 2 in the listint.
I want to use an for loop to do this thing.
#include <iostream>
#include <stdio.h>
using namespace std;
int main()
{
unsigned int count;
int j;
int listint[10] = { 1,2,2,2,4,4,5,5,7,7, };
int multi[7] = { 0 };
for (int i = 0; i < 9; i++)
{
if (i == listint[i])
count++;
j = count;
multi[j] = 1;
}
cout << "multi hit \n" << multi[1] << endl;
return 0;
}
After running this code, I thought that I would want the multiplicity of the each element of the array of listint. So i tried to work with 2D array.
#include <iostream>
#include <stdio.h>
using namespace std;
int main()
{
unsigned int count;
int i, j;
int listint[10] = { 1,2,2,2,4,4,5,5,7,7, };
int multi[7][10] = { 0 };
for (int i = 0; i < 9; i++)
{
if (i == listint[i])
count++;
j = count;
for (j = 0; j < count; j++) {
multi[j][i] = 1;
}
}
cout << "multi hit \n" << multi[4][i] << endl;
return 0;
}
The first code block is something that I wanted to print out the multiplicity. But later I found that, I want in a array that multiplicity of each elements. SO isn't the 2D array would be good idea?
I was not successful running the code using 2D array.
Another question. When I assign j = count, I mean that that's the multiplicity. so if the value of count is 2; I would think that is a multiplicity of two of any element in the array listint.

A 2d array is unnecessary if you're just trying to get the count of each element in a list.
#include <iostream>
int main() {
int listint[10] = { 1,2,2,2,4,4,5,5,7,7, };
int multi[8] = { 0 };
for (int i : listint)
++multi[i];
for (int i = 0; i < 8; ++i)
std::cout << i << ": " << multi[i] << '\n';
return 0;
}
There's also a simpler and better way of doing so using the standard collection std::map. Notably, this doesn't require you to know what the largest element in the array is beforehand:
#include <map>
#include <iostream>
int main() {
int listint[10] = {1,2,2,2,4,4,5,5,7,7,};
std::map<int, int> multi;
for (int i : listint)
multi[i]++;
for (auto [k,v] : multi)
std::cout << k << ": " << v << '\n';
}

Try this incase maps won't work for you since you're a beginner, simple:
#include <iostream>
#include <stdio.h>
using namespace std;
int main()
{
unsigned int count;
int j;
int listint[10] = {1,2,2,2,4,4,5,5,7,7};
int multi[8]={0};
for(int i=0; i<10; i++)
{
multi[listint[i]]++; // using listint arrays elements as index of multi to increase count.
}
for( int i=1; i<8; i++)
{
cout << "multi hit of "<<i<<" : "<< multi[i]<<endl;
}
return 0;
}
OR if numbers could get large and are unknown but sorted
#include <iostream>:
#include <stdio.h>
using namespace std;
int main()
{
unsigned int count = 0;
int index = 0; // used to fill elements in below arrays
int Numbers[10] = {0}; // storing unique numbers like 1,2,4,5,7...
int Count[10] = {0}; // storing their counts like 1,3,2,2,2...
int listint[10] = {1, 2, 2, 2, 4, 4, 5, 5, 7, 7};
for(int i = 0; i < sizeof(listint) / sizeof(listint[0]); i++)
{
count++;
if (listint[i] != listint[i+1]) {
Numbers[index] = listint[i];
Count[index] = count;
count=0;
index++;
}
}
for(int i=0; i<index; i++)
{
cout << "multi hit of "<<Numbers[i]<<" is " << Count[i]<<endl;
}
return 0;
}

Related

How to shift values of given array by moving first value to the last C++

I was struggling on how to move the first value to the las in order like shown in the picture
enter image description here
What should I do?
#include <iostream>
using namespace std;
void rotate(int A[], int n = 5)
{
int x = A[n - 1], i;
for (i = n - 1; i > 0; i--)
{
A[i] = A[i -1];
}
A[0] = x;
}
int main()
{
int A[] = { 1, 2, 3, 4, 5 }, i;
int n = sizeof(A) / sizeof(A[5]);
cout << "Given array is \n";
for (i = 0; i < n; i++)
cout << A[i] << ' ';
for (int j = 0; j < n; j++)
{
rotate(A, n);
cout << "\nStep " << j << " --> ";
for (i = 0; i < n; i++)
{
cout << A[i] << ' ';
}
}
return 0;
}
Your code is still quite "C" like. Here is an example that hopefully will teach you some C++ coding :
#include <algorithm>
#include <iostream>
#include <vector>
// passing arrays is easier using std::vector/std::array (no need to pass size seperately)
void rotate(std::vector<int>& values)
{
// using algorithm's std::swap you can better show WHAT you are doing
// vector and array also have a size() method so you don't
// have to use "C" style sizeof tricks.
for (std::size_t n = 0; n < values.size() - 1; ++n)
{
std::swap(values[n], values[n + 1]);
}
}
int main()
{
// prefer std::vector (or std::array) in C++. Not "C" style arrays
std::vector<int> values{ 1,2,3,4,5 };
rotate(values);
// use range based for loop if you can.
for (const auto value : values)
{
std::cout << value << " ";
}
return 0;
}

How can I start a loop from middle of the array?

There is a given pseudo code.
int Function(X : array[P..Q] of integer)
1 maxSoFar = 0
2 for L = P to Q
I was using C and trying to change it into C++ code.
The reason that I am struggling with it is I have no idea how to express it is start from 'P' in the loop.
I do not know how to do that before initilization even without parameter.
int Function(vector<int> X)
{
int maxSoFar = 0;
for (int I = 0; I < X.size(); I++) ;
}
This is what I did.
I wonder if it is same with the pseudo code or not.
You can just divide your vector size by 2:
#include <vector>
#include <iostream>
using namespace std;
int f(vector<int> v) {
int maxSoFar = 0;
int len = v.size();
for (int i = len / 2; i < len; i++) { // i = len / 2, starts from the middle
maxSoFar += v[i];
cout << v[i] << ' ';
cout << maxSoFar << endl;
}
}
int main(void) {
vector<int> v = {1, 3, 5};
f(v);
}
output:
3 3
5 8
You should take a closer look at the for loop on wikipedia: for (initialization; break condition; incrementation)
#include<iostream>
using namespace std;
int main()
{
int i,n;
cout<<"enter the number of elements : ";
cin>>n;
int a[n];
cout<<endl<<"enter the value of this array : ";
for(i=0;i<n;i++)
{
cin>>a[i];
}
cout<<endl<<"print the last half elements of this array : ";
for(i=(n/2);i<n;i++)
cout<<a[i]<<" ";
cout<<endl;
return 0;
}

Retrieve index of element of array stored in vector

I have a 2D array used to store non-repeated values and some entries are randomly picked and push_back-ed into a vector as favorite list.
int num[10][10];
vector<int> fav_list;
int retrieved_i, retrieved_j, retrieve_vector_position;
for(i=0;i<10;i++) for(j=0;j<10;j++)
// ...assign numbers to num...
fav_list.push_back(num[2][3]);
fav_list.push_back(num[4][7]);
fav_list.push_back(num[6][2]);
//...push_back more random selected num[...][...] into fav_list...
The problem is, how can I retrieve the i, j index of particular fav_list[...]?
I've tried to make struct struct Num{int value, index_i, index_j;}num[10][10]; so that I can do in this way
retrieved_i = fav_list[retrieve_vector_position].index_i;
retrieved_j = fav_list[retrieve_vector_position].index_j;
but I wish to know is there any other better/ efficient ways?
Using a plain vector to store your 2D array would solve the problem. You could access elements in the vector by calculating absolute index (i * row_len + j) and store in fav_list absolute indices.
Also, you may want to use std::unordered_map for fav_list. Generally, hash tables is the most efficient data structure for such caches.
There are a few possibilities depending on how often you want to access the i & j indices / the favorite number itself.
One approach is, to save the indices instead of the number (or additional to it). With this approach, more memory is required but the the time to access the indices will be constant, regardless how big your array becomes. This uses std::pair to store 2 elements in your favorite vector.
#include <vector>
#include <iostream>
#include <utility>
using namespace std;
int main(int argc, char* argv[]) {
int num[10][10];
vector<std::pair<int, int>> fav_list;
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
if (/* your condition for favorites */) {
fav_list.push_back(num[i][j]);
}
}
}
/* example get the indices of the first favorite */
cout << "i: " << fav_list[0].first << "j: " << fav_list[0].second << endl;
/* example get the first favorite */
cout << num[fav_list[0].first][fav_list[0].second] << endl;
return 0;
}
Another approach is to "lookup" the indices, when you require it: it has the condition, that one number is not multiple times contained in your num[][] array (otherwise the first entry is found). There is no additional memory overhead required, but the time to lookup the indices will increase when your array gets bigger.
#include <vector>
#include <iostream>
using namespace std;
int main(int argc, char* argv[]) {
int num[10][10];
vector<int> fav_list;
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
if (/* your condition for favorites */) {
fav_list.push_back(num[i][j]);
}
}
}
/* example get the indices of the first favorite */
int indexI = -1, indexJ = -1;
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
if (fav_list[0] == num[i][j]) {
indexI = i;
indexJ = j;
break;
}
}
}
cout << "i: " << indexI << "j: " << indexJ << endl;
/* example get the first favorite */
cout << fav_list[0] << endl;
return 0;
}
Instead of storing 3 variable value, x and y just store a single unsigned int via which you can retrieve x and y.
struct fav_list
{
unsigned int total_rows;
unsigned int total_columns;
fav_list(unsigned int _rows, unsigned int _columns)
{
total_rows = _rows;
total_columns = _columns;
}
unsigned int get_x(unsigned int _index)
{
return v[_index] / total_columns;
}
unsigned int get_y(unsigned int _index)
{
return v[_index] % total_columns;
}
void append_xy_to_list(unsigned int _x, unsigned int _y)
{
v.push_back(_x * total_columns + _y);
}
vector <unsigned int> v;
};
fav_list f(10, 10);
for(x = 0; x < 10; ++x)
{
for(y = 0; y < 10; ++y)
{
//suppose you want to store the indexes of element num[x][y] then:
f.append_xy_to_list(x, y);
}
}
retrieved_i = f.get_x(retrieve_vector_position);
retrieved_j = f.get_y(retrieve_vector_position);

Error implementing selection sort in C++

I've written this code to sort an array using selection sort, but it doesn't sort the array correctly.
#include <cstdlib>
#include <iostream>
using namespace std;
void selectionsort(int *b, int size)
{
int i, k, menor, posmenor;
for (i = 0; i < size - 1; i++)
{
posmenor = i;
menor = b[i];
for (k = i + 1; k < size; k++)
{
if (b[k] < menor)
{
menor = b[k];
posmenor = k;
}
}
b[posmenor] = b[i];
b[i] = menor;
}
}
int main()
{
typedef int myarray[size];
myarray b;
for (int i = 1; i <= size; i++)
{
cout << "Ingrese numero " << i << ": ";
cin >> b[i];
}
selectionsort(b, size);
for (int l = 1; l <= size; l++)
{
cout << b[l] << endl;
}
system("Pause");
return 0;
}
I can't find the error. I'm new to C++.
Thanks for help.
The selectionSort() function is fine. Array init and output is not. See below.
int main()
{
int size = 10; // for example
typedef int myarray[size];
myarray b;
for (int i=0;i<size;i++)
//------------^^--^
{
cout<<"Ingrese numero "<<i<<": ";
cin>>b[i];
}
selectionsort(b,size);
for (int i=0;i<size;i++)
//------------^^--^
{
cout<<b[l]<<endl;
}
system("Pause");
return 0;
}
In C and C++, an array with n elements starts with the 0 index, and ends with the n-1 index. For your example, the starting index is 0 and ending index is 9. When you iterate like you do in your posted code, you check if the index variable is less than (or not equal to) the size of the array, i.e. size. Thus, on the last step of your iteration, you access b[size], accessing the location in memory next to the last element in the array, which is not guaranteed to contain anything meaningful (being uninitialized), hence the random numbers in your output.
You provided some sample input in the comments to your question.
I compiled and executed the following, which I believe accurately reproduces your shown code, and your sample input:
#include <iostream>
void selectionsort(int* b, int size)
{
int i, k, menor, posmenor;
for(i=0;i<size-1;i++)
{
posmenor=i;
menor=b[i];
for(k=i+1;k<size;k++)
{
if(b[k]<menor)
{
menor=b[k];
posmenor=k;
}
}
b[posmenor]=b[i];
b[i]=menor;
}
}
int main(int argc, char **argv)
{
int a[10] = {-3, 100, 200, 2, 3, 4, -4, -5, 6, 0};
selectionsort(a, 10);
for (auto v:a)
{
std::cout << v << ' ';
}
std::cout << std::endl;
}
The resulting output was as follows:
-5 -4 -3 0 2 3 4 6 100 200
These results look correct. I see nothing wrong with your code, and by using the sample input you posted, this confirms that.

Max In a C++ Array

I am trying to find the 'biggest' element in a user made array ,by using the max function from the algorithm library/header.
I have done some research on the cplusplus reference site but there I only saw how to compare two elements using the max function. Instead I am trying to display the maximum number using a function 'max' ,without having to make a 'for' loop to find it.
For example:
Array: array[]={0,1,2,3,5000,5,6,7,8,9}
Highest value: 5000
I have made this code but it gives me a bunch of errors, which can be the issue?
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int array[11];
int n = 10;
for (int i = 0; i < n; i++) {
array[i] = i;
}
array[5] = 5000;
max(array , array + n);
for (int i = 0; i < n; i++)
cout << array[i] << " ";
return 0;
}
max_element is the function you need. It returns an iterator to the max element in given range. You can use it like this:
cout << " max element is: " << *max_element(array , array + n) << endl;
Here you can find more information about this function: http://en.cppreference.com/w/cpp/algorithm/max_element
Here is a modification of your program that does what you want:
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int array[11];
int n = 11;
for (int i = 0; i < n; i++) {
array[i] = i;
}
array[5] = 5000;
cout << *std::max_element(array, array + n) << "\n";
return 0;
}
Note that you had a bug in your program, you did not initialize the last element in your array. This would cause your array to contain junk value in the last element. I've fixed that by increasing n to 11. Note that this is OK because the condition in the for loop is i < n, which means that i can be at most 10, which is what you want.
You can also use std::array by #include<array>
#include <iostream>
#include <algorithm>
#include <array>
using namespace std;
int main()
{
array<int,10> arr;
int n = 10;
for (int i = 0; i < n; i++) {
arr[i] = i;
}
arr[5] = 5000;
cout<<"Max: "<< *max_element(arr.begin(),arr.end())<<endl;
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
return 0;
}
More info on std::array