A program to calculate the number of predecessors.

I'm trying to find the numbers in an array that are smaller or equal than each number in the array. I want to be able to check for numbers to the left or to the right.
Suppose the array is a[8]={1,4,8,6,3,2,6,7};
then for a[6] i would have 2,3,6 smaller or equal than a[6]=6 so 3 numbers.

I'm thinking to loop thru the array and check for each number, and make a secondary array filled with zeroes and increment each position to reflect the number of smaller or equal.
int b[8]={0,0,0,0,0,0,0,0,0};
b should be {0,1,2,0,0,0,3,0}

this is what i have so far.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
using namespace std;

int main(){
		
	int a[8]={1,4,8,6,3,2,6,7};
	int b[8]={0};
	int n = 8;
	
	for (int i=0;i<n;i++)
		cout<<b[i]<<endl;
	
	for(int i=1;i<n;i++){
		int t=0;
		while(a[i-t-1]<=a[i-t])
		{	
			b[i++];
			t++;
		}		
	}
	
	for (int i=0;i<n;i++)
	cout<<b[i]<<endl;
	return 0;
}

//the program loops f orever
Last edited on
I want to be able to check for numbers to the left or to the right.
What do you mean?

Suppose the array is a[8]={1,4,8,6,3,2,6,7};
then for a[6] i would have 2,3,6 smaller or equal than a[6]=6 so 3 numbers.
What about 1 and 4? Are you looking for the quantity of numbers, or for the numbers themselves?
It should check numbers to the left of each element. It can't go over 8 because 8 is larger than 6
This one works

1
2
3
4
5
6
7
8
9
10
11
12
int a[10] = { 9,4,5,8,10,2,1,3,7,6 };
int b[10] = { 0 }; 
  int pd; 
  for (int i = 1; i < 10; i++) { 
    pd = 0; 
    while (a[i] >= a[i - pd - 1] && pd<i) {
      pd++;
      b[i] = pd;

    }

  }
Last edited on
Topic archived. No new replies allowed.