poker program, is there a more efficent way of generating a deck of cards?

greetings everybody,

i'm writing a simple console program in C++, i'm teaching myself so excuse any bad coding practices :-) and please point them out, cheers.

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
void generate_deck(card * deck)
{
	for (int i = 0; i < 52; i++) //assigns the 52 cards their values
	{
		if (i < 13)
		{
			deck[i].set_card_number(i+1);
			deck[i].set_card_suit('h');
		}

		else if (i >= 13 && i < 26)
		{
			deck[i].set_card_number(i-12);
			deck[i].set_card_suit('d');
		}

		else if (i >= 26 && i < 39)
		{
			deck[i].set_card_number(i-25);
			deck[i].set_card_suit('s');
		}

		else if (i >= 39 && i < 52)
		{
			deck[i].set_card_number(i-38);
			deck[i].set_card_suit('c');
		}

		else
			cout << "ERROR IN generate_deck" << endl;
	}
}


i was wondering if there is a more efficient way of writing this as it seems like a crude method. i believe this code to be self-explanatory but if there's anything that's not clear please point it out and i'll do my best to explain.

cheers in advance, Sam Sutton.
Looks good to me.

Whenever you find yourself doing the same thing (with small variations) multiple times, you might want to think of ways to combine it.

1
2
3
4
5
6
7
8
9
10
void generate_deck( char *deck )
{
	char suits[] = "hdsc";

	for (int i = 0; i < 52; i++)
	{
		deck[ i ].set_card_number( (i %13) +1 );
		deck[ i ].set_card_suit( suits[ i /13 ] );
	}
}

Enjoy!
thanks mate, that's exactly what i was looking for.
could you post the class or structure?
Topic archived. No new replies allowed.