Bruno Cintra Posted October 23, 2020 Share Posted October 23, 2020 14 horas atrás, luiz.antonio disse: Funcionou !! Baixei o projeto...me parece que falta alguns arquivos, é isso mesmo ? Com o GCC acusa vários arquivos ausentes, e no fonte faz mesmo referencia a eles. Paz e Prosperidade. Luiz ve se consegue rodar esse aqui,esta sem o codigo só o exe,o codigo é do cover32.c convertido para vb6 http://www.mediafire.com/file/k1n7v9eikntwazb/Cover32.7z/file Quote Link to comment Share on other sites More sharing options...
Bruno Cintra Posted October 23, 2020 Share Posted October 23, 2020 21 horas atrás, luiz.antonio disse: Funcionou !! Baixei o projeto...me parece que falta alguns arquivos, é isso mesmo ? Com o GCC acusa vários arquivos ausentes, e no fonte faz mesmo referencia a eles. Paz e Prosperidade. Luiz o codigo que parece desta pagina eu consegui compilar em codeblocks é rapido,mais só vai ate 32 numeros https://blog.wakatta.jp/blog/2012/02/13/psychic-modeling-fast-version/ 1 Quote Link to comment Share on other sites More sharing options...
GAS Posted October 27, 2020 Share Posted October 27, 2020 @luiz.antonio Parabéns pela iniciativa Estudo aplicações em loterias com Python, não com programação mas com aplicação em Machine Learning, Regressões, Árvores de decisão, etc... Tendo algum caminho, supostamente interessante, vou postar para análise do grupo. Boa noite a todos Saúde e Sorte 1 Quote Link to comment Share on other sites More sharing options...
RobSmith Posted October 27, 2020 Share Posted October 27, 2020 Crie sua loteria, ou construa sua aplicação de loteria atraves do Arquiteto de loterias - LottoArchitect_2_2 Links do construtor de loterias freeware https://www.anastasios-tampakis.net/services/downloadApp.php?app=LA Manual em PDF https://www.anastasios-tampakis.net/services/downloadApp.php?app=LA_PDF Nota: Lotto Architect (freeware) O Lotto Architect oferece métodos e técnicas poderosas para jogar na loteria. Apresentando históricos de dados de extrações completos; filtragem por grupos de números e sistemas de avaliação estatística simplesmente aplicados; todos os testes e verificação de estágio posterior; um gerenciamento excepcional de matrizes (desenhos de cobertura) com suporte de banco de dados; algoritmos precisos que se aplicam a filtros de rejeição e previsão dos números que virão no próximo sorteio - todos os quais oferecem ao usuário uma "melhor chance" de recompensa em sua loteria preferida. O Lotto Architect oferece uma abordagem totalmente integrada e tem tudo o que é necessário para que você gerencie com eficácia seus interesses na loteria. Quote Link to comment Share on other sites More sharing options...
Bruno Cintra Posted April 10, 2021 Share Posted April 10, 2021 Em 22/10/2020 em 21:13, luiz.antonio disse: Funcionou !! Baixei o projeto...me parece que falta alguns arquivos, é isso mesmo ? Com o GCC acusa vários arquivos ausentes, e no fonte faz mesmo referencia a eles. Paz e Prosperidade. Luiz ola Luiz,olha esse codigo em python ve se consegue rodar peguei neste site. https://gimplearn.net/viewtopic.php?f=39&t=2333&p=25624&hilit=wheeling#p25624 #You can change below 4 lines to values you want and run program #---------------------------------------------------------------- ch = ['1','2','3','4','5','6','7','8','9','10','11','12'] #characters to use as number substitutes for wheeling keys/pattern if_match = 3 #if we match this number of numbers in our wheel min_match = 3 #minimum guarantee match numbers_per_ticket = 6 #numbers on per line on a ticket # ------------------------------------------------------------- def check(ind,i,group_size,l): if i >= 0: ind[i] += 1 #try incrementing it if ind[i] > (l - 1 - (group_size-1-i)): return check(ind,i-1,group_size,l) else: return i else: return i-1 def combinations(li,group_size): index = [0] * group_size #initialize pointers for i in range(0,group_size): index[i] = i l = len(li) combs = [] while index[0] <= (l - group_size): #print ((l - group_size)) #grab combination here comb = [] #print (index) for z in range(0,group_size): comb.append(li[index[z]]) combs.append(tuple(comb)) i = group_size-1 lowestchange = check(index,i,group_size,l) #print (lowestchange) for j in range(lowestchange+1,group_size): k = j - lowestchange #print (index[j-1]+k,end=",") index[j]=index[j-1]+1 # print return combs def row_match(row1,check1): #returns number of matches check appears in row count = 0 for item in row1: if item in check1: count += 1 return count dot_count = 1 def row_matches_count(clist,checklist): global dot_count for i in range(0,len(checklist)): #print (".",end="") dot_count += 1 if dot_count % 100==0: dot_count = 1 # print () checklist[i][1] = 0 #reset checks each time. for k in range(0,len(clist)): if clist[k][1] == 0: #not yet included c = row_match(clist[k][0],checklist[i][0]) if c >= min_match: #print "match:" + str(c) checklist[i][1] += 1 #increment counter of rows matched mininum matches. return clist,checklist; def allchecked(clist): for clistrow in clist: if clistrow[1] == 0: return False return True def markcheck(clist,checkrow): for clistrow in clist: if clistrow[1] == 0: #not yet included c = row_match(clistrow[0],checkrow) if c >= min_match: clistrow[1] = 1 #mark it as checked return clist # Get all combinations of [1, 2, 3] # and length 2 comb = combinations(ch, if_match) comb = list(comb) #mylist = [] #copy and convert to list for i in range(0,len(comb)): comb[i] = [list(comb[i]),0] #mylist.append([list(comb[i][0]),0]) mylist = combinations(ch,numbers_per_ticket) mylist = list(mylist) for i in range(0,len(mylist)): #comb[i] = [list(comb[i]),0] mylist[i] = [list(mylist[i]),0] #match count keys = [] while not allchecked(comb): # print () # print ("Processing...") comb,mylist = row_matches_count(comb,mylist) #print str(mylist) mylist = sorted(mylist,key=lambda x: -x[1]) keys.append(mylist[0][0]) #add it as key comb = markcheck(comb,mylist[0][0]) del mylist[0] #print () print ("Resultado possível, compras seguidas pelo número de correspondências") for i in range(0,len(comb)): linenum = str(i+1) # print (linenum+ "-result",end=" ") checkrow = comb[i][0] # print ("".join(checkrow),"buys:",end=" ") # for key in keys: # c = row_match(checkrow,key) # print ("".join(key),c,end=" ") # print () #print ("number of key lines:",len(keys)) #print ("Keys:",end=" ") for key in keys: print (" ".join(key)) print () print (str(len(ch)) + " Numeros, ganha "+str(if_match) + " se " + str(min_match)) print(str(len(keys)) + " Cartões ("+str(numbers_per_ticket)+" Numeros por Cartão).") print ("Fim!") 1 Quote Link to comment Share on other sites More sharing options...
Ralf Jones Posted April 12, 2021 Share Posted April 12, 2021 {$APPTYPE CONSOLE} uses SysUtils; const NUMBER_OF_SPHERES = 45; NUMBER_OF_BITS_ARRAY_UPPER_END = 255; var counter, counterCopy, counterOffset, range: int64; bitCounter, bitCount, bitPosition: integer; combCounter: integer; byteFragmentIndexOfCounter: integer; positionOfLowestBitOutOfSix: integer; numberOfBits: array[0..NUMBER_OF_BITS_ARRAY_UPPER_END] of byte; before, after, beforePrint, afterPrint: TDateTime; combstr: string; lottoList: TStringList; function powerOf2(exponent: integer): int64; var shifter: int64; counter: integer; begin shifter:= 1; for counter:= 1 to exponent do shifter:= shifter + shifter; result:= shifter; end; procedure presetBitCountLookupTable(highestIndex: integer); var arrayIndex: integer; numberOfBitsSet: integer; byteValue: integer; begin //preset bit count lookup table for arrayIndex:= 0 to highestIndex do begin byteValue:= arrayIndex; numberOfBitsSet:= 0; for bitCounter:= 1 to 8 do begin if ((byteValue and 1) = 1) then inc(numberOfBitsSet); byteValue:= byteValue shr 1; end; numberOfBits[arrayIndex]:= numberOfBitsSet; end; end; begin //main try presetBitCountLookupTable(NUMBER_OF_BITS_ARRAY_UPPER_END); range:= powerOf2(NUMBER_OF_SPHERES); lottoList:= TStringlist.create; before:= Time; Writeln('Lotto report start at: '+ FormatDateTime('hh:nn:ss.zzz',before)); Writeln('You get a file "All_lotto_combinations2.txt" of about 240 MByte!'); counter:= 0; lottoList.add('All lotto combinations 6/ ' +IntToStr(NUMBER_OF_SPHERES)); lottoList.add('**********************************************************'); while counter range do begin //check cases bitCount:= 0; counterCopy:= counter; for byteFragmentIndexOfCounter:= 0 to 5 do begin bitCount:= bitCount+numberOfBits[counterCopy mod 256]; counterCopy:= counterCopy shr 8; end; if (bitCount=6) then begin counterCopy:= counter; positionOfLowestBitOutOfSix:= -1; inc(combCounter); //write('combination #' + inttostr(combinationCounter) +': '); for bitCounter:=1 to NUMBER_OF_SPHERES do begin if ((counterCopy and 1) = 1) then begin //write(inttoStr(bitCounter) +' '); combstr:= combstr+ ' '+inttoStr(bitCounter); if (positionOfLowestBitOutOfSix= -1) then positionOfLowestBitOutOfSix:= bitCounter; end; counterCopy:= counterCopy shr 1; end; //writeln(' '); lottoList.add('# '+inttostr(combCounter)+': '+ combstr); combstr:= ''; counterOffset:= 1; bitPosition:= 1; while (bitPositionpositionOfLowestBitOutOfSix) do begin counterOffset:= counterOffset + counterOffset; inc(bitPosition); end; counter:= counter + counterOffset; end else counter:= counter + 1; end; //while after:= Time; beforePrint:= time; Writeln('Save lotto file start: '+TimeToStr(beforePrint)+' '+DateToStr(date)); lottoList.SaveToFile('All_lotto_combinations2.txt'); lottoList.Free; afterPrint:= time; Writeln('Save lotto stopped at: '+TimeToStr(afterPrint)+' '+DateToStr(date)); Writeln('Save file lasted: '+FormatDateTime('hh:nn:ss.zzz',afterPrint-beforePrint)); Writeln('Lotto report calc end: '+ FormatDateTime('hh:nn:ss.zzz',after)); Writeln('Lotto calc lasted: '+FormatDateTime('hh:nn:ss.zzz',after-before)); Writeln('Lotto report total lasted: '+FormatDateTime('hh:nn:ss.zzz',afterPrint-before)); Writeln('6 of '+IntToStr(NUMBER_OF_SPHERES)+'are: ' +IntToStr(combCounter)); except on E:Exception do Writeln(E.Classname, ': ', E.Message); end; end. Quote Link to comment Share on other sites More sharing options...
rockcavera Posted April 13, 2021 Share Posted April 13, 2021 Em 10/04/2021 em 14:50, Bruno Cintra disse: ola Luiz,olha esse codigo em python ve se consegue rodar peguei neste site. https://gimplearn.net/viewtopic.php?f=39&t=2333&p=25624&hilit=wheeling#p25624 #You can change below 4 lines to values you want and run program #---------------------------------------------------------------- ch = ['1','2','3','4','5','6','7','8','9','10','11','12'] #characters to use as number substitutes for wheeling keys/pattern if_match = 3 #if we match this number of numbers in our wheel min_match = 3 #minimum guarantee match numbers_per_ticket = 6 #numbers on per line on a ticket # ------------------------------------------------------------- def check(ind,i,group_size,l): if i >= 0: ind[i] += 1 #try incrementing it if ind[i] > (l - 1 - (group_size-1-i)): return check(ind,i-1,group_size,l) else: return i else: return i-1 def combinations(li,group_size): index = [0] * group_size #initialize pointers for i in range(0,group_size): index[i] = i l = len(li) combs = [] while index[0] <= (l - group_size): #print ((l - group_size)) #grab combination here comb = [] #print (index) for z in range(0,group_size): comb.append(li[index[z]]) combs.append(tuple(comb)) i = group_size-1 lowestchange = check(index,i,group_size,l) #print (lowestchange) for j in range(lowestchange+1,group_size): k = j - lowestchange #print (index[j-1]+k,end=",") index[j]=index[j-1]+1 # print return combs def row_match(row1,check1): #returns number of matches check appears in row count = 0 for item in row1: if item in check1: count += 1 return count dot_count = 1 def row_matches_count(clist,checklist): global dot_count for i in range(0,len(checklist)): #print (".",end="") dot_count += 1 if dot_count % 100==0: dot_count = 1 # print () checklist[i][1] = 0 #reset checks each time. for k in range(0,len(clist)): if clist[k][1] == 0: #not yet included c = row_match(clist[k][0],checklist[i][0]) if c >= min_match: #print "match:" + str(c) checklist[i][1] += 1 #increment counter of rows matched mininum matches. return clist,checklist; def allchecked(clist): for clistrow in clist: if clistrow[1] == 0: return False return True def markcheck(clist,checkrow): for clistrow in clist: if clistrow[1] == 0: #not yet included c = row_match(clistrow[0],checkrow) if c >= min_match: clistrow[1] = 1 #mark it as checked return clist # Get all combinations of [1, 2, 3] # and length 2 comb = combinations(ch, if_match) comb = list(comb) #mylist = [] #copy and convert to list for i in range(0,len(comb)): comb[i] = [list(comb[i]),0] #mylist.append([list(comb[i][0]),0]) mylist = combinations(ch,numbers_per_ticket) mylist = list(mylist) for i in range(0,len(mylist)): #comb[i] = [list(comb[i]),0] mylist[i] = [list(mylist[i]),0] #match count keys = [] while not allchecked(comb): # print () # print ("Processing...") comb,mylist = row_matches_count(comb,mylist) #print str(mylist) mylist = sorted(mylist,key=lambda x: -x[1]) keys.append(mylist[0][0]) #add it as key comb = markcheck(comb,mylist[0][0]) del mylist[0] #print () print ("Resultado possível, compras seguidas pelo número de correspondências") for i in range(0,len(comb)): linenum = str(i+1) # print (linenum+ "-result",end=" ") checkrow = comb[i][0] # print ("".join(checkrow),"buys:",end=" ") # for key in keys: # c = row_match(checkrow,key) # print ("".join(key),c,end=" ") # print () #print ("number of key lines:",len(keys)) #print ("Keys:",end=" ") for key in keys: print (" ".join(key)) print () print (str(len(ch)) + " Numeros, ganha "+str(if_match) + " se " + str(min_match)) print(str(len(keys)) + " Cartões ("+str(numbers_per_ticket)+" Numeros por Cartão).") print ("Fim!") Esse código é simples de rodar. Baste ter o Python instalado, configurar as 4 primeiras linhas e dar um "python nome.py" no prompt de comandos (famoso CMD.exe). Obs: "nome.py" é o nome do arquivo que você vai salvar o código. As configurações estão nas 4 primeiras linhas.: #You can change below 4 lines to values you want and run program #---------------------------------------------------------------- ch = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N'] #characters to use as number substitutes for wheeling keys/pattern if_match = 5 #if we match this number of numbers in our wheel min_match = 3 #minimum guarantee match numbers_per_ticket = 5 #numbers on per line on a ticket # ------------------------------------------------------------- A variável CH é uma lista com os elementos da combinação. Aqui no forum, estamos acostumados a chamar de V. Claro que o V será a contagem da quantidade de elementos. No caso do código acima, o programador inseriu letras para facilitar a substituição pelos números escolhidos depois. A variável IF_MATCH é o que chamamos de M. Ou seja, é a condição que precisa ser respeitada para termos a garantia T. A variável MIN_MATCH é o que chamamos de T. Portanto, é a garantia mínima pretendida com o sistema/desdobramento/fechamento. Por fim, a variável NUMBERS_PER_TICKET é o que chamamos de K. É a quantidade de elementos por combinação. Não olhei o código todo ainda, apenas testei e funciona perfeitamente. Depois vou dar uma olhada mais a funda e fazer algumas considerações. Abraço. Edit: @Bruno Cintra, antes que eu me esqueça, sempre que colar um código (linhas de programação), utilize um campo código do editor de publicação. Vide no Print. 1 Quote Link to comment Share on other sites More sharing options...
Bruno Cintra Posted April 13, 2021 Share Posted April 13, 2021 1 hora atrás, rockcavera disse: Esse código é simples de rodar. Baste ter o Python instalado, configurar as 4 primeiras linhas e dar um "python nome.py" no prompt de comandos (famoso CMD.exe). Obs: "nome.py" é o nome do arquivo que você vai salvar o código. As configurações estão nas 4 primeiras linhas.: #You can change below 4 lines to values you want and run program #---------------------------------------------------------------- ch = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N'] #characters to use as number substitutes for wheeling keys/pattern if_match = 5 #if we match this number of numbers in our wheel min_match = 3 #minimum guarantee match numbers_per_ticket = 5 #numbers on per line on a ticket # ------------------------------------------------------------- A variável CH é uma lista com os elementos da combinação. Aqui no forum, estamos acostumados a chamar de V. Claro que o V será a contagem da quantidade de elementos. No caso do código acima, o programador inseriu letras para facilitar a substituição pelos números escolhidos depois. A variável IF_MATCH é o que chamamos de M. Ou seja, é a condição que precisa ser respeitada para termos a garantia T. A variável MIN_MATCH é o que chamamos de T. Portanto, é a garantia mínima pretendida com o sistema/desdobramento/fechamento. Por fim, a variável NUMBERS_PER_TICKET é o que chamamos de K. É a quantidade de elementos por combinação. Não olhei o código todo ainda, apenas testei e funciona perfeitamente. Depois vou dar uma olhada mais a funda e fazer algumas considerações. Abraço. Edit: @Bruno Cintra, antes que eu me esqueça, sempre que colar um código (linhas de programação), utilize um campo código do editor de publicação. Vide no Print. eu baixei um programa python e rodei normal,só passei pro Luiz porque ele que esta mexendo com python 1 Quote Link to comment Share on other sites More sharing options...
Bruno Cintra Posted April 13, 2021 Share Posted April 13, 2021 2 horas atrás, rockcavera disse: Esse código é simples de rodar. Baste ter o Python instalado, configurar as 4 primeiras linhas e dar um "python nome.py" no prompt de comandos (famoso CMD.exe). Obs: "nome.py" é o nome do arquivo que você vai salvar o código. As configurações estão nas 4 primeiras linhas.: #You can change below 4 lines to values you want and run program #---------------------------------------------------------------- ch = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N'] #characters to use as number substitutes for wheeling keys/pattern if_match = 5 #if we match this number of numbers in our wheel min_match = 3 #minimum guarantee match numbers_per_ticket = 5 #numbers on per line on a ticket # ------------------------------------------------------------- A variável CH é uma lista com os elementos da combinação. Aqui no forum, estamos acostumados a chamar de V. Claro que o V será a contagem da quantidade de elementos. No caso do código acima, o programador inseriu letras para facilitar a substituição pelos números escolhidos depois. A variável IF_MATCH é o que chamamos de M. Ou seja, é a condição que precisa ser respeitada para termos a garantia T. A variável MIN_MATCH é o que chamamos de T. Portanto, é a garantia mínima pretendida com o sistema/desdobramento/fechamento. Por fim, a variável NUMBERS_PER_TICKET é o que chamamos de K. É a quantidade de elementos por combinação. Não olhei o código todo ainda, apenas testei e funciona perfeitamente. Depois vou dar uma olhada mais a funda e fazer algumas considerações. Abraço. Edit: @Bruno Cintra, antes que eu me esqueça, sempre que colar um código (linhas de programação), utilize um campo código do editor de publicação. Vide no Print. eu gostei do codigo,só vou tentar mudar o ch para colocar so a quantidade de numeros e ve até quantos ele consegue gerar.apesar de eu colocar quantidade maior demorou 1 Quote Link to comment Share on other sites More sharing options...
sorel Posted April 13, 2021 Share Posted April 13, 2021 ala Bruno e demais, filtros de padrões de loteria por setores? alguem ja tentou isso? setores seriam pequenos quadrantes no objetivo da matriz da loteria para pegar a nuvem de frequenciaes por onde passam os padrões do sorteio como usar esta formula para pegar nos setores a nuvens cheia? The formula that works for me is. F($$)= D( P1 +P2 + A + Sk1 + Sk2 + [-D] + [SpΦ] + ) Quote Link to comment Share on other sites More sharing options...
luiz.antonio Posted April 19, 2021 Author Share Posted April 19, 2021 (edited) Boa Tarde ! O Código abaixo faz um web scraping no site da caixa (resultado da lotomania), pega todos os resultados e gera um arquivo "ltm.txt" onde mostra o atraso de cada uma das 100 dezenas. * pra rodar o programa é preciso ter o python instalado e as libs instaladas, caso for instalar o python agora, após instalar...abra o cmd e digite: python -m pip install --upgrade pip (enter) pip install pandas (enter) pip install requests (enter) pip install bs4 (enter) pip install selenium (enter) import time import requests import pandas as pd from bs4 import BeautifulSoup from selenium import webdriver from selenium.webdriver.chrome.options import Options #ltm url = 'http://loterias.caixa.gov.br/wps/portal/loterias/landing/lotomania/!ut/p/a1/04_Sj9CPykssy0xPLMnMz0vMAfGjzOLNDH0MPAzcDbz8vTxNDRy9_Y2NQ13CDA38jYEKIoEKnN0dPUzMfQwMDEwsjAw8XZw8XMwtfQ0MPM2I02-AAzgaENIfrh-FqsQ9wBmoxN_FydLAGAgNTKEK8DkRrACPGwpyQyMMMj0VAajYsZo!/dl5/d5/L2dBISEvZ0FBIS9nQSEh/pw/Z7_HGK818G0K85260Q5OIRSC42045/res/id=historicoHTML/c=cacheLevelPage/=/' option = Options() option.headless = True driver = webdriver.Chrome(options=option) driver.get(url) time.sleep(10) pagina = driver.find_element_by_xpath('//html//body') html = pagina.get_attribute('outerHTML') soup = BeautifulSoup(html, 'html.parser') tabela = soup.find(name='table') df_full = pd.read_html(str(tabela))[0] df = df_full[['Bola1','Bola2','Bola3','Bola4','Bola5','Bola6','Bola7','Bola8','Bola9','Bola10','Bola11','Bola12','Bola13','Bola14','Bola15','Bola16','Bola17','Bola18','Bola19','Bola20']] df.columns = ['DZ01','DZ02','DZ03','DZ04','DZ05','DZ06','DZ07','DZ08','DZ09','DZ10','DZ11','DZ12','DZ13','DZ14','DZ15','DZ16','DZ17','DZ18','DZ19','DZ20',] df.dropna(axis=0, how='any', inplace=True) resultado = {} resultado = df.to_dict('records') driver.quit() arq=open('ltm.txt','w') tt = 0 mat = [0]*101 vet = [] for n in range(len(resultado)): for p in range(101): mat[p] = mat[p]+1 for k,v in resultado[n].items(): if (k) == 'DZ01': if int((v)) == 0: mat[100] = 0 else: mat[int((v))] = 0 if (k) == 'DZ02': if int((v)) == 0: mat[100] = 0 else: mat[int((v))] = 0 if (k) == 'DZ03': if int((v)) == 0: mat[100] = 0 else: mat[int((v))] = 0 if (k) == 'DZ04': if int((v)) == 0: mat[100] = 0 else: mat[int((v))] = 0 if (k) == 'DZ05': if int((v)) == 0: mat[100] = 0 else: mat[int((v))] = 0 if (k) == 'DZ06': if int((v)) == 0: mat[100] = 0 else: mat[int((v))] = 0 if (k) == 'DZ07': if int((v)) == 0: mat[100] = 0 else: mat[int((v))] = 0 if (k) == 'DZ08': if int((v)) == 0: mat[100] = 0 else: mat[int((v))] = 0 if (k) == 'DZ09': if int((v)) == 0: mat[100] = 0 else: mat[int((v))] = 0 if (k) == 'DZ10': if int((v)) == 0: mat[100] = 0 else: mat[int((v))] = 0 if (k) == 'DZ11': if int((v)) == 0: mat[100] = 0 else: mat[int((v))] = 0 if (k) == 'DZ12': if int((v)) == 0: mat[100] = 0 else: mat[int((v))] = 0 if (k) == 'DZ13': if int((v)) == 0: mat[100] = 0 else: mat[int((v))] = 0 if (k) == 'DZ14': if int((v)) == 0: mat[100] = 0 else: mat[int((v))] = 0 if (k) == 'DZ15': if int((v)) == 0: mat[100] = 0 else: mat[int((v))] = 0 if (k) == 'DZ16': if int((v)) == 0: mat[100] = 0 else: mat[int((v))] = 0 if (k) == 'DZ17': if int((v)) == 0: mat[100] = 0 else: mat[int((v))] = 0 if (k) == 'DZ18': if int((v)) == 0: mat[100] = 0 else: mat[int((v))] = 0 if (k) == 'DZ19': if int((v)) == 0: mat[100] = 0 else: mat[int((v))] = 0 if (k) == 'DZ20': if int((v)) == 0: mat[100] = 0 else: mat[int((v))] = 0 tt+=1 xct='' for p in range(101): if p > 0: xct+=str(mat[p]).zfill(2)+' ' arq.write(xct+'\n') print(xct) del vet[:] arq.close() Edited April 19, 2021 by luiz.antonio 2 Quote Link to comment Share on other sites More sharing options...
Bruno Cintra Posted April 19, 2021 Share Posted April 19, 2021 3 horas atrás, luiz.antonio disse: Boa Tarde ! O Código abaixo faz um web scraping no site da caixa (resultado da lotomania), pega todos os resultados e gera um arquivo "ltm.txt" onde mostra o atraso de cada uma das 100 dezenas. * pra rodar o programa é preciso ter o python instalado e as libs instaladas, caso for instalar o python agora, após instalar...abra o cmd e digite: python -m pip install --upgrade pip (enter) pip instalar pandas (entrar) solicitações de instalação pip (entrar) pip install bs4 (entrar) pip instalar selênio (entrar) import time import requests import pandas as pd from bs4 import BeautifulSoup from selenium import webdriver from selenium.webdriver.chrome.options import Options #ltm url = 'http://loterias.caixa.gov.br/wps/portal/loterias/landing/lotomania/!ut/p/a1/04_Sj9CPykssy0xPLMnMz0vMAfGjzOLNDH0MPAzcDbz8vTxNDRy9_Y2NQ13CDA38jYEKIoEKnN0dPUzMfQwMDEwsjAw8XZw8XMwtfQ0MPM2I02-AAzgaENIfrh-FqsQ9wBmoxN_FydLAGAgNTKEK8DkRrACPGwpyQyMMMj0VAajYsZo!/dl5/d5/L2dBISEvZ0FBIS9nQSEh/pw/Z7_HGK818G0K85260Q5OIRSC42045/res/id=historicoHTML/c=cacheLevelPage/=/' option = Options() option.headless = True driver = webdriver.Chrome(options=option) driver.get(url) time.sleep(10) pagina = driver.find_element_by_xpath('//html//body') html = pagina.get_attribute('outerHTML') soup = BeautifulSoup(html, 'html.parser') tabela = soup.find(name='table') df_full = pd.read_html(str(tabela))[0] df = df_full[['Bola1','Bola2','Bola3','Bola4','Bola5','Bola6','Bola7','Bola8','Bola9','Bola10','Bola11','Bola12','Bola13','Bola14','Bola15','Bola16','Bola17','Bola18','Bola19','Bola20']] df.columns = ['DZ01','DZ02','DZ03','DZ04','DZ05','DZ06','DZ07','DZ08','DZ09','DZ10','DZ11','DZ12','DZ13','DZ14','DZ15','DZ16','DZ17','DZ18','DZ19','DZ20',] df.dropna(axis=0, how='any', inplace=True) resultado = {} resultado = df.to_dict('records') driver.quit() arq=open('ltm.txt','w') tt = 0 mat = [0]*101 vet = [] for n in range(len(resultado)): for p in range(101): mat[p] = mat[p]+1 for k,v in resultado[n].items(): if (k) == 'DZ01': if int((v)) == 0: mat[100] = 0 else: mat[int((v))] = 0 if (k) == 'DZ02': if int((v)) == 0: mat[100] = 0 else: mat[int((v))] = 0 if (k) == 'DZ03': if int((v)) == 0: mat[100] = 0 else: mat[int((v))] = 0 if (k) == 'DZ04': if int((v)) == 0: mat[100] = 0 else: mat[int((v))] = 0 if (k) == 'DZ05': if int((v)) == 0: mat[100] = 0 else: mat[int((v))] = 0 if (k) == 'DZ06': if int((v)) == 0: mat[100] = 0 else: mat[int((v))] = 0 if (k) == 'DZ07': if int((v)) == 0: mat[100] = 0 else: mat[int((v))] = 0 if (k) == 'DZ08': if int((v)) == 0: mat[100] = 0 else: mat[int((v))] = 0 if (k) == 'DZ09': if int((v)) == 0: mat[100] = 0 else: mat[int((v))] = 0 if (k) == 'DZ10': if int((v)) == 0: mat[100] = 0 else: mat[int((v))] = 0 if (k) == 'DZ11': if int((v)) == 0: mat[100] = 0 else: mat[int((v))] = 0 if (k) == 'DZ12': if int((v)) == 0: mat[100] = 0 else: mat[int((v))] = 0 if (k) == 'DZ13': if int((v)) == 0: mat[100] = 0 else: mat[int((v))] = 0 if (k) == 'DZ14': if int((v)) == 0: mat[100] = 0 else: mat[int((v))] = 0 if (k) == 'DZ15': if int((v)) == 0: mat[100] = 0 else: mat[int((v))] = 0 if (k) == 'DZ16': if int((v)) == 0: mat[100] = 0 else: mat[int((v))] = 0 if (k) == 'DZ17': if int((v)) == 0: mat[100] = 0 else: mat[int((v))] = 0 if (k) == 'DZ18': if int((v)) == 0: mat[100] = 0 else: mat[int((v))] = 0 if (k) == 'DZ19': if int((v)) == 0: mat[100] = 0 else: mat[int((v))] = 0 if (k) == 'DZ20': if int((v)) == 0: mat[100] = 0 else: mat[int((v))] = 0 tt+=1 xct='' for p in range(101): if p > 0: xct+=str(mat[p]).zfill(2)+' ' arq.write(xct+'\n') print(xct) del vet[:] arq.close() vc conseguiu rodar o codigo que postei,estou tentando modificar para gerar numeros maiores mais rapido,nao sei se vai dar ,gera v,k,t,m Quote Link to comment Share on other sites More sharing options...
Bruno Cintra Posted April 19, 2021 Share Posted April 19, 2021 3 horas atrás, luiz.antonio disse: Boa Tarde ! O Código abaixo faz um web scraping no site da caixa (resultado da lotomania), pega todos os resultados e gera um arquivo "ltm.txt" onde mostra o atraso de cada uma das 100 dezenas. * pra rodar o programa é preciso ter o python instalado e as libs instaladas, caso for instalar o python agora, após instalar...abra o cmd e digite: python -m pip install --upgrade pip (enter) pip install pandas (enter) pip install requests (enter) pip install bs4 (enter) pip install selenium (enter) import time import requests import pandas as pd from bs4 import BeautifulSoup from selenium import webdriver from selenium.webdriver.chrome.options import Options #ltm url = 'http://loterias.caixa.gov.br/wps/portal/loterias/landing/lotomania/!ut/p/a1/04_Sj9CPykssy0xPLMnMz0vMAfGjzOLNDH0MPAzcDbz8vTxNDRy9_Y2NQ13CDA38jYEKIoEKnN0dPUzMfQwMDEwsjAw8XZw8XMwtfQ0MPM2I02-AAzgaENIfrh-FqsQ9wBmoxN_FydLAGAgNTKEK8DkRrACPGwpyQyMMMj0VAajYsZo!/dl5/d5/L2dBISEvZ0FBIS9nQSEh/pw/Z7_HGK818G0K85260Q5OIRSC42045/res/id=historicoHTML/c=cacheLevelPage/=/' option = Options() option.headless = True driver = webdriver.Chrome(options=option) driver.get(url) time.sleep(10) pagina = driver.find_element_by_xpath('//html//body') html = pagina.get_attribute('outerHTML') soup = BeautifulSoup(html, 'html.parser') tabela = soup.find(name='table') df_full = pd.read_html(str(tabela))[0] df = df_full[['Bola1','Bola2','Bola3','Bola4','Bola5','Bola6','Bola7','Bola8','Bola9','Bola10','Bola11','Bola12','Bola13','Bola14','Bola15','Bola16','Bola17','Bola18','Bola19','Bola20']] df.columns = ['DZ01','DZ02','DZ03','DZ04','DZ05','DZ06','DZ07','DZ08','DZ09','DZ10','DZ11','DZ12','DZ13','DZ14','DZ15','DZ16','DZ17','DZ18','DZ19','DZ20',] df.dropna(axis=0, how='any', inplace=True) resultado = {} resultado = df.to_dict('records') driver.quit() arq=open('ltm.txt','w') tt = 0 mat = [0]*101 vet = [] for n in range(len(resultado)): for p in range(101): mat[p] = mat[p]+1 for k,v in resultado[n].items(): if (k) == 'DZ01': if int((v)) == 0: mat[100] = 0 else: mat[int((v))] = 0 if (k) == 'DZ02': if int((v)) == 0: mat[100] = 0 else: mat[int((v))] = 0 if (k) == 'DZ03': if int((v)) == 0: mat[100] = 0 else: mat[int((v))] = 0 if (k) == 'DZ04': if int((v)) == 0: mat[100] = 0 else: mat[int((v))] = 0 if (k) == 'DZ05': if int((v)) == 0: mat[100] = 0 else: mat[int((v))] = 0 if (k) == 'DZ06': if int((v)) == 0: mat[100] = 0 else: mat[int((v))] = 0 if (k) == 'DZ07': if int((v)) == 0: mat[100] = 0 else: mat[int((v))] = 0 if (k) == 'DZ08': if int((v)) == 0: mat[100] = 0 else: mat[int((v))] = 0 if (k) == 'DZ09': if int((v)) == 0: mat[100] = 0 else: mat[int((v))] = 0 if (k) == 'DZ10': if int((v)) == 0: mat[100] = 0 else: mat[int((v))] = 0 if (k) == 'DZ11': if int((v)) == 0: mat[100] = 0 else: mat[int((v))] = 0 if (k) == 'DZ12': if int((v)) == 0: mat[100] = 0 else: mat[int((v))] = 0 if (k) == 'DZ13': if int((v)) == 0: mat[100] = 0 else: mat[int((v))] = 0 if (k) == 'DZ14': if int((v)) == 0: mat[100] = 0 else: mat[int((v))] = 0 if (k) == 'DZ15': if int((v)) == 0: mat[100] = 0 else: mat[int((v))] = 0 if (k) == 'DZ16': if int((v)) == 0: mat[100] = 0 else: mat[int((v))] = 0 if (k) == 'DZ17': if int((v)) == 0: mat[100] = 0 else: mat[int((v))] = 0 if (k) == 'DZ18': if int((v)) == 0: mat[100] = 0 else: mat[int((v))] = 0 if (k) == 'DZ19': if int((v)) == 0: mat[100] = 0 else: mat[int((v))] = 0 if (k) == 'DZ20': if int((v)) == 0: mat[100] = 0 else: mat[int((v))] = 0 tt+=1 xct='' for p in range(101): if p > 0: xct+=str(mat[p]).zfill(2)+' ' arq.write(xct+'\n') print(xct) del vet[:] arq.close() daria para converter o codigo que postei para C? Quote Link to comment Share on other sites More sharing options...
luiz.antonio Posted April 19, 2021 Author Share Posted April 19, 2021 20 minutos atrás, Bruno Cintra disse: daria para converter o codigo que postei para C? Boa Tarde Bruno ! Rodei o programa, funcionou, mas não verifiquei se o código poderia ser melhorado, quanto a converter entre linguagens..sim é perfeitamente possível....o problema é tempo...rsrs Paz e Prosperidade. Luiz Quote Link to comment Share on other sites More sharing options...
luiz.antonio Posted April 19, 2021 Author Share Posted April 19, 2021 8 horas atrás, luiz.antonio disse: Boa Tarde ! O Código abaixo faz um web scraping no site da caixa (resultado da lotomania), pega todos os resultados e gera um arquivo "ltm.txt" onde mostra o atraso de cada uma das 100 dezenas. * pra rodar o programa é preciso ter o python instalado e as libs instaladas, caso for instalar o python agora, após instalar...abra o cmd e digite: python -m pip install --upgrade pip (enter) pip install pandas (enter) pip install requests (enter) pip install bs4 (enter) pip install selenium (enter) import time import requests import pandas as pd from bs4 import BeautifulSoup from selenium import webdriver from selenium.webdriver.chrome.options import Options #ltm url = 'http://loterias.caixa.gov.br/wps/portal/loterias/landing/lotomania/!ut/p/a1/04_Sj9CPykssy0xPLMnMz0vMAfGjzOLNDH0MPAzcDbz8vTxNDRy9_Y2NQ13CDA38jYEKIoEKnN0dPUzMfQwMDEwsjAw8XZw8XMwtfQ0MPM2I02-AAzgaENIfrh-FqsQ9wBmoxN_FydLAGAgNTKEK8DkRrACPGwpyQyMMMj0VAajYsZo!/dl5/d5/L2dBISEvZ0FBIS9nQSEh/pw/Z7_HGK818G0K85260Q5OIRSC42045/res/id=historicoHTML/c=cacheLevelPage/=/' option = Options() option.headless = True driver = webdriver.Chrome(options=option) driver.get(url) time.sleep(10) pagina = driver.find_element_by_xpath('//html//body') html = pagina.get_attribute('outerHTML') soup = BeautifulSoup(html, 'html.parser') tabela = soup.find(name='table') df_full = pd.read_html(str(tabela))[0] df = df_full[['Bola1','Bola2','Bola3','Bola4','Bola5','Bola6','Bola7','Bola8','Bola9','Bola10','Bola11','Bola12','Bola13','Bola14','Bola15','Bola16','Bola17','Bola18','Bola19','Bola20']] df.columns = ['DZ01','DZ02','DZ03','DZ04','DZ05','DZ06','DZ07','DZ08','DZ09','DZ10','DZ11','DZ12','DZ13','DZ14','DZ15','DZ16','DZ17','DZ18','DZ19','DZ20',] df.dropna(axis=0, how='any', inplace=True) resultado = {} resultado = df.to_dict('records') driver.quit() arq=open('ltm.txt','w') tt = 0 mat = [0]*101 vet = [] for n in range(len(resultado)): for p in range(101): mat[p] = mat[p]+1 for k,v in resultado[n].items(): if (k) == 'DZ01': if int((v)) == 0: mat[100] = 0 else: mat[int((v))] = 0 if (k) == 'DZ02': if int((v)) == 0: mat[100] = 0 else: mat[int((v))] = 0 if (k) == 'DZ03': if int((v)) == 0: mat[100] = 0 else: mat[int((v))] = 0 if (k) == 'DZ04': if int((v)) == 0: mat[100] = 0 else: mat[int((v))] = 0 if (k) == 'DZ05': if int((v)) == 0: mat[100] = 0 else: mat[int((v))] = 0 if (k) == 'DZ06': if int((v)) == 0: mat[100] = 0 else: mat[int((v))] = 0 if (k) == 'DZ07': if int((v)) == 0: mat[100] = 0 else: mat[int((v))] = 0 if (k) == 'DZ08': if int((v)) == 0: mat[100] = 0 else: mat[int((v))] = 0 if (k) == 'DZ09': if int((v)) == 0: mat[100] = 0 else: mat[int((v))] = 0 if (k) == 'DZ10': if int((v)) == 0: mat[100] = 0 else: mat[int((v))] = 0 if (k) == 'DZ11': if int((v)) == 0: mat[100] = 0 else: mat[int((v))] = 0 if (k) == 'DZ12': if int((v)) == 0: mat[100] = 0 else: mat[int((v))] = 0 if (k) == 'DZ13': if int((v)) == 0: mat[100] = 0 else: mat[int((v))] = 0 if (k) == 'DZ14': if int((v)) == 0: mat[100] = 0 else: mat[int((v))] = 0 if (k) == 'DZ15': if int((v)) == 0: mat[100] = 0 else: mat[int((v))] = 0 if (k) == 'DZ16': if int((v)) == 0: mat[100] = 0 else: mat[int((v))] = 0 if (k) == 'DZ17': if int((v)) == 0: mat[100] = 0 else: mat[int((v))] = 0 if (k) == 'DZ18': if int((v)) == 0: mat[100] = 0 else: mat[int((v))] = 0 if (k) == 'DZ19': if int((v)) == 0: mat[100] = 0 else: mat[int((v))] = 0 if (k) == 'DZ20': if int((v)) == 0: mat[100] = 0 else: mat[int((v))] = 0 tt+=1 xct='' for p in range(101): if p > 0: xct+=str(mat[p]).zfill(2)+' ' arq.write(xct+'\n') print(xct) del vet[:] arq.close() Perdão...faltou um pacote para instalar. * pip install lxml 1 Quote Link to comment Share on other sites More sharing options...
rockcavera Posted April 20, 2021 Share Posted April 20, 2021 22 horas atrás, Bruno Cintra disse: vc conseguiu rodar o codigo que postei,estou tentando modificar para gerar numeros maiores mais rapido,nao sei se vai dar ,gera v,k,t,m Sei que não perguntou para mim, mas o código acima pode ser melhorado sim. Tem várias coisinhas que podem ser feitas de outras formas que vão fazer o desempenho saltar. 22 horas atrás, Bruno Cintra disse: daria para converter o codigo que postei para C? A conversão é muito fácil. Eu converti para Nim em menos de 2 horas, isso sem saber Python. Fui olhando tutorial de Python e fazendo a transcrição do código. Funcionou perfeitamente e rodou cerca de 35 vezes mais rápido, isso sem fazer qualquer otimização. No entanto, não vale a penas otimizar o código, pois o algoritmo é simples e não é vantajoso. Praticamente uma versão sem otimizações do gencover meu. Ou seja, ele gera todas combinações de V,M e V,K, depois fica adicionando combinações de V,K na matriz de saída até que todas as combinações de V,M estejam cobertas segundo a garantia T. A seleção das combinações de V,K, que irão compor a matriz são feita da seguinte maneira a cada adição: verifica-se todas as combinações de V,K restantes com as combinações de V,M restantes e pega-se a combinações de V,K que mais elimina combinações de V,M. É simples assim. Com certeza é um dos métodos mais simples de gerar matrizes/desdobramentos/fechamentos (ou qualquer outro nome que dê para isso). Quem quiser o código Nim, conversão nua e crua, apenas com ajustes para se comportar igual ao código Python original: # Tradução para Nim do código Python em https://thelotteryforum.com/code-skulptor.php?id=user303_FzKynHVfSjm4VIx import std/[algorithm, strutils] const ch = ['A','B','C','D','E','F','G','H','I','J','K','L'] # v if_match = 5 # m min_match = 3 # t numbers_per_ticket = 5 # k proc check(ind: var seq[int], i, group_size, l: int): int = if i >= 0: ind[i] += 1 if ind[i] > (l - 1 - (group_size - 1 - i)): return check(ind, i - 1, group_size, l) else: return i else: return i - 1 proc combinations(li: openarray[char], group_size: int): seq[tuple[comb: seq[char], count: int]] = var index = newSeq[int](group_size) for i in 0 ..< group_size: index[i] = i let l = len(li) while index[0] <= (l - group_size): var comb = newSeqOfCap[char](group_size) for z in 0 ..< group_size: add(comb, li[index[z]]) add(result, (comb, 0)) let i = group_size - 1 lowestchange = check(index, i, group_size, l) for j in (lowestchange + 1) ..< group_size: # Índices negativos em Python retornam a lista na ordem de traz para frente. # Em Nim dá erro. Este código faz ter o mesmo comportamento de Python. if j > 0: index[j] = index[j - 1] + 1 elif j == 0: index[0] = index[^1] + 1 else: let i1 = abs(j) i2 = abs(j - 1) index[^i1] = index[^i2] + 1 proc row_match(row1, check1: seq[char]): int = for item in row1: if item in check1: result += 1 var dot_count = 1 proc row_matches_count(clist, checklist: var seq[tuple[comb: seq[char], count: int]]) = for i in 0 ..< len(checklist): write(stdout, '.') dot_count += 1 if (dot_count mod 100) == 0: dot_count = 1 write(stdout, '\n') checklist[i].count = 0 for k in 0 ..< len(clist): if clist[k].count == 0: let c = row_match(clist[k].comb, checklist[i].comb) if c >= min_match: checklist[i].count += 1 proc allchecked(clist: seq[tuple[comb: seq[char], count: int]]): bool = for clistrow in clist: if clistrow.count == 0: return false return true proc markcheck(clist: var seq[tuple[comb: seq[char], count: int]], checkrow: seq[char]) = for i in 0 ..< len(clist): if clist[i].count == 0: let c = row_match(clist[i].comb, checkrow) if c >= min_match: clist[i].count = 1 proc myCmp(a, b: tuple[comb: seq[char], count: int]): int = # Código adicionado para comparação e ordenação. if a.count == b.count: return 0 elif a.count < b.count: return -1 else: return 1 var comb = combinations(ch, if_match) mylist = combinations(ch, numbers_per_ticket) var keys: seq[seq[char]] while not allchecked(comb): echo "\nProcessing..." row_matches_count(comb,mylist) sort(mylist, myCmp, Descending) add(keys, mylist[0].comb) markcheck(comb, mylist[0].comb) del(mylist, 0) echo "\nPossible Result, buys followed by number of match" for i in 0 ..< len(comb): let linenum = i + 1 write(stdout, linenum, "-result ") let checkrow = comb[i].comb write(stdout, join(checkrow, ""), " buys: ") for key in keys: let c = row_match(checkrow, key) write(stdout, join(key, ""), " ", c, " ") write(stdout, '\n') echo "number of key lines: ", len(keys) write(stdout, "Keys: ") for key in keys: write(stdout, join(key, ""), " ") echo "" echo "\n", len(ch), " Wheel, if match ", if_match, ", win ", min_match, " with ", len(keys), " tickets (", numbers_per_ticket, " numbers per ticket)." echo "end program!" Obs: a impressão de caracteres na tela é mais lerda no Nim que no Python. O teste de velocidade que fiz, eu comentei as impressões desnecessárias, apenas retornando a matriz gerada. Essa lerdeza da impressão no Nim se dá principalmente no Windows que o cmd.exe (prompt de comandos) é por buffer e o Nim até hoje não otimizou a impressão. Obs2: Nim gera código C não muito legível para inexperientes. 1 Quote Link to comment Share on other sites More sharing options...
Bruno Cintra Posted April 20, 2021 Share Posted April 20, 2021 1 hora atrás, rockcavera disse: Sei que não perguntou para mim, mas o código acima pode ser melhorado sim. Tem várias coisinhas que podem ser feitas de outras formas que vão fazer o desempenho saltar. A conversão é muito fácil. Eu converti para Nim em menos de 2 horas, isso sem saber Python. Fui olhando tutorial de Python e fazendo a transcrição do código. Funcionou perfeitamente e rodou cerca de 35 vezes mais rápido, isso sem fazer qualquer otimização. No entanto, não vale a penas otimizar o código, pois o algoritmo é simples e não é vantajoso. Praticamente uma versão sem otimizações do gencover meu. Ou seja, ele gera todas combinações de V,M e V,K, depois fica adicionando combinações de V,K na matriz de saída até que todas as combinações de V,M estejam cobertas segundo a garantia T. A seleção das combinações de V,K, que irão compor a matriz são feita da seguinte maneira a cada adição: verifica-se todas as combinações de V,K restantes com as combinações de V,M restantes e pega-se a combinações de V,K que mais elimina combinações de V,M. É simples assim. Com certeza é um dos métodos mais simples de gerar matrizes/desdobramentos/fechamentos (ou qualquer outro nome que dê para isso). Quem quiser o código Nim, conversão nua e crua, apenas com ajustes para se comportar igual ao código Python original: # Tradução para Nim do código Python em https://thelotteryforum.com/code-skulptor.php?id=user303_FzKynHVfSjm4VIx import std/[algorithm, strutils] const ch = ['A','B','C','D','E','F','G','H','I','J','K','L'] # v if_match = 5 # m min_match = 3 # t numbers_per_ticket = 5 # k proc check(ind: var seq[int], i, group_size, l: int): int = if i >= 0: ind[i] += 1 if ind[i] > (l - 1 - (group_size - 1 - i)): return check(ind, i - 1, group_size, l) else: return i else: return i - 1 proc combinations(li: openarray[char], group_size: int): seq[tuple[comb: seq[char], count: int]] = var index = newSeq[int](group_size) for i in 0 ..< group_size: index[i] = i let l = len(li) while index[0] <= (l - group_size): var comb = newSeqOfCap[char](group_size) for z in 0 ..< group_size: add(comb, li[index[z]]) add(result, (comb, 0)) let i = group_size - 1 lowestchange = check(index, i, group_size, l) for j in (lowestchange + 1) ..< group_size: # Índices negativos em Python retornam a lista na ordem de traz para frente. # Em Nim dá erro. Este código faz ter o mesmo comportamento de Python. if j > 0: index[j] = index[j - 1] + 1 elif j == 0: index[0] = index[^1] + 1 else: let i1 = abs(j) i2 = abs(j - 1) index[^i1] = index[^i2] + 1 proc row_match(row1, check1: seq[char]): int = for item in row1: if item in check1: result += 1 var dot_count = 1 proc row_matches_count(clist, checklist: var seq[tuple[comb: seq[char], count: int]]) = for i in 0 ..< len(checklist): write(stdout, '.') dot_count += 1 if (dot_count mod 100) == 0: dot_count = 1 write(stdout, '\n') checklist[i].count = 0 for k in 0 ..< len(clist): if clist[k].count == 0: let c = row_match(clist[k].comb, checklist[i].comb) if c >= min_match: checklist[i].count += 1 proc allchecked(clist: seq[tuple[comb: seq[char], count: int]]): bool = for clistrow in clist: if clistrow.count == 0: return false return true proc markcheck(clist: var seq[tuple[comb: seq[char], count: int]], checkrow: seq[char]) = for i in 0 ..< len(clist): if clist[i].count == 0: let c = row_match(clist[i].comb, checkrow) if c >= min_match: clist[i].count = 1 proc myCmp(a, b: tuple[comb: seq[char], count: int]): int = # Código adicionado para comparação e ordenação. if a.count == b.count: return 0 elif a.count < b.count: return -1 else: return 1 var comb = combinations(ch, if_match) mylist = combinations(ch, numbers_per_ticket) var keys: seq[seq[char]] while not allchecked(comb): echo "\nProcessing..." row_matches_count(comb,mylist) sort(mylist, myCmp, Descending) add(keys, mylist[0].comb) markcheck(comb, mylist[0].comb) del(mylist, 0) echo "\nPossible Result, buys followed by number of match" for i in 0 ..< len(comb): let linenum = i + 1 write(stdout, linenum, "-result ") let checkrow = comb[i].comb write(stdout, join(checkrow, ""), " buys: ") for key in keys: let c = row_match(checkrow, key) write(stdout, join(key, ""), " ", c, " ") write(stdout, '\n') echo "number of key lines: ", len(keys) write(stdout, "Keys: ") for key in keys: write(stdout, join(key, ""), " ") echo "" echo "\n", len(ch), " Wheel, if match ", if_match, ", win ", min_match, " with ", len(keys), " tickets (", numbers_per_ticket, " numbers per ticket)." echo "end program!" Obs: a impressão de caracteres na tela é mais lerda no Nim que no Python. O teste de velocidade que fiz, eu comentei as impressões desnecessárias, apenas retornando a matriz gerada. Essa lerdeza da impressão no Nim se dá principalmente no Windows que o cmd.exe (prompt de comandos) é por buffer e o Nim até hoje não otimizou a impressão. Obs2: Nim gera código C não muito legível para inexperientes. obrigado,qualquer um que responde-se seria bem vindo 1 Quote Link to comment Share on other sites More sharing options...
rockcavera Posted April 20, 2021 Share Posted April 20, 2021 1 hora atrás, Bruno Cintra disse: obrigado,qualquer um que responde-se seria bem vindo Só para não passar batido, vou explicar o motivo de não compensar otimizar tal código. Existem outras formas de se obter matrizes/desdobramentos/sistemas/fechamentos que são mais atuais que essa lógica deste programa. Não desmerecendo, até porque esta é uma lógica comum quando se entende o que é preciso para gerar um sistema. Só o fato de você conseguir chegar neste entendimento já lhe dá méritos, ainda mais fazendo sozinho. Ocorre que, esse método nem sempre vai trazer a melhor solução, mas pode ser usado para encurtar a utilização de outros métodos mais elaborados, como: Problem Dependent Optimization (PDO) e Simulated Annealing. Com certeza existe coisa melhor ainda, pois existe muita gente inteligente pesquisando e criando algoritmos para isso, mas não necessariamente para uso em loterias. Você mesmo já me passou links usando estes métodos. Abraço. 1 Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.