r/cprogramming • • Feb 12 '24

How to printf the winner of a random number generator?

Hi there, I'm new to C programming and programming in general.

I'm trying to use a random number generator sorta as coin flip. I'm making a program where two teams face off and I'm confused on how to use the number to determine the winner. The teams are user input which is where I think I'm getting confused.

0 Upvotes

4 comments sorted by

2

u/Bitwise_Gamgee Feb 12 '24

Since others have already done the whole "code vomit" routine, I'll offer a more succinct solution:

/* Boring preamble */
srand(time(NULL));
(rand() % 2 == 0) ? printf("Team 1 wins!\n") : printf("Team 2 wins!\n");

/*the rest*/

Essentially, we're seeding the random generator and then flipping a coin, if it is divisible by two (even), Team 1 wins, otherwise Team 2 wins.

It doesn't need to be any more complicated.

1

u/Away-Fig-1207 Feb 12 '24

This is very helpful, thank you! 🙏

0

u/thebatmanandrobin Feb 12 '24 edited Feb 12 '24

Well if it's just a coin flip, you have the user enter something like a 1 or 0 for heads or tails. Then just do a random generation between 0 and 1, where 1 is heads and 0 is tails.

So something like this:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(int argc, char** argv)
{
    int choice; // the users choice, 1 for heads, 0 for tails
    int flip; // the coin
    srand(time(NULL)); // generate seed

    printf("Enter '1' for heads, or '0' for tails: ");
    scanf("%d", &choice);

    flip = rand() % 2; // will be 0 or 1
    if (flip == 1) {
        printf("The coin was heads\n");
    } else {
        printf("The coin was tails\n");
    }

    if (flip == choice) {
        printf("You won the toss!\n");
    } else {
        printf("You lost the toss!\n");
    }

    return 0;
}

This is, of course, an extremely simple example and will need to be incorporated in a way into whatever it is you're doing, it's also not "secure" because it relies on the user entering exactly a 1 or a 0, but since you're just learning, this should help you get going.

Also, the rand function is a PRNG (pseudo random number generator), so it's likely that the "coin flip" (e.g. flip = rand() % 2;) will generate a similar coin flip on successive runs.

If you want it to be a little more "equal" and less bias in its RNG, you can get an average or total, and the flips with the most total could be considered the "winner" .. so something like this:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(int argc, char** argv)
{
    int choice; // the users choice, 1 for heads, 0 for tails
    int heads = 0;
    int tails = 0;
    int flip = -1;
    srand(time(NULL)); // generate seed

    printf("Enter '1' for heads, or '0' for tails: ");
    scanf("%d", &choice);

    for (int i = 0; i < 101; ++i) {
        // 100 "flips" should normalize the results better. You could do more, but this
        // seems like a reasonable amount given that you're just learning. Also, note
        // that we're doing 101 "flips", this is to avoid the chance that it's exactly
        // a 50/50 flip. So one of them will always be more likely to come out as the winner.
        
        if (rand() % 2 == 1) {
            ++heads;
        } else {
            ++tails;
        }
    }

    if (heads > tails) {
        flip = 1; // more heads than tails, so heads won
    } else {
        flip = 0; // more tails than heads, so tails won
    }

    if (flip == 1) {
        printf("The coin was heads\n");
    } else {
        printf("The coin was tails\n");
    }

    if (flip == choice) {
        printf("You won the toss!\n");
    } else {
        printf("You lost the toss!\n");
    }

    return 0;
}

There's well more you could do with this, and again, this is a very simple example, but should hopefully get you in the direction you're trying to go.

-2

u/nerd4code Feb 12 '24

The team data and how it’s selected are different concepts.

Usually for indexing you’d do

index = random()%nteams

(but that won’t necessarily give you evenly-distributed random numbers, unless random is guaranteed to give you an even spread given a particular argument) and then you’d have some array or list of ≥2 teams wherein teams[index] gives you the team info.

In Python, you’d probably do a class for the team data type, then aim list entries at instances of that class. In C/++ you’d do a struct(/class) for the data type and an array for the team list—

struct TeamData {
	uintmax_t points;
	char name[128];
};
struct TeamData teams[however_many] = {0};

or something along those lines; if you have arbitrarily large elements you might

/* (C, primarily:) */
struct TeamData {uintmax_t points; char name[];};
struct TeamData *teams[however_many];
for(unsigned i=0, n=countof(teams); n--;) {
	if(!(teams[i] = TeamData_create(teamName))) {
		while(i--) TeamData_destroy(teams[i]);
		return ENOMEM;
	}
}
…
for(unsigned i = countof(teams); i--;)
	TeamData_destroy(teams[i]);

// C++:
struct TeamData {
	std::uintmax_t points; std::string name;
	inline TeamData(const string &name_) : points(0), name(name_) {}
} *teams[N];
for(unsigned i=0; i < N; i++)
	try {teams[i] = new TeamData(teamNames[i]);}
	catch {
		while(--i) delete teams[i];
		throw;
	}
…
for(unsigned i = N; i--;)
	delete teams[i];

or

/* C: */
struct TeamData {uintmax_t points; char name[128];};
struct TeamData *teams;
assert(however_many <= SIZE_MAX / sizeof *teams);
teams = calloc(however_many * sizeof *teams);
if(!teams) return ENOMEM;
…
free(teams);

// C++
struct TeamData {…} *teams = new TeamData[however_many];
…
delete[] teams;

or some combination of the two.

In Java,

class TeamData {
	long points; String name;
	…
}
…
final TeamData[] teams = new TeamData[nteams];
for(int i = 0; i < teams.length; i++)
	teams = new TeamData();

Iiiiiiin JS, you’d probably do an object array:

const teams = [];
for(let i=0, n=however_many; n--;)
	teams[i++] = {name: "", points: 0};

Etc.