Dynamic array with random value - Sorting + value problem

I have to make a program that generates an array with random values < 50, finds all groups of 3 numbers whose sum is divisible by 25, and then outputs those groups of numbers in ascending order.

Problems:
1) The code does compile but sometimes generates up numbers that are > 50.
2) I can't use the <algorithm> header => tried to use bubble sort but the array just won't sort itself.

Any help would be greatly appreciated!

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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>
#include <cmath>
#include <cstdlib>

using namespace std;

int* genNumbers (int N) {
    int* a = new int[N];
    for (int i = 0; i < N; i++) {
        a[i] = (rand() % 50);
    }
    int temp = 0;
    for (int i = 0; i < N; i++) {
        if (a[i] > a[i+1]) {
            temp = a[i];
            a[i] = a[i+1];
            a[i+1] = temp;
        }
    }
    return a;
}

void printNumbers(int *a, int N) {
    for (int i = 0; i < N; i++) {
        for (int j = N-1; j > i; j--) {
            for (int k = N; k > j; k--) {
                if ((a[i] + a[j] + a[k]) % 25 == 0) {
                    cout << a[i] << " " << a[j] << " " << a[k] << endl;
                }
            }
        }
    }
}

//system testcase
int main() {
    int seed = 1;
    srand(seed);
    int n;
    cin >> n;
    int *a = genNumbers(n);
    printNumbers(a, n);
}
Last edited on
closed account (E0p9LyTq)
You are going out of bounds with your array.

If N = 12: i = 11 on the final loop, lines 13-18. i+1 = 12, which accesses the 13th element of a 12 element array.

And where are you releasing your heap memory you allocated in genNumbers()? You have a potential memory leak.
to sort you may want to look into sort
http://www.cplusplus.com/reference/algorithm/sort/
include algorithm
call std::sort(a.begin(),a.end())
Topic archived. No new replies allowed.