Click here to Skip to main content
15,890,717 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I finally finished this code for an assignment but there is one problem: for the output "Positions:" I want it to output every position where the minimum occurs. However, my code only outputs the last position of the minimum in each randomly generated array (size 20).

C++
#include <iostream>
#include <iomanip>
using namespace std;

double random(unsigned int &seed);
unsigned int seed = (unsigned int)time(0);
const int SIZE = 20;

void print_array (int a[]);
void fill_array (int a []);
int find_min (int [], int);

int main ()
{
    int arr[SIZE];
    cout << "Arrays: \n";
    fill_array(arr);
    print_array(arr);
    
    int pos = find_min(arr, SIZE); 
    int minimum = arr[pos];
    
    cout << "Min is: " << minimum << endl;
    cout << "At position: " << pos +1 << endl; 
         
    return 0;
}

double random(unsigned int &seed)
{
    const int MODULUS = 15749;
    const int MULTIPLIER = 69069;
    const int INCREMENT = 1;
    seed = ((MULTIPLIER*seed)+INCREMENT)%MODULUS;
    return double(seed)/MODULUS;
}

void fill_array (int a [])
{
    for (int i = 0; i < SIZE; ++i)
        a[i] = 0 + (10 * (random(seed)));
}

int find_min (int arr[], int n)
{
    int min = arr[0]; 
    int index = 0;
    
    for (int i = 1; i < n; ++i)
        if (arr[i] < min) 
        {
            index = i;
            min = arr[i];
        }
    return index;
}

void print_array (int a[])
{
    for (int i = 0; i <SIZE; ++i)
        cout << setw(3) << a[i];
    cout << endl;
}


What I have tried:

I don't understand how to add more position values since the array size is 20 and no matter what, the minimum will be printed at least twice.
Posted
Updated 24-Sep-17 9:03am

1 solution

Write another function: FindNext.
Hand it the array and it's size, the value to look for, and the index to start at.
If you find another example, return the index. If you don't, return -1.
Then loop calling that and printing minima until it can't find any more.

But this is your homework, so I'll give you no code!
 
Share this answer
 
Comments
Member 13426989 24-Sep-17 15:55pm    
Hello, thank you so much for your response! I'm still confused as to where to define the new function and to loop it (I think in the int find_min function?) also because I am trying to avoid redundancy and the addition of extra functions, if you may, would you mind directing me to where the addition of this new function would work best? And then I will loop it
OriginalGriff 24-Sep-17 16:13pm    
In main. Call find_min first, then loop using the result.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900