Skip to content

feat: risiko exercise implemented #301

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 60 additions & 0 deletions exercises/risk-risiko.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,63 @@
M 3 vs 3 => blue win
O 2 vs 1 => red win
*/

#define EXIT_SUCCESS 0
#include <iostream>
#include <stdlib.h>
#include <time.h>

using namespace std;

void swap(int *A, int i, int j){

int tmp = A[i];
A[i] = A[j];
A[j] = tmp;

}

void sort(int *A, int n){

for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){

if(A[i] > A[j]) swap(A,i,j);
Comment on lines +49 to +51
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Immagino la task non riguardasse implementare un buon algoritmo di ordinamento, ma non posso non notare che bastano due cambiamenti per migliorare le prestazioni.
In questo momento ci sono dei casi in cui $i = j$, per cui compari un elemento con sè stesso, Per di più, ogni volta scorri l'array per intero nel loop interno.

// Variante sort
void sort(int *A, int n) {
  for (int i = 0; i < n; i++) {
    for (int j = i + 1; j < n; j++) {
      // Se il nuovo elemento A[j] è più grande di A[i]
      // allora scambiamo i due elementi 
      // per mettere A[j] in cima (a sinistra)
      if (A[j] > A[i]) swap(A, i, j);
    }
  }
}

}
}

}
int main(){

srand(time(NULL));

int RedRolls[3];
int BlueRolls[3];

for(int i = 0; i < 3; i++){

RedRolls[i] = int(rand()%6) + 1;
BlueRolls[i] = int(rand()%6) + 1;

}

sort(RedRolls,3);
sort(BlueRolls,3);

cout << "Red Dices:"<<endl;
cout << RedRolls[0] << " (N)"<< endl;
cout << RedRolls[1] << " (M)"<< endl;
cout << RedRolls[2] << " (O)"<< endl;

cout << "Blue Dices:"<<endl;
cout << BlueRolls[0] << " (N)"<< endl;
cout << BlueRolls[1] << " (M)"<< endl;
cout << BlueRolls[2] << " (O)"<< endl;

cout << " R B"<<endl;
cout << "N "<< RedRolls[0] <<" vs "<< BlueRolls[0] << " => " << (BlueRolls[0] >= RedRolls[0] ? "Blue wins" : "Red Wins")<< endl;
cout << "M "<< RedRolls[1] <<" vs "<< BlueRolls[1] << " => " << (BlueRolls[1] >= RedRolls[1] ? "Blue wins" : "Red Wins")<< endl;
cout << "O "<< RedRolls[2] <<" vs "<< BlueRolls[2] << " => " << (BlueRolls[2] >= RedRolls[2] ? "Blue wins" : "Red Wins")<< endl;

return EXIT_SUCCESS;
}