Mega-Sena, the most important lottery in Brazil: Simulation, betting and learning.

Anderson C. Gaudio
Federal University of Espírito Santo (ES-Brazil)

Join the Conversation #WolframTechConf

Initialization

(* Hidden data (Initialization cell) *)
Remove["Global`*"]//Quiet

(* Set the location of external data *)
SetNameAndLocationOfExternalData[null___]:=Module[{},

Print["\n"];
Print["Step 1: Set the location of external data"];
Print["===================================="];
Pause[1];

(* Mega-Sena *)
(* ========= *)

(* Source of MS results *)
(* Fonte dos resultados da MS *)
Print["Mega-Sena results..."];Pause[1];

MSFileURL="http://www1.caixa.gov.br/loterias/_arquivos/loterias/D_megase.zip";

(* Files related to obtaining MS results  *)
(* Arquivos relacionados à obtenção dos resultados da MS *)
MSZipFile="d_megase.zip";
MSHtmFile="d_mega.htm";
MSGifFile="t2.gif";
MSXlsxFile="d_mega.xlsx";

(* Source of MS Minimum Bet Value *)
(* Fonte do valor da aposta mínima da MS *)
Print["Mega-Sena Minimum Bet Value..."];Pause[1];

MSCostOfaSixNumbersBetURL="http://loterias.caixa.gov.br/wps/portal/loterias/landing/megasena/";

(* IPCA - Broad Consumer Price Index *)
(* IPCA - Índice de Preços ao Consumidor Ampliado *)
(* ============================================== *)

(* Source of the IPCA index table, necessary for monetary updating of the MS premiums *)
(* Fonte da tabela de índices do IPCA, necessários à atualização monetária dos prêmios da MS *)
Print["IPCA index table..."];Pause[1];

IPCAFileURL="http://www.excelcontabilidade.com.br/indice/5/IPCA";

(* Map, population and economic data *)
(* Mapa, população e dados econômicos *)
(* ================================== *)

(* Image of the map of Brazil *)
(* Imagem do mapa do Brasil *)
BRMapOfBrazilIMG=Import["http://estradas.com.br/paginas/mapa.png"];

(* Source of the population of the Brazilian states and the Federal District *)
(* Fonte da população dos estados e do Distrito Federal (DF) *)
Print["Population of the Brazilian states..."];Pause[1];

BRPopulationURL="https://pt.wikipedia.org/wiki/Lista_de_unidades_federativas_do_Brasil_por_popula%C3%A7%C3%A3o";

(* Source of per capita income of states and DF *)
(* Fonte da renda per capita dos estados e do DF *)
Print["Per capita income table..."];Pause[0.5];BRPerCaptaIncomeURL="https://pt.wikipedia.org/wiki/Lista_de_unidades_federativas_do_Brasil_por_renda_per_capita";

(* Source of the economically active population of the states and DF *)
(* Fonte da população economicamente ativa dos estados e do DF  *)
Print["Economically active population table..."];Pause[0.5];BRPopulationEconomicallyActiveURL="http://seriesestatisticas.ibge.gov.br/exportador.aspx?arquivo=PD295_UF_ABS.csv&categorias=Homem_Mulher&localidade=Todas";

Print["End of Step 1"];Pause[1];
]

(* Set transformation rules and converters *)
SetTransformationRulesAndConverters[null___]:=Module[{cost},

Print["\n"];
Print["Step 2: Set transformation rules and converters"];
Print["========================================="];
Pause[1];

(* Rules for converting state names into abbreviations and vice-versa *)
(* Regras para conversão dos nomes dos estados em abreviações e vice-e-versa *)
Print["Rules for converting state names into abbreviations and vice-versa..."];Pause[0.5];
StateToST={"São Paulo"->"SP","Sao Paulo"->"SP","Minas Gerais"->"MG","Rio de Janeiro"->"RJ","Bahia"->"BA","Rio Grande do Sul"->"RS","Paraná"->"PR","Parana"->"PR","Pernambuco"->"PE","Ceará"->"CE","Ceara"->"CE","Pará"->"PA","Para"->"PA","Maranhão"->"MA","Maranhao"->"MA","Santa Catarina"->"SC","Goiás"->"GO","Goias"->"GO","Amazonas"->"AM","Paraíba"->"PB","Paraiba"->"PB","Espírito Santo"->"ES","Espirito Santo"->"ES","Rio Grande do Norte"->"RN","Alagoas"->"AL","Mato Grosso"->"MT","Piauí"->"PI","Piaui"->"PI","Distrito Federal"->"DF","Mato Grosso do Sul"->"MS","Sergipe"->"SE","Rondônia"->"RO","Rondonia"->"RO","Tocantins"->"TO","Acre"->"AC","Amapá"->"AP","Amapa"->"AP","Roraima"->"RR"};

STtoState={"SP"->"São Paulo","MG"->"Minas Gerais","RJ"->"Rio de Janeiro","BA"->"Bahia","RS"->"Rio Grande do Sul","PR"->"Paraná","PE"->"Pernambuco","CE"->"Ceará","PA"->"Pará","MA"->"Maranhão","SC"->"Santa Catarina","GO"->"Goiás","AM"->"Amazonas","PB"->"Paraíba","ES"->"Espírito Santo","RN"->"Rio Grande do Norte","AL"->"Alagoas","MT"->"Mato Grosso","PI"->"Piauí","DF"->"Distrito Federal","MS"->"Mato Grosso do Sul","SE"->"Sergipe","RO"->"Rondônia","TO"->"Tocantins","AC"->"Acre","AP"->"Amapá","RR"->"Roraima"};

(* Real to Dollar conversion factor *)
(* Fator de conversão de Real para Dolar *)
Print["Real to Dollar conversion..."];Pause[0.5];
RealToUSDollarConverter=QuantityMagnitude@CurrencyConvert[Quantity[1,"Reals"],"USDollars"];

(* Minimum cost of a MS bet *)
(* Custo mínimo de uma aposta da MS *)
Print["Minimum cost of a MS bet..."];Pause[0.5];
cost=Import[MSCostOfaSixNumbersBetURL,"Data"];
MSCostOfSixNumbersBet=ToExpression[StringReplace[cost[[2,5,2,1,3,1,2]],","->"."]];

Print["End of Step 2"];Pause[1];
]

