Skip to content

Instantly share code, notes, and snippets.

@juanfal
Created January 8, 2024 17:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save juanfal/9df45a63431541f156659ad06dcf2922 to your computer and use it in GitHub Desktop.
Save juanfal/9df45a63431541f156659ad06dcf2922 to your computer and use it in GitHub Desktop.
m biggest numbers and their positions
// x3.mbiggest.cpp
// juanfc 2024-01-08
// Without open array
//
#include <iostream>
#include <array>
using namespace std;
const int MAXDIFNUMS = 50;
const int MAXREPETIT = 10;
typedef array<int, MAXREPETIT> TPoss;
struct TNum {
int num;
TPoss pos;
};
typedef array<TNum, MAXDIFNUMS> TSeq;
void addNumbers(TSeq& seq, int m);
void displayNumbers(TSeq seq);
void init(TSeq& seq);
int main()
{
TSeq seq;
init(seq);
int m = 5;
addNumbers(seq, m);
displayNumbers(seq);
return 0;
}
int posn(TSeq seq, int n);
int posMin(TSeq seq);
void initPos(TPoss& poss);
int lenSeq(TSeq seq);
void writeFirstTime(TSeq& seq, int i, int n, int pos);
void addPos(TSeq& seq, int i, int pos);
void addNumbers(TSeq& seq, int m)
{
int cnt = 0;
int n;
while (cin >> n and n != 0) {
++cnt;
int pFound = posn(seq, n);
if (pFound == -1) { // not in
int currLen = lenSeq(seq);
if (currLen < m)
writeFirstTime(seq, currLen, n, cnt);
else {
int pmin = posMin(seq); // always >= 0 here
if (seq[pmin].num < n) {
writeFirstTime(seq, pmin, n, cnt);
}
}
} else {
addPos(seq, pFound, cnt);
}
}
}
int lenSeq(TSeq seq)
{
int i = 0;
while (i<seq.size() and seq[i].num != 0)
++i;
return i;
}
void addPos(TSeq& seq, int i, int pos)
{
int ii = 0;
while (seq[i].pos[ii] != 0)
++ii;
seq[i].pos[ii] = pos;
}
void writeFirstTime(TSeq& seq, int i, int n, int pos)
{
seq[i].num = n;
initPos(seq[i].pos);
seq[i].pos[0] = pos;
}
int posMin(TSeq seq)
{
int i = 1, pos = 0;
while (i<seq.size() and seq[i].num != 0) {
if (seq[i].num < seq[pos].num)
pos = i;
++i;
}
return pos;
}
void initPos(TPoss& poss)
{
for (int i = 0; i < poss.size(); ++i)
poss[i] = 0;
}
int posn(TSeq seq, int n)
{
int i = 0;
while (i<seq.size() and seq[i].num != 0 and seq[i].num != n)
++i;
if (i == seq.size() or seq[i].num != n)
i = -1;
return i;
}
void displayNumbers(TSeq seq)
{
int i = 0;
while ( seq[i].num != 0) {
cout << seq[i].num << ": ";
int j = 0;
while (seq[i].pos[j] != 0)
cout << seq[i].pos[j++] << " ";
cout << endl;
++i;
}
}
void init(TSeq& seq)
{
for (int i = 0; i < seq.size(); ++i) {
seq[i].num = 0;
initPos(seq[i].pos);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment