Lottery

Posts 1–5 of 5 · Page 1 of 1
Lottery
Hey, can somebody help me to create lottery where is 1-39 numbers and it will pick 7 numbers and it will check that any picked numbers are not doubled.
Code:
#include "stdafx.h"
#include <stdio.h>     
#include <stdlib.h>    
#include <time.h> 
#include <string>
#include <vector>
const int max_lotto_numbers = 39;
const int max_lotto_pulls = 7;

void generate_lotto_numbers(std::vector<int>& v)
{
	v.clear();
	int i = 0;
	while (i < max_lotto_pulls)
	{
		int lottoNumber = rand() % max_lotto_numbers + 1;
		for (int c = 0; c < i; c++)
			if (lottoNumber == v[c])
				continue;
		v.push_back(lottoNumber);
		i++;
	}
}

void int_vector_to_lotto_string(std::vector<int>& v, std::string& s)
{
	s = std::to_string(v[0]) + " " +
		std::to_string(v[1]) + " " +
		std::to_string(v[2]) + " " +
		std::to_string(v[3]) + " " +
		std::to_string(v[4]) + " " +
		std::to_string(v[5]) + " " +
		std::to_string(v[6]);
}

int main()
{
	srand(time(NULL));
	std::vector<int> v;
	std::string str;
	for (int i = 0; i < 99; i++)
	{
		generate_lotto_numbers(v);
		int_vector_to_lotto_string(v, str);
		printf("%s\n", &str[0]);
	}
	return 0;
}
Python alternative.
Code:
import random

def generate_numbers():
  return random.sample(range(1,39), 7)
  
def main():
  print(str(generate_numbers()))
  
main()
Quote Originally Posted by MikeRohsoft View Post
Code:
#include "stdafx.h"
#include <stdio.h>     
#include <stdlib.h>    
#include <time.h> 
#include <string>
#include <vector>
const int max_lotto_numbers = 39;
const int max_lotto_pulls = 7;

void generate_lotto_numbers(std::vector<int>& v)
{
	v.clear();
	int i = 0;
	while (i < max_lotto_pulls)
	{
		int lottoNumber = rand() % max_lotto_numbers + 1;
		for (int c = 0; c < i; c++)
			if (lottoNumber == v[c])
				continue;
		v.push_back(lottoNumber);
		i++;
	}
}

void int_vector_to_lotto_string(std::vector<int>& v, std::string& s)
{
	s = std::to_string(v[0]) + " " +
		std::to_string(v[1]) + " " +
		std::to_string(v[2]) + " " +
		std::to_string(v[3]) + " " +
		std::to_string(v[4]) + " " +
		std::to_string(v[5]) + " " +
		std::to_string(v[6]);
}

int main()
{
	srand(time(NULL));
	std::vector<int> v;
	std::string str;
	for (int i = 0; i < 99; i++)
	{
		generate_lotto_numbers(v);
		int_vector_to_lotto_string(v, str);
		printf("%s\n", &str[0]);
	}
	return 0;
}
Keep in mind that rand() only generates up to RAND_MAX, which could be as low as 32767. If you need larger numbers than this consider using any of the alternatives found here
too long, you can write a smaller programm easeliy
Posts 1–5 of 5 · Page 1 of 1

Post a Reply

Similar Threads

Tags for this Thread

None

Talk with us