Created
March 6, 2015 23:08
-
-
Save dakk/ffeb0959da24fb149272 to your computer and use it in GitHub Desktop.
Array exit sequence with recursion
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <malloc.h> | |
#define N 9 | |
#define M 5 | |
void print_ar (int *a, int n) | |
{ | |
for (int i=0;i<n;i++) printf ("%d ", a[i]); | |
printf ("\n\n"); | |
} | |
/** | |
Supponiamo che N persone abbiano deciso di competere per il premio sistemandosi in circolo ed eliminando la persona che occupa il posto M, stringendosi al crescere del numero degli | |
eliminati. Il problema consiste nel determinare chi è il vincitore o, più in generale, nel determinare l’ordine con cui le persone vengono eliminate. Ad esempio, siano dati N=9 e M=5, | |
le N persone siano numerate 1 2 3 4 5 6 7 8 9. Il programma leggerà i valori di N e M e stamperà la sequenza risultante 5 1 7 4 3 6 9 2 8. */ | |
void exitseq (int *ar, int n, int pos, int irem, int i) | |
{ | |
if (n == 0) | |
return; | |
if (i==irem-1 && ar[pos] != -1) | |
{ | |
printf ("%d ", ar[pos]); | |
ar[pos] = -1; | |
return exitseq (ar, n-1, (pos+1) % N, irem, 0); | |
} | |
else if (ar[pos] != -1) | |
return exitseq (ar, n, (pos+1) % N, irem, i+1); | |
else | |
return exitseq (ar, n, (pos+1) % N, irem, i); | |
} | |
int main () | |
{ | |
int *ar = (int *) malloc (sizeof(int) * N); | |
// Inizializzo con numeri a caso | |
for (int i=0; i<N; i++) ar[i] = i+1; | |
print_ar (ar, N); | |
exitseq (ar, N, 0, M, 0); | |
printf ("\n"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment