This is the complete question:-
All Indices Of Array
You are given a number n, representing the count of elements.
You are given n numbers.
You are given a number x.
You are required to find the all indices at which x occurs in array a.
Return an array of appropriate size which contains all indices at which x occurs in array a.
Sample Input
6
15
11
40
4
4
9
Sample Output
3
4
This is my code:-
#include<iostream>
using namespace std;
int* allIndices(int arr[],int n,int x,int idx,int* fsf){
if(idx==n){
int *q=new int[*fsf];
return q;
}
if(arr[idx]==x){
int* iarr=allIndices(arr,n,x,idx+1,fsf+1);
iarr[*fsf]=idx;
return iarr;
}
else{
int* iarr=allIndices(arr,n,x,idx+1,fsf);
return iarr;
}
}
int main(){
int n;
cin>>n;
int *p = new int[n];
for(int i=0;i<n;i++)
cin>>p[i];
int x;
cin>>x;
int k=0;
int *y=allIndices(p,n,x,0,&k);
for(int i=0;i<k;i++){
cout<<y[i]<<endl;
}
}
This code must be printing an array of index positions but its not printing anything ....
please help!
This does the job quite fine. You might have overcomplicated it a bit.
#include <iostream>
using namespace std;
int* alLIndices(int arr[], int n, int x){
int *y = new int[n];
for(int i=0; i<n; i++){
if(arr[i] == x){
y[i] = i;
}
}
cout<<"Number "<<x<<" occurs at indices: "<<endl;
for(int i=0; i<n; i++){
cout<<y[i]<<endl;
}
}
int main() {
int n;
cout<<"Enter n: ";
cin>>n;
int *p = new int[n];
cout<<"Enter an array of numbers: "<<endl;
for(int i=0; i<n; i++)
cin>>p[i];
int x;
cout<<"Enter x: ";
cin>>x;
alLIndices(p, n, x);
return 0;
}
You just go through the array and see which element of it is equal to the x that you are searching for. If there is any, then you put the index of that element in a new array which you allocated beforehand. Finally, you print out the array containing those indices.
I was trying to make a program that swaps all the biggest and smallest numbers in an array or a vector. I came up with a program but for some reason I'm not able to debug it to get the problem. Its not printing the vector, neither do I know what the issue is. Can anyone please help me.
Desired Input and Output
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main()
{
int n;
cin>>n; //size input
vector<int> arr;
for(int i=0;i<n;i++) //filling up the vector
{
int input;
cin>>input;
arr.push_back(input);
}
vector<int> arr1=arr; //copying the vector
sort(arr1.begin(), arr1.end()); //sorting the new vector
int i=0,j=n-1,i1=0,j1=n-1; //i and j are for the vector arr & i1 and j1 are for vector arr1
while(i1<j1)
{
if(arr1[i1]==arr[i] && arr1[j1]==arr[j]) //if the first and last number of the sorted vector is found in arr the swap
{
int temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
i1++;
j1--;
i=0; // i and j are set to initial value so that it is checked from the start
j=n-1;;
}
else if(arr1[i1]<arr[i] && arr1[j1]==arr[j]) //if only the biggest place element is found the increase i
{
i++;
}
else if(arr1[i1]==arr[i] && arr1[j1]>arr[j]) //if only the smallest place element is found the decrease j
{
j--;
}
else if(arr1[i1]!=arr[i] && arr1[j1]!=arr[j]) //if none of them are found then increase i and decrease j
{
i++;
j--;
}
}
for(int f=0;f<n;f++) //print the vector
cout<<arr[f]<<" ";
return 0;
}
/*
Sample input 1
6
12 34 87 56 38 98
Sample output 1
98 87 34 38 56 12
Sample input 2
6
8 7 9 2 4 6
Sample output 2
4 6 2 9 8 7
*/
Some help would be really appreciated.
A simpler method would be to make a vector of indexes rather than sorting the vector and trying to find the values in the original vector. For example:
#include <iostream>
#include <algorithm>
#include <vector>
int main()
{
int n;
std::cin >> n;
std::vector<int> arr;
std::vector<int> indexes;
for (int i = 0; i < n; i++)
{
int input;
std::cin >> input;
arr.push_back(input);
indexes.push_back(i);
}
std::sort(indexes.begin(), indexes.end(), [&](int a, int b) {return arr[a] < arr[b]; });
for (int i = 0, j = n - 1; i < n / 2; i++, j--)
{
std::swap(arr[indexes[i]], arr[indexes[j]]);
}
for (int f = 0; f < n; f++)
{
std::cout << arr[f] << " ";
}
return 0;
}
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
I was not really sure what this order of printing is called hence called it strange.
Consider the following sample example:
1 3 5
2 6 7
Expected output:
1,2
1,6
1,7
3,2
3,6
3,7
5,2
5,6
5,7
Or this example:
1 2 3
4 5 6
7 8 9
output:
1,4,7
1,4,8
1,4,9
1,5,7
1,5,8
1,5,9
... and so on.
I have analyzed that the number of possible combinations will be rows^columns for any given matrix.Here is my solution:
#include <iostream>
#include <vector>
#include <string>
#include <cstdlib>
#include <cstdio>
using namespace std;
void printAllPossibleCombinations(int** a, int h, int n, string prefix)
{
if (h == 0)
{
for (int i = 0; i < n; i++)
{
cout << prefix << a[0][i] << endl;
}
}
else
{
for (int i = 0; i < n; i++)
{
string recursiveString = prefix;
recursiveString.append(to_string(a[h][i]));
recursiveString.append(1, ',');
printAllPossibleCombinations(a, h-1, n, recursiveString);
}
}
}
int main()
{
int **a;
int m,n,k;
cout<<"Enter number of rows: ";
cin>>m;
a = new int*[m];
cout<<endl<<"Enter number of columns: ";
cin>>n;
for(int i=0;i<m;i++)
{
a[i] = new int [n];
}
for(int i=0;i<m;i++)
{
for(int j = 0; j < n;j++)
{
cout<<"Enter a[" << i << "][" << j<< "] = ";
cin>>a[i][j];
cout<<endl;
}
}
printAllPossibleCombinations(a, m-1, n, "");
return 0;
}
Is there an easy and more optimized way of doing it? Please suggest.
Thank You
As you said, there are rows^columns things to physically print out in the algorithm so you can't do better than an O(rows^columns) algorithm and your algorithm is as optimal as you'll get.
I am getting time limit exceeded in hotels from spoj .
Here 's my code:
int main()
{
long long n,m;
scanf("%lld",&n);
scanf("%lld",&m);
long long a[300005],dp[300005];
for(int i=0;i<n;i++) scanf("%lld",&a[i])
for(int i=1;i<n;i++) a[i]+=a[i-1];
for(int i=n-1;i>=0;i--)
{
if(a[i]<m){
dp[0] = a[i];
break;
}
}
for(int i=1;i<n;i++)
{
long long x = a[i-1];
for(int j=i;j<n;j++)
{
a[j]-=x;
}
for(int j=n-1;j>=i;j--)
{
if(a[j]<=m){
dp[i] = a[j];
break;
}
}
}
long long max_=0;
for(int i=0;i<n;i++)
{
max_ = max(max_,dp[i]);
}
printf("%lld\n",max_);
return 0;
}
Explaination:
First of all, i calculated all the values in the array "a" by summing with previous values.Then, calulated the maximum value less than equal to "m" in dp array.Then, i started subtracting from the previous minus the current value from each element of array and stored value in dp array.So,max of dp array would give me the answer.
for e.g. :
n=5,m=12;
2 1 3 4 5
My array 'a':
2 3 6 10 15
then after 2nd pass :
2 1 4 8 13
then after 3rd pass :
2 1 3 7 12
Here's the code in action:
Ideone
This problem has complexity O(n).
#include <iostream>
using namespace std;
int a[300013];
int main(){
int n,m;
scanf("%d%d",&n,&m);
for(int i=0; i<n; i++) scanf("%d",&a[i]);
long long sumNow = 0;
long long maxAns = 0;
int left=0,right=-1;
while(right!= n-1){
right++;
sumNow+=a[right];
while(sumNow>m){
sumNow-=a[left];
left++;
}
maxAns = max(maxAns,sumNow);
}
printf("%lld", maxAns);
return 0;
}