Related
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;
}
#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
int i;
int n=0;
int F[10];
F[0]=0;
F[1]=1;
cin>>n;
for(i=2; i<n+1; ++i)
{
F[i]=(F[i-1])+F[i-2];
cout <<F[i]<<endl;
}
getch();
return 0;
}
now this is a sort of a fibonacci number generator, but it outputs all previous numbers in the fibonacci series. I want it to print the last one. For example, if the input is 8, i want it to output "21" instead of 1 2 3 5 8 13 21.
#include <iostream>
#include <conio.h>
int main()
{
int F[10];
F[0] = 0;
F[1] = 1;
int n = 0;
cin >> n;
for (int i = 2; i <= n; ++i)
{
F[i] = F[i-1] + F[i-2];
}
std::cout << F[n] << std::endl;
getch();
}
Since you already know the index of the last element (n), you can just print that after the loop. I also did some other cleanup that didn't change the functionality of the program.
Note that the program originally and still assumes that n is less than 10.
Just store only 2 last values:
#include <iostream>
using namespace std;
int main()
{
int F[2] = { 1, 1 };
int n = 0;
cin>>n;
for(int i=2; i<n; ++i)
{
swap( F[0], F[1] );
F[1] += F[0];
}
std::cout << F[1] << std::endl;
return 0;
}
The idea of the program is to input elements in an array. Then give the integer 'x' a value. If 'x' is 3 and the array a[] holds the elements {1,2,3,4,5,6}, we must "split" a[] into two other arrays. Lets say b[] and c[].
In b[] we must put all values lower or equal to 3 and in c[] all values greater than 3.
My question is- How can i express the 3 elements in b[i]?
#include <iostream>
using namespace std;
int main()
{
int a[6];
int b[6];
int c[6];
int d;
for (int i = 0; i < 6; i++) {
cin >> a[i];
}
cin >> d;
for (int i = 0; i < 6; i++) {
if (d >= a[i]) {
b[i] = a[i]; // if d is 3, then i have 3 elements. How can i express them?
}
}
for (int i = 0; i < 6; i++) {
if (d< a[i]) {
c[i] = a[i];
}
}
for (int i = 0; i < 3; i++) {
cout << b[i];
}
cout << endl;
for (int i = 3; i < 6; i++) {
cout << c[i];
}
return 0;
}
I think all you're trying to do is have a way to determine how many int values you're copying from a[] to either b[] or c[]. To do that, introduce two more counters that start at zero and increment with each item copied to the associated array:
Something like this:
#include <iostream>
using namespace std;
int main()
{
int a[6];
int b[6], b_count=0; // see here
int c[6], c_count=0; // see here
int d;
for (int i = 0; i < 6; i++) {
cin >> a[i];
}
cin >> d;
for (int i = 0; i < 6; i++) {
if (d >= a[i]) {
b[b_count++] = a[i]; // see here
}
}
for (int i = 0; i < 6; i++) {
if (d< a[i]) {
c[c_count++] = a[i]; // see here
}
}
for (int i = 0; i < b_count; i++) { // see here
cout << b[i];
}
cout << endl;
for (int i = 3; i < c_count; i++) { // and finally here
cout << c[i];
}
return 0;
}
Now, if you want b[] or c[] to be dynamic in their space allocation, then dynamic-managed containers like st::vector<> would be useful, but I don't think that is required for this specific task. Your b[] and c[] are already large enough to hold all elements from a[] if needed.
WhozCraigs answer does a good job showing what you need to solve this using traditional arrays according to your tasks requirements.
I'd just like to show you how this can be done if you were allowed the full arsenal of the standard library. It is why people are calling for you to use std::vector. Things gets simpler that way.
#include <algorithm>
#include <iostream>
int main()
{
int a[6] = {1, 2, 3, 4, 5, 6 }; // Not using input for brevity.
int x = 3; // No input, for brevity
// Lets use the std:: instead of primitives
auto first_part = std::begin(a);
auto last = std::end(a);
auto comparison = [x](int e){ return e <= x; };
auto second_part = std::partition(first_part, last, comparison);
// Print the second part.
std::for_each(second_part, last, [](int e){ std::cout << e; });
// The first part is first_part -> second_part
}
The partition function does exactly what your problem is asking you to solve, but it does it inside of the array a. The returned value is the first element in the second part.
use std::vectors. do not use int[]s.
with int[]s (that are pre-c++11) you could, with a few heavy assumptions, find array length with sizeof(X)/sizeof(X[0]); This has, however, never been a good practice.
in the example you provided, probably you wanted to:
#define MAX_LEN 100
...
int main() {
int a[MAX_LEN];
int b[MAX_LEN];
int c[MAX_LEN];
int n;
std::cout << "how many elements do you want to read?" << std::endl;
std::cin >> n;
and use n from there on (these are common practice in programming schools)
Consider a function that reads a vector of ints:
std::vector<int> readVector() {
int n;
std::cout << "how many elements do you want to read?" << std::endl;
std::cin >> n;
std::vector<int> ret;
for (int i=0; i<n; i++) {
std::cout << "please enter element " << (i+1) << std::endl;
int el;
std::cin >> el;
ret.push_back(el);
}
return ret;
}
you could use, in main, auto a = readVector(); auto b = readVector(); a.size() would be the length, and would allow to keep any number of ints
Here's an example of how you'll approach it once you've a little more experience.
Anything you don't understand in here is worth studying here:
#include <iostream>
#include <vector>
#include <utility>
std::vector<int> get_inputs(std::istream& is)
{
std::vector<int> result;
int i;
while(result.size() < 6 && is >> i) {
result.push_back(i);
}
return result;
}
std::pair<std::vector<int>, std::vector<int>>
split_vector(const std::vector<int>& src, int target)
{
auto it = std::find(src.begin(), src.end(), target);
if (it != src.end()) {
std::advance(it, 1);
}
return std::make_pair(std::vector<int>(src.begin(), it),
std::vector<int>(it, src.end()));
}
void print_vector(const std::vector<int>& vec)
{
auto sep = " ";
std::cout << "[";
for (auto i : vec) {
std::cout << sep << i;
sep = ", ";
}
std::cout << " ]" << std::endl;
}
int main()
{
auto initial_vector = get_inputs(std::cin);
int pivot;
if(std::cin >> pivot)
{
auto results = split_vector(initial_vector, pivot);
print_vector(results.first);
print_vector(results.second);
}
else
{
std::cerr << "not enough data";
return 1;
}
return 0;
}
example input:
1 2 3 4 5 6
3
expected output:
[ 1, 2, 3 ]
[ 4, 5, 6 ]
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.
The program I'm trying to write allows me to enter 10 numbers and it should get tell me Number X is repeated X times and so on.
I've been trying this but the problem is I get the result as follows:
For example...{1,1,1,1,4,6,4,7,4}
The number 1 is repeated 4 times
The number 1 is repeated 3 times
The number 1 is repeated 2 times
The number 1 is repeated 1 times
The number 4 is repeated 3 times
The number 6 is repeated 1 times
The number 4 is repeated 2 times
The number 7 is repeated 1 times
The number 4 is repeated 1 times
The problem is that it checks the next number with the following numbers without skipping it, or without knowing it has written it before
#include <iostream>
#include <string>
using namespace std;
int main() {
int x[10];
for (int i=0;i<10;i++) {
cin>>x[i];
}
for (int i=0;i<9;i++) {
int count=1;
for (int j=i+1;j<10;j++) {
if (x[i]==x[j]) count++;
}
cout<<"The number "<<x[i]<<" is repeated "<<count<<" times"<<"\n";
}
}
The problem with your code is that you re-process numbers that you've already processed. So if there is an occurrence of 1 at position 0 and another occurrence of 1 at position 5, then you will process the 1 at position 5 again when you get there in the loop.
So you need a way to decide if a number has been processed already or not. An easy way is to add a second array (initially all values are set to 0) and whenever you process a number you mark all positions where that element occurs. Now before processing an element you check if it's been processed already and do nothing if that's the case.
Also, try to indent your code properly :)
C++ Code:
int main( void ) {
const int N = 10;
int A[N];
for(int i = 0; i < N; i++)
cin >> A[i];
int seen[N];
for(int i = 0; i < N; i++)
seen[i] = 0;
for(int i = 0; i < N; i++) {
if(seen[i] == 0) {
int count = 0;
for(int j = i; j < N; j++)
if(A[j] == A[i]) {
count += 1;
seen[j] = 1;
}
cout << A[i] << " occurs " << count << " times" << endl;
}
}
return 0;
}
Here's a fairly simple implementation using std::map.
#include <map>
#include <vector>
#include <cstdlib>
#include <iostream>
std::map<int, unsigned int> counter(const std::vector<int>& vals) {
std::map<int, unsigned int> rv;
for (auto val = vals.begin(); val != vals.end(); ++val) {
rv[*val]++;
}
return rv;
}
void display(const std::map<int, unsigned int>& counts) {
for (auto count = counts.begin(); count != counts.end(); ++count) {
std::cout << "Value " << count->first << " has count "
<< count->second << std::endl;
}
}
int main(int argc, char** argv) {
std::vector<int> mem = {1, 1, 1, 1, 4, 6, 4, 7, 4};
display(counter(mem));
return 0;
}
Output:
Value 1 has count 4
Value 4 has count 3
Value 6 has count 1
Value 7 has count 1
Compiled using the C++14 standard, but it should also work with C++11. Get rid of the vector initializer and use of auto and it should work with C++98.
Update:
I've updated this code a bit to use std::unordered_map instead of std::map, since order doesn't seem to be an issue. Also, I have simplified the loop controls based on some newer C++ features.
#include <unordered_map>
#include <vector>
#include <cstdlib>
#include <iostream>
std::unordered_map<int, unsigned int> counter(const std::vector<int>& vals) {
std::unordered_map<int, unsigned int> rv;
for (auto val : vals) {
rv[val]++;
}
return rv;
}
void display(const std::unordered_map<int, unsigned int>& counts) {
for (auto count : counts) {
std::cout << "Value " << count.first << " has count " << count.second << std::endl;
}
}
int main(int argc, char** argv) {
std::vector<int> mem = {1, 1, 1, 1, 4, 6, 4, 7, 4};
display(counter(mem));
return 0;
}
Output:
Value 7 has count 1
Value 6 has count 1
Value 4 has count 3
Value 1 has count 4
In this case, the order of the counts will be random since std::unordered_map is a hash table with no intrinsic ordering.
The most effective way I have recently come across with this...
#include<iostream>
#include<cstring>
using namespace std;
int main()
{
int array[10]={1,1,1,1,4,6,4,7,4};
int a[100];
memset(a,0,sizeof(a));
for(int i=0; i<sizeof(array)/sizeof(array[0]); i++)
{
a[array[i]]++;
}
for(int i=1; i<sizeof(a)/sizeof(a[0]); i++)
{
if(a[i]>0)
{
cout<<"The number "<<i<<"is repeated "<<a[i]<<" times"<<"\n";
}
}
OUTPUT:
The number 1 is repeated 4 times
The number 4 is repeated 3 times
The number 6 is repeated 1 times
The number 7 is repeated 1 times
Pretty simple using map!
See the Repl.it
#include <iostream>
#include <map>
int main()
{
int foo[]{1,1,1,1,4,6,4,7,4};
std::map<int, int> bar;
for (auto const &f : foo)
bar[f]++;
for (auto const &b : bar)
std::cout << "The number " << b.first
<< "is repeated " << b.second
<< "times\n";
}
Expected output:
The number 1 is repeated 4 times
The number 4 is repeated 3 times
The number 6 is repeated 1 times
The number 7 is repeated 1 times
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n;
cout<<"enter length of array:"<<endl;
cin>>n;
int arr[n];
for(int i=0;i<n;i++)
{
cout<<"enter element:";
cin>>arr[i];
}
sort(arr,arr+n);
/*this is for sort the array so we can find maximum element form user input and
using this element we make one array of that size
*/
int m=arr[n-1];
m++;
int a[m];
for(int i=0;i<m;i++)
{
a[i]=0;
}
for(int i=0;i<n;i++)
{
a[arr[i]]++;
}
cout<<endl;
for(int i=0;i<m;i++)
{
if(a[i]>0)
cout<<i<<"is repeat:"<<a[i]<<"time"<<endl;
}
}
output is like this:
enter length of array:
6
enter element:6
enter element:5
enter element:5
enter element:6
enter element:2
enter element:3
2is repeat:1time
3is repeat:1time
5is repeat:2time
6is repeat:2time
package DP;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
public class countsofRepeatedNumber {
public static void main(String[] args) {
// TODO Auto-generated method stub
int arr[]= {1,1,1,1,4,4,6,4,7};
int n=arr.length;
countNumber(arr,n);
}
private static void countNumber(int[] arr, int n) {
TreeMap<Integer,Integer>list= new TreeMap<Integer,Integer>();
Arrays.sort(arr);
int count=1;
for(int i=0;i<n-1;i++) {
if(arr[i]==arr[i+1]) {
count++;
}else {
list.put(arr[i], count);
count=1;
}
}
list.put(arr[n-1], count);
printDatas(list);
}
private static void printDatas(TreeMap<Integer, Integer> list) {
for(Map.Entry<Integer, Integer>m:list.entrySet()) {
System.out.println("Item "+m.getKey()+": "+m.getValue());
}
}
}
#include<bits/stdc++.h> using namespace std; int Duplicate(int a[],int n){ int i; int c=1; for(i=0;i<n;i++){ if(a[i]==a[i+1]){c++;continue;} if(c>1) cout<<a[i]<<" occured: "<<c<<" times"<<endl; c=1; }
} int main(){ int t; cin>>t; while(t--){ int n; cin>>n; int a[n]; for(int i=0;i<n;i++) cin>>a[i]; sort(a,a+n); Duplicate(a,n); } }
This code is in just O(n) time and O(1) space
#include<bits/stdc++.h> using namespace std; int Duplicate(int a[],int n){ int i; int c=1; for(i=0;i<n;i++){ if(a[i]==a[i+1]){c++;continue;} if(c>1) cout<<a[i]<<" occured: "<<c<<" times"<<endl; c=1; } } int main(){ int t; cin>>t; while(t--){ int n; cin>>n; int a[n]; for(int i=0;i<n;i++) cin>>a[i]; sort(a,a+n); Duplicate(a,n); } }
#include <iostream>
#include<map>
using namespace std;
int main()
{
int arr[]={1,1,1,1,4,6,4,7,4};
int count=1;
map<int,int> mymap;
try
{
if(sizeof(arr)/sizeof(arr[0])<=1)
{
throw 1;
}
}
catch(int x)
{
cout<<"array size is not be 1";
return 0;
}
for(int i=0;i<(sizeof(arr)/sizeof(arr[0]));i++)
{
for(int j=i;j<(sizeof(arr)/sizeof(arr[0]));j++)
{
if(arr[i]==arr[j+1])
{
count++;
}
}
if(mymap.find(arr[i])!=mymap.end())
{
auto it = mymap.find(arr[i]);
if((it)->second<=count)
(it)->second=count;
count=1;
}
else if(count)
{
mymap.insert(pair<int,int>(arr[i],count));
count=1;
}
}
for(auto it=mymap.begin();it!=mymap.end();it++)
{
cout<<it->first<<"->"<<it->second<<endl;
}
return 0;
}
Expected Output:
1->4
4->3
6->1
7->1