(* Set special functions *)
SetSpecialFunctions[null___]:=Module[{},

Print["\n"];
Print["Step 3: Loading special functions"];
Print["========================="];
Pause[1];

(* Format monetary amounts *)
(* Formata quantias monetárias *)
(* =========================== *)
Print["Format monetary amounts..."];Pause[0.5];
ApplyCashFormat::usage="ApplyCashFormat[amount,currencyName] applies currencyName format to amount.
...aplica o formato de currencyName a amount.";

ApplyCashFormat[amount_Real,currencyName_String]:=Module[{value},
If[currencyName=="Real",
value=Row[{"R$ ",NumberForm[amount,{20,2},DigitBlock->3,NumberSeparator->".",NumberPoint->",",ExponentFunction->(Null&)]}];
];
If[currencyName=="Dollar",
value=Row[{"US$ ",NumberForm[amount,{20,2},DigitBlock->3,NumberSeparator->",",NumberPoint->".",ExponentFunction->(Null&)]}];
];
value
];

(* -------------------------------------------------------------------------------- *)

(* IPCA monetary update of amounts in Brazilian Reals *)
(* Atualização monetária de quantias em Reais *)
(* ================================================== *)
Print["IPCA monetary update..."];Pause[0.5];
BrazilianRealCurrencyUpdateByIPCA::usage="BrazilianRealCurrencyUpdateByIPCA[value,month,year,ipca] updates by IPCA the amount value from month/year to the present time.
(...atualiza pelo IPCA a quantia value a partir de month/year até o presente momento.)";

BrazilianRealCurrencyUpdateByIPCA[value_,month_Integer,year_Integer,IPCAdata_List]:=Module[{updatedValue,initialDate,initialPosition},

(* Sets the date relative to the amount value *)
(* Define a data relativa à quantia value *)
initialDate=DateList[{year,month}];

(* Identify the position of the first index in the IPCAdata that will update the value. *)
(* Identifica a posição do primeiro índice no IPCAdata que irá atualizar value *)
initialPosition=Position [IPCAdata,Select[IPCAdata,AbsoluteTime[#[[1]]]==AbsoluteTime[initialDate]&][[1]]][[1,1]];

(* Update value *)
(* Atualiza value *)
updatedValue=value *IPCAdata[[initialPosition,3]]
];

(* -------------------------------------------------------------------------------- *)

(* Combinatorial analysis *)
(* Análise combinatória *)
(* ====================== *)
Print["Combinatorial analysis..."];Pause[0.5];
ProbabilityCalculation::usage="ProbabilityCalculation[n,p] calculates the number of ways a group of n different objects can be combined in subgroups of p of those objects.
(...calcula o número de formas em que um grupo de n objetos diferentes podem ser combinados em subgrupos de p desses objetos.";

ProbabilityCalculation[n_,p_]:=n!/(p!(n-p)!);

(* -------------------------------------------------------------------------------- *)

(* MS betting cost *)
(* Custo das apostas da MS *)
(* ======================= *)
Print["MS betting cost..."];Pause[0.5];
CostOfaMSBet::usage="CostOfaMSBet[n] returns the price to be paid for a MS bet with n numbers.
...retorna o preço a pagar por uma aposta da MS com n números";

CostOfaMSBet[nNumbersInTheBet_Integer]:=
RealToUSDollarConverter ProbabilityCalculation[nNumbersInTheBet,6]MSCostOfSixNumbersBet;

(* -------------------------------------------------------------------------------- *)

(* Probabilities of winning in MS *)
(* Probabilidades de se ganhar na MS *)
(* ================================= *)
Print["Probabilities of winning in MS..."];Pause[0.5];
ChancesOfWinningOnMS::usage="ChancesOfWinningOnMS[numbers,premium\!] returns the probability (1 in chance) of winning in one of the MS available premiums, that is, sena, quina e quadra.
...Retorna a probabilidade (1 em chance) de ganhar em um dos prêmios disponíveis na MS, isto é, sena, quina e quadra";

ChancesOfWinningOnMS[numbers_,premium_]:=Module[{chance},
If[premium=="Sena",
chance=Round[ProbabilityCalculation[60,6]/ProbabilityCalculation[numbers,6]]];
If[premium=="Quina",
chance=Round[ProbabilityCalculation[60,6]/(ProbabilityCalculation[numbers,5]ProbabilityCalculation[60-numbers,1])]];
If[premium=="Quadra",
chance=Round[ProbabilityCalculation[60,6]/(ProbabilityCalculation[numbers,4]ProbabilityCalculation[60-numbers,2])]];
chance
];
Print["End of Step 3"];Pause[1];
]

(* Import and cleaning IPCA data *)
ImportExtractAndCleanIPCAData[null___]:=
Module[{h,g,f,ipca1,ipca2,ipca3,ipca4,ipca5,ipca6,ipca7,line,i,j,year,lastMonth,indexAverage},

Print["\n"];
Print["Step 4: Import and cleaning IPCA data"];
Print["================================="];
Pause[1];

Print["Importing IPCA table..."];Pause[0.5];
(* Import the IPCA table *)
(* Importa a tabela do IPCA *)
ipca1=Import[IPCAFileURL,"Data"];

Print["Cleaning IPCA data..."];Pause[0.5];
Off[General::stop];
Off[ToExpression::sntxi];
(* This four lines cleanup code was created by Bill Simpson in a discussion in the Wolfram Community *)
(* Este código de limpeza de quatro linhas foi criado por Bill Simpson em uma discussão na Comunidade Wolfram *)
(* http://community.wolfram.com/groups/-/m/t/1148737?p_p_auth=WcENzuX4 *)
h[s_]:=If[DigitQ[StringTake[s,1]]||StringTake[s,1]=="-",ToExpression[s],s];
g[s_]:=h[StringReplace[s,{"%"->"",","->"."}]];
f[v_]:=Join[{First[v]},Map[g,Rest[v]]];
ipca2=Map[f,Rest[ipca1[[3]]]];

(* Converts the data gathered in two dimensions into the linear format,in addition to transforming the dates (month/year) into objects.. *)
(* Converte os dados obtidos em duas dimensões para o formato linear, além de transformar as datas (mês/ano) em objetos.  *)
ipca3={};
i=1;
Do[
year=ipca2[[i,1]];
line=Drop[ipca2[[i]],1];
ipca3=Join[ipca3,
Table[{DateObject[{year,j}],line[[j]]},{j,Length[line]}]];
i=i+1,
Length[ipca2]
];

(* Delete the indexes from before March,1996. *)
(* Exclua os índices de antes de março de 1996. *)
ipca4=Drop[ipca3,First@First@Position[ipca3,{1996,2}]];

(* Delete the last  elements of ipca4 ($Failed) *)
(* Elimine os dados finais de ipca4 ($Failed) *)
ipca5=Drop[ipca4,-Length@Position[ipca4,$Failed]];

Print["Making few corrections..."];Pause[0.5];
(* If there is no IPCA index in the month before the current one,use for the current month the average of the last three months *)
(* Se ainda não houver índice IPCA no mês anterior ao atual,utilize para o mês atual a média dos últimos três meses *)
lastMonth=DateObject[DateList[DateObject[]][[;;2]]-{0,1}];
If[ipca5[[Length[ipca5],1]]≠lastMonth,
indexAverage=Mean[{ipca5[[-3,2]],ipca5[[-2,2]],ipca5[[-1,2]]}];
ipca6=Append[ipca5,{lastMonth,indexAverage}],
ipca6=ipca5;
];

(* Add the index zero for the current month *)
(* Adicione 0 índice zero para o mês atual *)
If[DateObject[DateList[DateObject[]][[;;2]]]>Last[ipca6][[1]],
ipca7=Append[ipca6,{DateObject[DateList[DateObject[]][[;;2]]],0.0}]
];

(* Create an extra column in IPCAdata to store accumulated index multipliers *)
(* Crie uma coluna extra no IPCAdata para armazenar os multiplicadores de índices acumulados *)
IPCAdata=ipca7;
AppendTo[IPCAdata[[Length@IPCAdata]],1+IPCAdata[[Length@IPCAdata]][[2]]/100];
For[i=Length[ipca7]-1,i≥1,i--,
AppendTo[IPCAdata[[i]],IPCAdata[[i+1,3]](1+ipca7[[i,2]]/100)]
];
Print["End of Step 4"];Pause[1];
]

(* Import and clean Mega-Sena file *)
ImportExtractAndCleanMSData[null___]:=
Module[{ms0,ms1,ms2,ms3,ms4,ms5,i,nLoops,day,month,year},

Print["\n"];
Print["Step 5: Import and clean Mega-Sena data"];
Print["=================================="];
Pause[1];

(* Download and import MS data file *)
(* Baixe e importe o arquivo de dados da MS *)
(* ======================================== *)

Print["Downloading and importing MS file..."];Pause[0.5];

Off[ExtractArchive::filex];
Off[DeleteFile::fdnfnd];

(* Import and extract MS results *)
(* Importa e extrai os resultados da MS *)
URLSave[MSFileURL,FileNameJoin[{ $TemporaryDirectory,MSZipFile}]];
ExtractArchive[FileNameJoin[{ $TemporaryDirectory,MSZipFile}],$TemporaryDirectory];

(* Converts the data of type HTM to XLSX and then imports into the Mathematica *)
(* Converte os dados do tipo HTM para XLSX e, em seguida, importa para o Mathematica *)
ms0=Import[FileNameJoin[{ $TemporaryDirectory,MSHtmFile}],"Data"];
Export[FileNameJoin[{ $TemporaryDirectory,MSXlsxFile}],ms0];
ms0=Import[FileNameJoin[{ $TemporaryDirectory,MSXlsxFile}],"Data"];

(* Delete all temporary files *)
(* Apaga todos os arquivos temporários *) 
DeleteFile@FileNameJoin[{$TemporaryDirectory,#}]&/@{MSZipFile,MSHtmFile,MSXlsxFile,MSGifFile};

(* Cleans the MS data file *)
(* Limpa o arquivo de dados da MS *)
(* ============================== *)
Print["Cleaning MS data..."];Pause[0.5];
(* Delete the external curly braces *)
ms1=ms0[[1]];
(* Delete number points *)
ms2=StringReplace[#,{"."->""}]&/@ms1[[All]];
(* Adjust the number separators and eliminate double primes *)
ms2a=StringReplace[ms2[[All,1]],","->"."];
ms2b=StringReplace[ms2a,". "->", "];
ms3=ToExpression@ms2b[[All]];
(* Adjust the heads *)

Off[First::normal];
ms4=ms3;
Do[
If[NumberQ@First@ms4[[i]],
(* Adjust the number of elements of each line *)
If[Length[ms4[[i]]]==19,ms4[[i]]=Insert[ms4[[i]],"",{{11},{11}}]];
If[Length[ms4[[i]]]==20,ms4[[i]]=Insert[ms4[[i]],"",11]];
(* Convert some strings to real numbers *)
ms4[[i]]=MapAt[ToExpression,ms4[[i]],{{9},{13},{15},{17},{19},{20},{21}}]
],
{i,1,Length[ms4]}];

i=1;
nLoops=Length[ms4];
(* Put the Brazilian cities and states in the regular rows *)
Do[
i=i+1;

(* Make isolated Brazilian states as lists *)
If[ListQ[ms4[[i]]]==False,
ms4[[i]]={ToString@ms4[[i]]}
];

Do[
(* Make embedded Brazilian states as lists *)
If[NumberQ@First@ms4[[i]]&&ms4[[i,j]]!=""&&ListQ[ms4[[i,j]]]==False,
ms4[[i,j]]={ms4[[i,j]]}
],{j,11,12}];

(* Join isolated Brazilian states to embedded states *)
If[Length[ms4[[i]]]==1,
ms4[[i-1,12]]=Join[ms4[[i-1,12]],ms4[[i]]];
ms4=Delete[ms4,i];
i=i-1;
nLoops=nLoops-1
];

(* Join isolated Brazilian cities and states to embedded cities and states *)
If[Length[ms4[[i]]]==2,
ms4[[i-1,11]]=Append[ms4[[i-1,11]],ms4[[i,1]]];
ms4[[i-1,12]]=Append[ms4[[i-1,12]],ms4[[i,2]]];
ms4=Delete[ms4,i];
i=i-1;
nLoops=nLoops-1
]
,nLoops-1
];

(* Adjust dates *)
For[i=2,i<=Length[ms4],i++,
year=ToExpression@StringTake[ms4[[i,2]],-4];
month=ToExpression@StringTake[ms4[[i,2]],{4,5}];
day=ToExpression@StringTake[ms4[[i,2]],2];
ms4[[i,2]]=DateObject[{year,month,day}]
];

(* Currency update from 1996 to present date *)
(* Atualização de moeda de 1996 até a presente data *)
(* ================================================ *)
Print["Updating currency from 1996 to the present date..."];Pause[0.5];

ms5=ms4;
Do[
(* Update the fields that contain currency data *)
{ms5[[n,9]],ms5[[n,13]],ms5[[n,15]],ms5[[n,17]],ms5[[n,19]],ms5[[n,20]],ms5[[n,21]]}=
Map[ 
BrazilianRealCurrencyUpdateByIPCA[#,ms4[[n,2]][[1,2]],
ms4[[n,2]][[1,1]],IPCAdata]&,
Cases[ms4[[n]],n_Real]
],
{n,2,Length[ms4]}
];

(* Converts Brazilian Reals to American Dollars *)
(* Converte Reais em Dólares americanos *)
(* ============================================ *)
Print["Converting Brazilian Reals to American Dollars..."];Pause[0.5];

MSdata=ms5;
Do[
(* Convert to US Dollars fields that contain currency data *)
{MSdata[[n,9]],MSdata[[n,13]],MSdata[[n,15]],MSdata[[n,17]],MSdata[[n,19]],MSdata[[n,20]],MSdata[[n,21]]}=
Map[ 
Times[RealToUSDollarConverter,#]&,Cases[ms5[[n]],n_Real] 
],
{n,2,Length[ms5]}
];
Print["End of Step 5"];Pause[1];
]

(* Import population and economic data per state of Brazil *)
ImportAndCleanPopulationalData[null___]:=Module[{pop1,pop2,pop3,percap1,percap2,percap3,percap4,percap5,i,active1,active2,active3,active4,x,y},

Print["\n"];
Print["Step 6: Import population and economic data"];
Print["======================================"];
Pause[1];

(* Download and clean population table *)
(* Baixa e limpa a tabela populacional  *)
(* ------------------------------------- *)
Print["Downloading and cleaning populational table..."];Pause[0.5];

pop1=Import[BRPopulationURL,"Data"][[1,1,1]];
pop2=Drop[pop1,1];
pop3=Table[{pop2[[i,2]],ToExpression@StringDelete[pop2[[i,3]]," "]},{i,Length[pop2]}];
BRPopulationData=pop3/.StateToST//Sort;

Print["==========="];
Print["System ready!"];
Print["==========="];
]

Initialization

SetNameAndLocationOfExternalData[];
SetTransformationRulesAndConverters[];
SetSpecialFunctions[];
ImportExtractAndCleanIPCAData[];
ImportExtractAndCleanMSData[];
ImportAndCleanPopulationalData[];

What is the Brazilian Mega-Sena?

The Mega-Sena is the largest lottery in Brazil, held by the Caixa Econômica Federal (CEF) bank.

In Brazil only the federal government can explore gambles. And CEF explores them a lot!

Button["Lotteries managed by CEF", 
Print@Image[,ImageSize->100
],BaseStyle->{20}]

Things you need to know before playing

How to play on the MS

Button["Betting and winning",
Print[Text[Style["\nNumbers available for betting:",16]]];
Print[Table[i +Range[1,10],{i,0,50,10}]//TableForm];

Print[Text[Style["\nWays you can win:",16]]];
Print["If you hit 4 numbers -> win the 'Quadra'"];
Print["If you hit 5 numbers -> win the 'Quina'"];
Print["If you hit 6 numbers -> win the 'Sena' (jackpot)"];

,BaseStyle->{20}]

Button["Cost of a bet",Module[{minimumBetCost,MSCostOfSixNumbersBet},
Print@TableForm[Table[{i,NumberForm[CostOfaMSBet[i],{6,2},DigitBlock->3]},{i,6,15}],TableAlignments->Right,TableHeadings->{None,{"Bet","Cost (US$)"}}];
],BaseStyle->{20}
]

Chances of winning

How difficult is to win something by betting on the Mega-Sena?

Button["Chances of winning (1 in...)",
Print@TableForm[Table[{i,ChancesOfWinningOnMS[i,"Sena"],ChancesOfWinningOnMS[i,"Quina"],ChancesOfWinningOnMS[i,"Quadra"]},{i,6,15}],TableAlignments->Right,TableHeadings->{None,{"Bet","Sena","Quina","Quadra"}}
],BaseStyle->{20}
]

Let us compare the chances of winning the MS to two lotteries from US:

Button["", Print@Image[,ImageSize->300],BaseStyle->{20}]

Button["", Print@Image[,ImageSize->300],BaseStyle->{20}]

Playing the Brazilian Mega-Sena

This is a typical place where people bet on the Mega-Sena and other lotteries.

Button["Mega-Sena playslip", Print@Image[,ImageSize->200],BaseStyle->{20}]

If you’re planning to go to Brazil, don’t miss the chance of betting on the MS .

Button["If you won the jackpot alone you may become a millionaire!!!", 
Print@Image[,ImageSize->300];
Print[""];Print[""];Print[""];
Print["Oh, I'm sorry. Not this money... THAT ONE!"];
Print["⇓⇓⇓⇓⇓"];Print["⇓⇓⇓⇓⇓"];Print["⇓⇓⇓⇓⇓"];Print["⇓⇓⇓⇓⇓"];
Print@Image[,ImageSize->300];
,BaseStyle->{20}]

Statistics about the Mega-Sena

Button["Frequency of the numbers drawn",
Module[{tensDrawn,freqTensDrawn,partedFreqTensDrawn,partedFreqTensDrawnTable,MSFreqTensDrawnTable,MSFreqTensDrawnChart,mostTensDrawn,leastTensDrawn,MSMostAndLeastTensDrawnTable},

(**)
tensDrawn={};
tensDrawn=Table[Append[tensDrawn,MSdata[[i,3;;8]]],{i,2,Length[MSdata]}]//Flatten//Sort;
freqTensDrawn=Tally[tensDrawn];

(* Most and least tens drawn *)
mostTensDrawn=Sort[freqTensDrawn,#1[[2]]>#2[[2]]&][[1;;10]];
leastTensDrawn=Sort[freqTensDrawn,#1[[2]]<#2[[2]]&][[1;;10]];
MSMostAndLeastTensDrawnTable=TableForm[Grid[#,Frame->True,ItemStyle->Directive[FontSize->16]]&/@{mostTensDrawn,leastTensDrawn},TableDirections->Row];

Print["\nMost and least drawn numbers\n",MSMostAndLeastTensDrawnTable];


],BaseStyle->{20},Method->"Queued"
]

Button["Where do the Sena winners come from?",
Module[{BRstates,freqStates,MSstatesFrequency,freqByStatesA,freqByStatesB,MSFreqByStatesTable,MSFreqByStatesChart,popPerState,BRPopulationPerStateChart,perCapIncPerState,BRPerCaptaIncomePerStateChart,econActPopPerState,BREconomicallyActivePopulationPerStateChart},

BRstates={};
(* Isolate the Brazilian states from the rest of MSdata *)
BRstates=Table[Append[BRstates,MSdata[[i,12]]],{i,2,Length[MSdata] }]//Flatten//Sort;

(* Finds the frequency of every states. The first term was discarded because it is related to the draws without sena winners *)
freqStates=Drop [Tally[BRstates],1];

(* Brazilian state Amapá may have no Sena winner *)
If[Total[StringCount[freqStates[[All,1]],"AP"]]==0,freqStates=Insert[freqStates,{"AP",0},4];];

(* Separate the frequencies from the state names  *)
freqStates=Transpose[freqStates];
BRstates=freqStates[[1]];
MSstatesFrequency=freqStates[[2]];

(* Build the table *)
freqByStatesA=Table[{freqStates[[1,i]],freqStates[[2,i]]},{i,1,13}];
freqByStatesB=Table[{freqStates[[1,i]],freqStates[[2,i]]},{i,14,Length[freqStates[[1]]]}];
MSFreqByStatesTable=TableForm[Grid[#,Frame->True,ItemStyle->Directive[FontSize->16]]&/@{freqByStatesA,freqByStatesB},TableDirections->Row];

(* Build the Sena winners chart *)
MSFreqByStatesChart=BarChart[MSstatesFrequency,ChartLabels->BRstates,ImageSize->600,Frame->True,LabelStyle->Directive[12],FrameLabel->{"Brazilian states","Frequency of Sena winners"}];

(* Build the Sena winners chart *)
MSFreqByStatesChart=BarChart[MSstatesFrequency,ChartLabels->BRstates,ImageSize->600,Frame->True,LabelStyle->Directive[12],FrameLabel->{"Brazilian states","Frequency of Sena winners"}];

(* Build the population per state chart *)
popPerState=Transpose[BRPopulationData];
BRPopulationPerStateChart=BarChart[popPerState[[2]]/(10^6.),ChartLabels->popPerState[[1]],ImageSize->600,Frame->True,LabelStyle->Directive[12],FrameLabel->{"Brazilian states","Population (Millions)"}];

Print["\nNumber of Sena winners per state\n",MSFreqByStatesChart];
Print["Number of inhabitants per state\n",BRPopulationPerStateChart];

],BaseStyle->{20},Method->"Queued"
]

Button["Have there ever been two equal results in the MS draws?",
Module[{i,j,k,results,totalHits},
Print["Number of drawns so far: ",Length[MSdata],"\n"];

(* Seleciona as dezenas sorteadas em todos os concursos *)
results=Table[MSdata[[i,3;;8]],{i,1,Length[MSdata]}];
(* Ordena as dezenas para facilitar a comparação *)
results=Map[Sort,results];

(* Iteração para agrupar coincidências de 6, 5 e 4 dezenas *)
For[k=6,k≥4,k--, (* k = contador de número de dezenas coincidentes *)
Print["Analysis of draws with ",k," matching numbers"];
Print["===================================="];
(* Zera o contador de acertos (totHits) *)
totalHits=0;
For[i=1,i<=Length[results]-1,i++,
For[j=i+1,j<=Length[results],j++,
(* Verifica a ocorrência de coincidência *)
If[Length[Intersection[results[[i]],results[[j]]]]==k,
If[k==6||k==5,
Print["Draw ",  i ," ",results[[i]], " and Draw ", j," ",results[[j]]];
totalHits+=1;,
totalHits+=1;
]
]
]
];
If[totalHits==0,Print["There are no two draws with ",k," coincident numbers so far."],
Print["Total occurrences with ",k," matching numbers = ",totalHits]];
Print[""];
]
],BaseStyle->{20},Method->"Queued"
]

Simulation

Button["Simulate MS betting",
CreateDocument[
Manipulate[
Module[{numbersDrawn},

(* Updates the initial bet amount and how much money remains *)
(* Atualiza a quantia apostada inicial e o quanto ainda resta de dinheiro *)
If[yourInitialMoney≠initialMoney,
yourMoney=yourMoney+(initialMoney-yourInitialMoney);
yourInitialMoney=initialMoney
];


(* ===== YOU STARTED WITH ===== *)
(* ============================ *)

txtYouStartedWithTitle=Text[Style[Row[{
"You started with: "
}
],FontSize->18, FontFamily->"Courier",FontWeight->"Bold",  TextAlignment->Right],Scaled[{0.3,0.97}]];

txtYouStartedWith=Text[Style[Row[{
ApplyCashFormat[N@yourInitialMoney ,"Dollar"]
}
],FontSize->18, FontFamily->"Courier",FontWeight->"Bold", FontColor->Darker@Green, TextAlignment->Left],Scaled[{0.65,0.97}]];
(* ------------------------------------------------------------------------------------- *)


(* ===== YOUR BET ===== *)
(* =================== *)

txtYourBetTitle=Text[Style[Row[{"Your bet"}],
FontSize->16, FontFamily->"Courier",FontWeight->"Bold", FontColor->Blue,TextAlignment->Left],
Scaled[{.2,0.91}]];

cost=nBets*CostOfaMSBet[nNumbers];

txtYourBet=Text[Style[Row[{
"Amount of bets: ",nBets,"\n",
"Numbers in each bet: ",nNumbers,"\n",
"Cost: ",ApplyCashFormat[cost*nTeimosinhas,"Dollar"]}
],FontSize->14, FontFamily->"Courier",FontWeight->"Bold", TextAlignment->Left],Scaled[{0.2,0.82}]];

(* ===== PROBABILITIES ===== *)
(* ======================== *)

txtProbabilitiesTitle=Text[Style[Row[{"Probabilities"}],
FontSize->16, FontFamily->"Courier",FontWeight->"Bold", FontColor->Blue,TextAlignment->Left],
Scaled[{.55,0.91}]];

(* Calculates the winning probabilities *)
(* Calcula as probabilidades de ganho *)
chancesOfWinningOnSena= ChancesOfWinningOnMS[nNumbers,"Sena"]/N[nBets*nTeimosinhas];
chancesOfWinningOnQuina= ChancesOfWinningOnMS[nNumbers,"Quina"]/N[nBets*nTeimosinhas];
chancesOfWinningOnQuadra= ChancesOfWinningOnMS[nNumbers,"Quadra"]/N[nBets*nTeimosinhas];

If[Round@chancesOfWinningOnSena≥1,
probSena1=1;probSena2=Round@chancesOfWinningOnSena,
probSena1=Round[1/chancesOfWinningOnSena];probSena2=1
];

If[Round@chancesOfWinningOnQuina≥1,
probQuina1=1;probQuina2=Round@chancesOfWinningOnQuina,
probQuina1=Round[1/chancesOfWinningOnQuina];probQuina2=1
];

If[Round@chancesOfWinningOnQuadra≥1,
probQuadra1=1;probQuadra2=Round@chancesOfWinningOnQuadra,
probQuadra1=Round[1/chancesOfWinningOnQuadra];probQuadra2=1
];

txtProbabilities=Text[Style[Row[{
"  Sena: ",probSena1," in ",probSena2,"\n",
" Quina: ",probQuina1," in ",probQuina2,"\n",,
"Quadra: ",probQuadra1," in ",probQuadra2}
],FontSize->14, FontFamily->"Courier",FontWeight->"Bold", TextAlignment->Left],Scaled[{0.55,0.82}]];

(* ===== FORECAST ===== *)
(* ==================== *)

txtForecastTitle=Text[Style[Row[{"Forecast"}],
FontSize->16, FontFamily->"Courier",FontWeight->"Bold", FontColor->Blue,TextAlignment->Left],
Scaled[{.85,0.91}]];

(* Calculate the time interval to win some prize *)
(* Calcula o intervalo de tempo para ganhar algum prêmio *)
If[
probSena1>=probSena2,
timeSena=Quantity[0.,"Days"],
If[
Quantity[probSena2 7/2.,"Days"]>UnitConvert[Quantity[1.,"Years"],"Days"],
timeSena=UnitConvert[Quantity[probSena2 7/2.,"Days"],"Years"],
If[Quantity[probSena2 7/2.,"Days"]>UnitConvert[Quantity[1.,"Months"],"Days"],
timeSena=UnitConvert[Quantity[probSena2 7/2.,"Days"],"Months"],
timeSena=Quantity[probSena2 7/2.,"Days"]
]
]
];

If[
probQuina1>=probQuina2,
timeQuina=Quantity[0.,"Days"],
If[
Quantity[probQuina2 7/2.,"Days"]>UnitConvert[Quantity[1.,"Years"],"Days"],
timeQuina=UnitConvert[Quantity[probQuina2 7/2.,"Days"],"Years"],
If[Quantity[probQuina2 7/2.,"Days"]>UnitConvert[Quantity[1.,"Months"],"Days"],
timeQuina=UnitConvert[Quantity[probQuina2 7/2.,"Days"],"Months"],
timeQuina=Quantity[probQuina2 7/2.,"Days"]
]
]
];

If[
probQuadra1>=probQuadra2,
timeQuadra=Quantity[0.,"Days"],
If[
Quantity[probQuadra2 7/2.,"Days"]>UnitConvert[Quantity[1.,"Years"],"Days"],
timeQuadra=UnitConvert[Quantity[probQuadra2 7/2.,"Days"],"Years"],
If[Quantity[probQuadra2 7/2.,"Days"]>UnitConvert[Quantity[1.,"Months"],"Days"],
timeQuadra=UnitConvert[Quantity[probQuadra2 7/2.,"Days"],"Months"],
timeQuadra=Quantity[probQuadra2 7/2.,"Days"]
]
]
];

txtForecast=Text[Style[Row[{
"  Sena: ",NumberForm[timeSena,{10,1}],"\n",
" Quina: ",NumberForm[timeQuina,{10,1}],"\n",
"Quadra: ",NumberForm[timeQuadra,{10,1}]}
],FontSize->14, FontFamily->"Courier",FontWeight->"Bold", TextAlignment->Left],Scaled[{0.85,0.82}]];
(* ------------------------------------------------------------------------------------- *)

(* ===== SHOW ===== *)
(* ================ *)

Show[Graphics[{
txtYouStartedWithTitle,
txtYouStartedWith,

txtYourBetTitle,
txtYourBet,

txtProbabilitiesTitle,
txtProbabilities,

txtForecastTitle,
txtForecast,

txtDrawnTitle,
txtDrawn,

txtPrizesTitle,
txtPrizes,

txtYouHitTitle,
txtYouHit,

txtYourHitsTitle,
txtYourHits,

txtYourPrizesTitle,
txtYourPrizes,

txtPrizeEarnedTitle,
txtPrizeEarned,

txtAccumulatedPrizeEarnedTitle,
txtAccumulatedPrizeEarned,

txtAccumulatedPrizesTitle,
txtAccumulatedYouHit,
txtAccumulatedYourHits,
txtAccumulatedYourPrizes,

txtYourExpensesTitle,
txtYourExpenses,

txtYourBalanceTitle,
txtYourBalance

},PlotRange->{{0,10},{0,8}},ImageSize->Full]]
]
,
{{initialMoney,100,"Start with (US$):"},{100,1000,10000,100000,1000000,10000000,100000000,1000000000},ControlType->RadioButtonBar},
{{nBets,1,"Number of bets:"},{1,10,100,1000,10000,100000,500000,1000000},ControlType->RadioButtonBar},
{{nNumbers,6,"Quantity of numbers per bet:"},{6,7,8,9,10,11,12,13,14,15},ControlType->RadioButtonBar},
{{nTeimosinhas,1,"Teimosinha:"},{1,10,50,100,500,1000},ControlType->RadioButtonBar},

Row[{
Button["Run",

(* My bets *)
(* Minhas apostas *)
myBets=Table[Sort@RandomSample[Range[60],nNumbers],{i,nBets}];

nSenas=0;
nQuinas=0;
nQuadras=0;

nSenasWon=0;
nQuinasWon=0;
nQuadrasWon=0;

For[teimosinha=1,teimosinha≤nTeimosinhas,teimosinha++,
yourMoney=yourMoney-cost;

(* ===== DRAWN ===== *)
(* ================= *)

txtDrawnTitle=Text[Style[Row[{"Drawn"}],
FontSize->16, FontFamily->"Courier",FontWeight->"Bold", FontColor->Blue,TextAlignment->Left],
Scaled[{.2,0.72}]];

(* Numbers drawn *)
(* Números sorteadas *)
numSorteio=RandomInteger[{2,Length[MSdata]}];
numbersDrawn=Sort@MSdata[[numSorteio,3;;8]];

txtDrawn=Text[Style[Row[{
"Number: ",numSorteio,"\n",
numbersDrawn
}
],FontSize->14, FontFamily->"Courier",FontWeight->"Bold", TextAlignment->Left],Scaled[{0.2,0.63}]];

(* ===== PRIZES ===== *)
(* ================== *)

txtPrizesTitle=Text[Style[Row[{"Prizes"}],
FontSize->16, FontFamily->"Courier",FontWeight->"Bold", FontColor->Blue,TextAlignment->Left],
Scaled[{.7,0.72}]];

(* Prizes *)
(* Prêmios *)
If[MSdata[[numSorteio,18]]=="SIM",premioSena=MSdata[[numSorteio,19]],
premioSena= MSdata[[numSorteio,13]]];
premioQuina=MSdata[[numSorteio,15]];
premioQuadra=MSdata[[numSorteio,17]];

txtPrizes=Text[Style[Row[{
"  Sena = ",ApplyCashFormat[ premioSena,"Dollar"],"\n",
" Quina = ",ApplyCashFormat[premioQuina,"Dollar"],"\n",
"Quadra = ",ApplyCashFormat[ premioQuadra,"Dollar"]
}
],FontSize->14, FontFamily->"Courier",FontWeight->"Bold", TextAlignment->Left],Scaled[{0.7,0.63}]];

(* ===== YOU HIT ===== *)
(* =================== *)

txtYouHitTitle=Text[Style[Row[{"You hit"}],
FontSize->16, FontFamily->"Courier",FontWeight->"Bold", FontColor->Blue,TextAlignment->Left],
Scaled[{0.1,0.53}]];

(* Draw *)
(* Sorteio *)
For[i=1,i≤Length[myBets],i++,
c=Intersection[numbersDrawn,myBets[[i]]];
If[Length[c]==6,nSenas=nSenas+1,
If[Length[c]==5,nQuinas=nQuinas+1,
If[Length[c]==4,nQuadras=nQuadras+1]
]
]
];

txtYouHit=Text[Style[Row[{
"  Senas: ",nSenas,"\n",
" Quinas: ",nQuinas,"\n",
"Quadras: ",nQuadras
}
],FontSize->14, FontFamily->"Courier",FontWeight->"Bold", TextAlignment->Left],
Scaled[{0.1,0.44}]];

If[teimosinha==nTeimosinhas,

(* ===== YOUR HITS ===== *)
(* ===================== *)

txtYourHitsTitle=Text[Style[Row[{"Your hits"}],
FontSize->16, FontFamily->"Courier",FontWeight->"Bold", FontColor->Blue,TextAlignment->Left],
Scaled[{0.38,0.53}]];

premiumsReceivable=Table[ProbabilityCalculation[hits,prize]*ProbabilityCalculation[n-hits,6-prize],{hits,6,4,-1},{prize,hits,4,-1},{n,6,15}];

If[nSenas>0,
nSenasWon=nSenasWon+nSenas*premiumsReceivable[[1,1,nNumbers-5]];
nQuinasWon=nQuinasWon+nSenas*premiumsReceivable[[1,2,nNumbers-5]];
nQuadrasWon=nQuadrasWon+nSenas*premiumsReceivable[[1,3,nNumbers-5]];
];

If[nQuinas>0,
nQuinasWon=nQuinasWon+nQuinas*premiumsReceivable[[2,1,nNumbers-5]];
nQuadrasWon=nQuadrasWon+nQuinas*premiumsReceivable[[2,2,nNumbers-5]];
];

If[nQuadras>0,
nQuadrasWon=nQuadrasWon+nQuadras*premiumsReceivable[[3,1,nNumbers-5]];
];

premioTotalSena=nSenasWon*premioSena;
premioTotalQuina=nQuinasWon*premioQuina;
premioTotalQuadra=nQuadrasWon*premioQuadra;

txtYourHits=Text[Style[Row[{
"  Senas: ",nSenasWon,"\n",
" Quinas: ",nQuinasWon,"\n",
"Quadras: ",nQuadrasWon
}
],FontSize->14, FontFamily->"Courier",FontWeight->"Bold", TextAlignment->Left],
Scaled[{0.38,0.44}]];

(* ===== YOUR PRIZES ===== *)
(* ======================= *)

txtYourPrizesTitle=Text[Style[Row[{"Your prizes"}],
FontSize->16, FontFamily->"Courier",FontWeight->"Bold", FontColor->Blue,TextAlignment->Left],
Scaled[{0.75,0.53}]];

txtYourPrizes=Text[Style[Row[{
 " Sena: ",ApplyCashFormat[premioTotalSena ,"Dollar"],"\n",
" Quina: ",ApplyCashFormat[premioTotalQuina ,"Dollar"],"\n",
"Quadra: ",ApplyCashFormat[premioTotalQuadra ,"Dollar"]
}
],FontSize->14, FontFamily->"Courier",FontWeight->"Bold", TextAlignment->Left],
Scaled[{0.75,0.44}]];

premioTotal=premioTotalSena+premioTotalQuina+premioTotalQuadra;
yourMoney=yourMoney+premioTotal;


(* ===== ACCUMULATED PRIZES ===== *)
(* =============================== *)

txtAccumulatedPrizesTitle=Text[Style[Row[{"Accumulated prizes"}],
FontSize->16, FontFamily->"Courier",FontWeight->"Bold", FontColor->Blue,TextAlignment->Left],
Scaled[{0.45,0.33}]];


nAccumulatedSenas=nAccumulatedSenas+nSenas;
nAccumulatedQuinas=nAccumulatedQuinas+nQuinas;
nAccumulatedQuadras=nAccumulatedQuadras+nQuadras;

txtAccumulatedYouHit=Text[Style[Row[{
"  Senas: ",nAccumulatedSenas,"\n",
" Quinas: ",nAccumulatedQuinas,"\n",
"Quadras: ",nAccumulatedQuadras
}
],FontSize->14, FontFamily->"Courier",FontWeight->"Bold", TextAlignment->Left],
Scaled[{0.1,0.24}]];

nAccumulatedSenasWon=nAccumulatedSenasWon+nSenasWon;
nAccumulatedQuinasWon=nAccumulatedQuinasWon+nQuinasWon;
nAccumulatedQuadrasWon=nAccumulatedQuadrasWon+nQuadrasWon;

txtAccumulatedYourHits=Text[Style[Row[{
"  Senas: ",nAccumulatedSenasWon,"\n",
" Quinas: ",nAccumulatedQuinasWon,"\n",
"Quadras: ",nAccumulatedQuadrasWon
}
],FontSize->14, FontFamily->"Courier",FontWeight->"Bold", TextAlignment->Left],
Scaled[{0.38,0.24}]];

premioTotalSenaAccumulated=premioTotalSenaAccumulated+premioTotalSena;
premioTotalQuinaAccumulated=premioTotalQuinaAccumulated+premioTotalQuina;
premioTotalQuadraAccumulated=premioTotalQuadraAccumulated+premioTotalQuadra;

txtAccumulatedYourPrizes=Text[Style[Row[{
 " Sena: ",ApplyCashFormat[premioTotalSenaAccumulated ,"Dollar"],"\n",
" Quina: ",ApplyCashFormat[premioTotalQuinaAccumulated ,"Dollar"],"\n",
"Quadra: ",ApplyCashFormat[premioTotalQuadraAccumulated ,"Dollar"]
}
],FontSize->14, FontFamily->"Courier",FontWeight->"Bold", TextAlignment->Left],
Scaled[{0.75,0.24}]];

(* ===== PRIZE EARNED ===== *)
(* ======================== *)

txtPrizeEarnedTitle=Text[Style[Row[{
"            Prize earned: "
}
],FontSize->18, FontFamily->"Courier",FontWeight->"Bold", TextAlignment->Right],
Scaled[{0.3,0.15}]];

txtPrizeEarned=Text[Style[Row[{
ApplyCashFormat[premioTotal ,"Dollar"]
}
],FontSize->18, FontFamily->"Courier",FontWeight->"Bold", FontColor->Darker@Green, TextAlignment->Left],
Scaled[{0.7,0.15}]];

(* ===== ACCUMULATED PRIZE EARNED ===== *)
(* =================================== *)

txtAccumulatedPrizeEarnedTitle=Text[Style[Row[{
"Accumulated prize earned: "
}
],FontSize->18, FontFamily->"Courier",FontWeight->"Bold", TextAlignment->Right],
Scaled[{0.3,0.10}]];

premioTotalAccumulated=premioTotalAccumulated+premioTotal;

txtAccumulatedPrizeEarned=Text[Style[Row[{
ApplyCashFormat[premioTotalAccumulated ,"Dollar"]
}
],FontSize->18, FontFamily->"Courier",FontWeight->"Bold", FontColor->Darker@Green, TextAlignment->Left],
Scaled[{0.7,0.10}]];

(* ===== YOUR EXPENSES ===== *)
(* ======================== *)

txtYourExpensesTitle=Text[Style[Row[{
"           Your expenses: "
}
],FontSize->18, FontFamily->"Courier",FontWeight->"Bold", TextAlignment->Right],
Scaled[{0.3,0.05}]];

yourExpenses=yourExpenses+nTeimosinhas*cost;

txtYourExpenses=Text[Style[Row[{
ApplyCashFormat[yourExpenses ,"Dollar"]
}
],FontSize->18, FontFamily->"Courier",FontWeight->"Bold", FontColor->Red, TextAlignment->Left],
Scaled[{0.7,0.05}]];

(* ===== YOUR BALANCE ===== *)
(* ======================= *)

txtYourBalanceTitle=Text[Style[Row[{
"            Your balance: "
}
],FontSize->18, FontFamily->"Courier",FontWeight->"Bold", TextAlignment->Right],
Scaled[{0.3,0.01}]];

If[yourMoney≥0.,
txtYourBalance=Text[Style[Row[{
ApplyCashFormat[yourMoney ,"Dollar"]
}
],FontSize->18, FontFamily->"Courier",FontWeight->"Bold", FontColor->Darker@Green, TextAlignment->Left],
Scaled[{0.7,0.01}]],
txtYourBalance=Text[Style[Row[{
ApplyCashFormat[yourMoney ,"Dollar"]
}
],FontSize->18, FontFamily->"Courier",FontWeight->"Bold", FontColor->Red, TextAlignment->Left],
Scaled[{0.7,0.01}]]
];

];

],Method->"Queued"

,ImageSize->100],

"   ",

Button["Clear",
cost=0.;
teimosinha=0;

chancesOfWinningOnSena=0;
chancesOfWinningOnQuina=0;
chancesOfWinningOnQuadra=0;

probSena1=0;
probQuina1=0;
probQuadra1=0;

probSena2=0;
probQuina2=0;
probQuadra2=0;

timeSena=0;
timeQuina=0;
timeQuadra=0;

myBets=0;
yourExpenses=0;

yourInitialMoney=initialMoney;
yourMoney=initialMoney;

nSenas=0;
nQuinas=0;
nQuadras=0;

nSenasWon=0;
nQuinasWon=0;
nQuadrasWon=0;

nAccumulatedSenas=0;
nAccumulatedQuinas=0;
nAccumulatedQuadras=0;

nAccumulatedSenasWon=0;
nAccumulatedQuinasWon=0;
nAccumulatedQuadrasWon=0;

premioSena=0;
premioQuina=0;
premioQuadra=0;
premioTotal=0;

premioTotalSenaAccumulated=0.;
premioTotalQuinaAccumulated=0.;
premioTotalQuadraAccumulated=0.;

premiumsReceivable=0;

premioTotalAccumulated=0.;

txtDrawnTitle=Text["",{0.,0.}];
txtDrawn=Text["",{0.,0.}];

txtPrizesTitle=Text["",{0.,0.}];
txtPrizes=Text["",{0.,0.}];

txtYouHitTitle=Text["",{0.,0.}];
txtYouHit=Text["",{0.,0.}];

txtYourHitsTitle=Text["",{0.,0.}];
txtYourHits=Text["",{0.,0.}];

txtYourPrizesTitle=Text["",{0.,0.}];
txtYourPrizes=Text["",{0.,0.}];

txtAccumulatedPrizesTitle=Text["",{0.,0.}];
txtAccumulatedYouHit=Text["",{0.,0.}];
txtAccumulatedYourHits=Text["",{0.,0.}];
txtAccumulatedYourPrizes=Text["",{0.,0.}];

txtPrizeEarnedTitle=Text["",{0.,0.}];
txtPrizeEarned=Text["",{0.,0.}];

txtAccumulatedPrizeEarnedTitle=Text["",{0.,0.}];
txtAccumulatedPrizeEarned=Text["",{0.,0.}];

txtYourExpensesTitle=Text["",{0.,0.}];
txtYourExpenses=Text["",{0.,0.}];

txtYourBalanceTitle=Text["",{0.,0.}];
txtYourBalance=Text["",{0.,0.}]

,ImageSize->100
]
}],

SynchronousUpdating->False,

Initialization:>(
cost=0.;
teimosinha=0;

chancesOfWinningOnSena=0;
chancesOfWinningOnQuina=0;
chancesOfWinningOnQuadra=0;

probSena1=0;
probQuina1=0;
probQuadra1=0;

probSena2=0;
probQuina2=0;
probQuadra2=0;

timeSena=0;
timeQuina=0;
timeQuadra=0;

myBets=0;
yourExpenses=0;

yourInitialMoney=initialMoney;
yourMoney=initialMoney;

nSenas=0;
nQuinas=0;
nQuadras=0;

nSenasWon=0;
nQuinasWon=0;
nQuadrasWon=0;

nAccumulatedSenas=0;
nAccumulatedQuinas=0;
nAccumulatedQuadras=0;

nAccumulatedSenasWon=0;
nAccumulatedQuinasWon=0;
nAccumulatedQuadrasWon=0;

premioSena=0;
premioQuina=0;
premioQuadra=0;
premioTotal=0;

premioTotalSenaAccumulated=0.;
premioTotalQuinaAccumulated=0.;
premioTotalQuadraAccumulated=0.;

premiumsReceivable=0;

premioTotalAccumulated=0.;

txtDrawnTitle=Text["",{0.,0.}];
txtDrawn=Text["",{0.,0.}];

txtPrizesTitle=Text["",{0.,0.}];
txtPrizes=Text["",{0.,0.}];

txtYouHitTitle=Text["",{0.,0.}];
txtYouHit=Text["",{0.,0.}];

txtYourHitsTitle=Text["",{0.,0.}];
txtYourHits=Text["",{0.,0.}];

txtYourPrizesTitle=Text["",{0.,0.}];
txtYourPrizes=Text["",{0.,0.}];

txtAccumulatedPrizesTitle=Text["",{0.,0.}];
txtAccumulatedYouHit=Text["",{0.,0.}];
txtAccumulatedYourHits=Text["",{0.,0.}];
txtAccumulatedYourPrizes=Text["",{0.,0.}];

txtPrizeEarnedTitle=Text["",{0.,0.}];
txtPrizeEarned=Text["",{0.,0.}];

txtAccumulatedPrizeEarnedTitle=Text["",{0.,0.}];
txtAccumulatedPrizeEarned=Text["",{0.,0.}];

txtYourExpensesTitle=Text["",{0.,0.}];
txtYourExpenses=Text["",{0.,0.}];

txtYourBalanceTitle=Text["",{0.,0.}];
txtYourBalance=Text["",{0.,0.}])
]
],BaseStyle->{20},Method->"Queued"
]

8 tips from the “experts”

Button["Tip #1",
Print[Text[Style["
Prefer to bet more numbers on a same playslip than making several simple bets.",Blue]]
]]

Button["Comment #1",
Print["Really?\n
What would you prefer?\n
To bet 7 numbers in a playslip:\n",
RandomInteger[{1,60},7],
"\n\nOr to bet 7 playslips with 6 numbers?\n",
Table[RandomInteger[{1,60},7],7]];
Print["==============="],Method->"Queued"
]

Button["Tip #2",
Print[Text[Style["
Avoid choosing consecutive numbers (e.g., 4,5,6,7,8,9,10). The chances of this happening are nil.",Blue]]
]]

Button["Comment #2",
Grid[Table[i +Range[1,10],{i,0,50,10}],Frame->{None,None,{{{1,1},{1,6}}->True}}]//Print;

line=Range[5];column=Range[10];
rc0:={RandomChoice[line],
RandomChoice[column]};
rc={};
For[n=1,n≤6,n++,
AppendTo[rc,rc0];
For[i=1,i≤n-1,i++,
If[rc[[n]]==rc[[i]],
rc[[n]]=rc0]
]
];
Grid[
Table[i +Range[1,10],{i,0,50,10}],Frame->{None,None,{rc[[1]]->True,rc[[2]]->True,rc[[3]]->True,rc[[4]]->True,rc[[5]]->True,rc[[6]]->True}}]//Print;
Print["==============="],Method->"Queued"
]

Button["Tip #3",
Print[Text[Style["
Try to balance the choice between odd and even numbers.",Blue]]
]]

Button["Comment #3",
numbers=Table[MSdata[[n,3;;8]],{n,2,Length[MSdata]}]//Flatten;
Print["Total of numbers drawn so far: ",Length[numbers]];
Print["Total of even numbers: ",Count[numbers,_?EvenQ]];Print["Total of odd numbers: ",Count[numbers,_?OddQ]];
Print["==============="],Method->"Queued"
]

Button["Tip #4",
Print[Text[Style["
Divide the card into four quadrants and distribute your numbers between them.",Blue]]
]]

Button["Comment #4",
line=Range[5];column=Range[10];
rc:={RandomChoice[line],
RandomChoice[column]};Grid[Table[i +Range[1,10],{i,0,50,10}],Frame->{True,True,{{{1,3},{1,5}}->{Red,Dashed},{{1,3},{6,10}}->{Red,Dashed},{{4,6},{1,5}}->{Red,Dashed},{{4,6},{6,10}}->{Red,Dashed},rc->True,rc->True,rc->True,rc->True,rc->True,rc->True}}]//Print;
Print["==============="],Method->"Queued"
]

Button["Tip #5",
Print[Text[Style["
Do not play on numbers that are on the same vertical line.",Blue]]
]]

Button["Comment #5",
Grid[Table[i +Range[1,10],{i,0,50,10}],Frame->{{None,None,None,True},None}]//Print;

line=Range[5];column=Range[10];
rc0:={RandomChoice[line],
RandomChoice[column]};
rc={};
For[n=1,n≤6,n++,
AppendTo[rc,rc0];
For[i=1,i≤n-1,i++,
If[rc[[n]]==rc[[i]],
rc[[n]]=rc0]
]
];
Grid[
Table[i +Range[1,10],{i,0,50,10}],Frame->{None,None,{rc[[1]]->True,rc[[2]]->True,rc[[3]]->True,rc[[4]]->True,rc[[5]]->True,rc[[6]]->True}}]//Print;
Print["==============="],Method->"Queued"
]

Button["Tip #6",
Print[Text[Style["
Do not play on numbers that are barely drawn.",Blue]]
]]

Button["Comment #6",
tensDrawn={};
tensDrawn=Table[Append[tensDrawn,MSdata[[i,3;;8]]],{i,2,Length[MSdata]}]//Flatten//Sort;
freqTensDrawn=Tally[tensDrawn];
ListPlot[Tooltip[freqTensDrawn],Filling->Axis,ImageSize->Large,Frame->True,LabelStyle->Directive[12],FrameLabel->{"Tens","Frequency"}]//Print;
Print["==============="],Method->"Queued"
]

Button["Tip #7",
Print[Text[Style["
Never play a result that has already come out, because that never happened.",Blue]]
]]

Button["Comment #7",
Module[{i,j,k,results,totalHits},
Print["Number of drawns so far: ",Length[MSdata],"\n"];

(* Seleciona as dezenas sorteadas em todos os concursos *)
results=Table[MSdata[[i,3;;8]],{i,1,Length[MSdata]}];
(* Ordena as dezenas para facilitar a comparação *)
results=Map[Sort,results];

(* Iteração para agrupar coincidências de 6, 5 e 4 dezenas *)
For[k=6,k≥5,k--, (* k = contador de número de dezenas coincidentes *)
Print["Analysis of draws with ",k," matching numbers"];
Print["===================================="];
(* Zera o contador de acertos (totHits) *)
totalHits=0;
For[i=1,i<=Length[results]-1,i++,
For[j=i+1,j<=Length[results],j++,
(* Verifica a ocorrência de coincidência *)
If[Length[Intersection[results[[i]],results[[j]]]]==k,
If[k==6||k==5,
Print["Draw ",  i ," ",results[[i]], " and Draw ", j," ",results[[j]]];
totalHits+=1;,
totalHits+=1;
]
]
]
];
If[totalHits==0,Print["There are no two draws with ",k," coincident numbers so far."],
Print["Total occurrences with ",k," matching numbers = ",totalHits]];
Print[""];
]
];
Print["==============="],Method->"Queued"
]

Button["Tip #8",
Print[Text[Style["
Never bet on Mega-Sena if you're in Amapá!!!",Blue]]
]]

Button["Comment #8",

Print[BRMapOfBrazilIMG];

Module[{BRstates,freqStates,MSstatesFrequency,freqByStatesA,freqByStatesB,MSFreqByStatesTable},
BRstates={};
(* Isolate the Brazilian states from the rest of MSdata *)
BRstates=Table[Append[BRstates,MSdata[[i,12]]],{i,2,Length[MSdata] }]//Flatten//Sort;

(* Finds the frequency of every states. The first term was discarded because it is related to the draws without sena winners *)
freqStates=Drop [Tally[BRstates],1];

(* Brazilian state Amapá may have no Sena winner *)
If[Total[StringCount[freqStates[[All,1]],"AP"]]==0,freqStates=Insert[freqStates,{"AP",0},4];];

(* Separate the frequencies from the state names  *)
freqStates=Transpose[freqStates];
BRstates=freqStates[[1]];
MSstatesFrequency=freqStates[[2]];

(* Build the table *)
freqByStatesA=Table[{freqStates[[1,i]],freqStates[[2,i]]},{i,1,13}];
freqByStatesB=Table[{freqStates[[1,i]],freqStates[[2,i]]},{i,14,Length[freqStates[[1]]]}];
MSFreqByStatesTable=Print@TableForm[Grid[#,Frame->True,ItemStyle->Directive[FontSize->16]]&/@{freqByStatesA,freqByStatesB},TableDirections->Row]
];

Print["==============="],Method->"Queued"
]