arrays problem. could learn something too...

HI! figured out problem while posting. for educational purpose i will still post
its a good code

This program chooses cards from a 52 indexed array.
It makes sure it doesn't pick the same card in the array.
If you don't know how to already pick something unique every time you rune the loop, stay tuned for this code.

Also a quick helper before you ask how it works. The array is only 0s and 1s. To determine which ones have already been chose, it runs a while loop in a function(select_new). The while loops checks to see if the current index is set to true or false. After checking if true, it increments the index going to the next one. It will do this in till it finds a card that is false(0).

after doing this it decrements the random number chose in till it arrives to the chosen card. After arriving to the chosen card it checks one more time to make sure it isn't already used. Then changes its value to true, and it then returns i.

Extra information

using g++ compiler from gnu linux distro(ubuntu)
in kate workpad
i recommend these alot.


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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#include <iostream>
#include <string>
#include <stdlib.h>
#include <math.h>
#include <time.h>
using namespace std;

string rank[13] = {"Ace", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "King"};
string suit[4] = {"Diamonds", "Hearts", "Spades", "Clubs"};

void draw_card();
int card_remaining = 52;
int cards[52];
int select_new(int n);
int rand(int n);

int main()
{
int n, i;

srand(time(NULL));

while(1)
{

cout << "Enter no. of cards to draw (0 to exit): ";
cin >> n;
if (n == 0)
break;

for( i = 1; i <= n ; i++)
draw_card();

}
return 0;
}

void draw_card()
{
int r, s;
int n, card;

n = rand(card_remaining--);
card = select_new(n);

r = card % 13;
s = card / 13;

cout << rank[r] << " of " << suit[s] << endl;

}

int select_new(int n)
{
int i = 0;

while(cards[i])
i++;

while (n-- > 0)
{
i++;
while(cards[i])
i++;
}

cards[i] = true;

return i;
}

int rand(int n)
{
return rand() % n;
}



Last edited on
http://www.cplusplus.com/reference/algorithm/random_shuffle/

EDIT: Unless this is a basic programming exercise, of course.
Last edited on
Topic archived. No new replies allowed.