On 2005-12-07,

vi**********@mailinator.com <vi**********@mailinator.com> wrote:

well i got it to work. i need some help with the output tho.

say if a number repeats, how can i get it to display only once

but still display a correct repetition count right now its

outputting something like this:

Number Count

8 3

8 3

8 3

1 1

but i wanna fix so it displays this:

Number Count

8 3

1 1

heres the code

#include <iostream>

using namespace std;

const int size = 7;

int main()

{

int numbers[size] = {1,6,8,5,4,5,6};

int temp, counter, index, numorder, times, appears = 0, me;

cout << "This program will read in numbers and display them in

ascending order." << endl;

cout << "It will also count the number of times a number is

repeated." << endl;

cout << endl;

for (counter = 0; counter < 7; counter++)

{

for (index = 0; index < size - counter; index++)

{

if (numbers[index] > numbers[index + 1])

{

temp = numbers[index];

numbers[index] = numbers[index+1];

numbers[index+1] = temp;

}

}

}

for (numorder = 0; numorder < size; numorder++)

{

cout << numbers[numorder] << " ";

}

cout << endl;

cout << "\nNumber Count" << endl;

for (int times = 0; times < size ; times++)

{

appears = 0;

for (int me = size - 1 ; me >= 0; me--)

{

if (numbers[times] == numbers [me] )

{

appears++;

}

}

cout << numbers[times] << " " <<

appears << endl;

}

You are counting the total appearances every time a number

appears. You only need to count once for each number. It will

save time, and produce the index you need, to count from

position [times] instead of from the back of the array.

For example, assuming my list is 1, 1, 4, 5, 5:

I see a one, so I count from there to the end of the ones. I

print the output. 1, 2. I then start looking past the end of the

ones, at the four. And so on.

In psuedocode:

set i to 0.

loop1: if i is not less than size, break from loop1.

set j to i.

loop2: if j is not less than size, or

numbers[i] <> number[j], break from loop2.

increment j by one.

Loop.

print numbers[i], (j-i+1).

set i to j+1;

It translates into two or three lines of C++ code.

For fun, it can be solved with std::equal_range.

std::pair<const int*, const int*> p(0, numbers);

while (p.second != numbers+size) {

p = std::equal_range(p.second, numbers+size, *p.second);

std::cout << *p.first << ": " << p.second-p.first << '\n';

}

--

Neil Cerutti