Sorteio números aleatórios
Por favor se alguém souber me ajude, estou precisando urgente.
Pensei que tivesse solucionado o problema do sorteio, mas quando faço um determinado filtro não está posicionando no registro correto. Está sorteando um registro da tabela de pesquisa, mas está gravando outro na tabela de Sorteio.
Preciso sortear um ou mais registro(s) aleatório(s) da tabela de pesquisa e gravar o(s) registro(s) sorteado(s) na tabela de sorteio para depois fazer um filtro e jogar num grid.
Onde está o erro e o que devo fazer para não sortear o mesmo registro mais de uma vez(está faltando isto)?
Urgente!!!! Agradeço a quem puder ajudar.
procedure TfrmSorteio.SpeedButton1Click(Sender: TObject);
var j,i,numsorteado:integer;
s:string;
begin
qrSorteio.Close;
qrSorteio.SQL.Clear;
qrSorteio.SQL.Add(´ select nome, bairro, rg, telefone, celular, email, premio, promocao, data, hora from pesquisa´);
qrSorteio.SQL.Add(´where data between :datai and :dataf´);
qrSorteio.ParamByName(´datai´).DataType:=ftdate;
qrSorteio.ParamByName(´datai´).ParamType:=ptInputOutput;
qrSorteio.ParamByName(´datai´).AsDate:=dtmini.Date;
qrSorteio.ParamByName(´dataf´).DataType:=ftdate;
qrSorteio.ParamByName(´dataf´).ParamType:=ptInputOutput;
qrSorteio.ParamByName(´dataf´).AsDate:=dtmfim.Date;
qrSorteio.SQL.Add(´and hora between :horai and :horaf´);
qrSorteio.ParamByName(´horai´).datatype:=fttime;
qrSorteio.ParamByName(´horai´).paramtype:=ptinputoutput;
qrSorteio.ParamByName(´horai´).AsTime:=dtmhorai.Time;
qrSorteio.ParamByName(´horaf´).DataType:=fttime;
qrSorteio.ParamByName(´horaf´).paramtype:=ptinputoutput;
qrSorteio.ParamByName(´horaf´).Astime:=dtmhoraf.Time;
qrSorteio.SQL.Add(´and premio=:premio´);
qrsorteio.ParamByName(´premio´).DataType:=ftInteger;
qrsorteio.ParamByName(´premio´).ParamType:=ptInputOutput;
qrSorteio.ParamByName(´premio´).AsInteger:=dm.tbPremiosCODIGO.AsInteger;
qrSorteio.SQL.Add(´or premio is null´);
qrSorteio.Prepare;
qrSorteio.Open;
if qrSorteio.RecordCount > 0 then
begin
i:=qrSorteio.RecordCount;
Randomize;
for j := 1 to spcount.Value do
begin
numsorteado:=Random(i);
ShowMessage(´Numero sorteado: ´ + IntToStr(numsorteado));
qrSorteio.First;
qrSorteio.MoveBy(numsorteado-1);
dm.tbSorteio.Append;
dm.tbSorteioNOME.Value:=qrSorteio.fieldbyname(´nome´).AsString;
dm.tbBairros.findkey([qrSorteio.FieldByName(´BAIRRO´).AsInteger]);
dm.tbSorteioBAIRRO.Value:=dm.tbBairrosNOME.AsString;
dm.tbSorteioRG.Value:=qrSorteio.fieldbyname(´rg´).AsString;
dm.tbSorteioTELEFONE.Value:=qrSorteio.fieldbyname(´telefone´).AsString;
dm.tbSorteioCELULAR.Value:=qrSorteio.fieldbyname(´celular´).AsString;
dm.tbSorteioEMAIL.Value:=qrSorteio.fieldbyname(´email´).AsString;
dm.tbSorteioPREMIO.Value:=dm.tbPremiosDESCRICAO.AsString;
dm.tbSorteioDATA.Value:=qrSorteio.fieldbyname(´data´).AsDateTime;
dm.tbSorteioHORA.Value:=qrSorteio.fieldbyname(´hora´).AsDateTime;
dm.tbSorteio.Post;
end;
qrSorteados.Close;
qrSorteados.SQL.Clear;
qrSorteados.SQL.Add(´ select nome, bairro, RG, TELEFONE, CELULAR, EMAIL, PREMIO, PROMOCAO, DATA, HORA from sorteio´);
qrSorteados.SQL.Add(´where data between :datai and :dataf´);
qrSorteados.ParamByName(´datai´).DataType:=ftdate;
qrSorteados.ParamByName(´datai´).ParamType:=ptInputOutput;
qrSorteados.ParamByName(´datai´).AsDate:=dtmini.Date;
qrSorteados.ParamByName(´dataf´).DataType:=ftdate;
qrSorteados.ParamByName(´dataf´).ParamType:=ptInputOutput;
qrSorteados.ParamByName(´dataf´).AsDate:=dtmfim.Date;
qrSorteados.SQL.Add(´and hora between :horai and :horaf´);
qrSorteados.ParamByName(´horai´).datatype:=fttime;
qrSorteados.ParamByName(´horai´).paramtype:=ptinputoutput;
qrSorteados.ParamByName(´horai´).AsTime:=dtmhorai.Time;
qrSorteados.ParamByName(´horaf´).DataType:=fttime;
qrSorteados.ParamByName(´horaf´).paramtype:=ptinputoutput;
qrSorteados.ParamByName(´horaf´).Astime:=dtmhoraf.Time;
qrSorteados.SQL.Add(´and premio=:premio´);
qrsorteados.ParamByName(´premio´).DataType:=ftstring;
qrsorteados.ParamByName(´premio´).ParamType:=ptInputOutput;
qrSorteados.ParamByName(´premio´).Asstring:=dm.tbPremiosDESCRICAO.asstring;
qrSorteados.Prepare;
qrSorteados.Open;
if frmSorteados = nil then
frmSorteados:=TfrmSorteados.create(self);
frmSorteados.showmodal;
end
else showmessage(´Não há dados para os parâmetros informados...´);
end;
Pensei que tivesse solucionado o problema do sorteio, mas quando faço um determinado filtro não está posicionando no registro correto. Está sorteando um registro da tabela de pesquisa, mas está gravando outro na tabela de Sorteio.
Preciso sortear um ou mais registro(s) aleatório(s) da tabela de pesquisa e gravar o(s) registro(s) sorteado(s) na tabela de sorteio para depois fazer um filtro e jogar num grid.
Onde está o erro e o que devo fazer para não sortear o mesmo registro mais de uma vez(está faltando isto)?
Urgente!!!! Agradeço a quem puder ajudar.
procedure TfrmSorteio.SpeedButton1Click(Sender: TObject);
var j,i,numsorteado:integer;
s:string;
begin
qrSorteio.Close;
qrSorteio.SQL.Clear;
qrSorteio.SQL.Add(´ select nome, bairro, rg, telefone, celular, email, premio, promocao, data, hora from pesquisa´);
qrSorteio.SQL.Add(´where data between :datai and :dataf´);
qrSorteio.ParamByName(´datai´).DataType:=ftdate;
qrSorteio.ParamByName(´datai´).ParamType:=ptInputOutput;
qrSorteio.ParamByName(´datai´).AsDate:=dtmini.Date;
qrSorteio.ParamByName(´dataf´).DataType:=ftdate;
qrSorteio.ParamByName(´dataf´).ParamType:=ptInputOutput;
qrSorteio.ParamByName(´dataf´).AsDate:=dtmfim.Date;
qrSorteio.SQL.Add(´and hora between :horai and :horaf´);
qrSorteio.ParamByName(´horai´).datatype:=fttime;
qrSorteio.ParamByName(´horai´).paramtype:=ptinputoutput;
qrSorteio.ParamByName(´horai´).AsTime:=dtmhorai.Time;
qrSorteio.ParamByName(´horaf´).DataType:=fttime;
qrSorteio.ParamByName(´horaf´).paramtype:=ptinputoutput;
qrSorteio.ParamByName(´horaf´).Astime:=dtmhoraf.Time;
qrSorteio.SQL.Add(´and premio=:premio´);
qrsorteio.ParamByName(´premio´).DataType:=ftInteger;
qrsorteio.ParamByName(´premio´).ParamType:=ptInputOutput;
qrSorteio.ParamByName(´premio´).AsInteger:=dm.tbPremiosCODIGO.AsInteger;
qrSorteio.SQL.Add(´or premio is null´);
qrSorteio.Prepare;
qrSorteio.Open;
if qrSorteio.RecordCount > 0 then
begin
i:=qrSorteio.RecordCount;
Randomize;
for j := 1 to spcount.Value do
begin
numsorteado:=Random(i);
ShowMessage(´Numero sorteado: ´ + IntToStr(numsorteado));
qrSorteio.First;
qrSorteio.MoveBy(numsorteado-1);
dm.tbSorteio.Append;
dm.tbSorteioNOME.Value:=qrSorteio.fieldbyname(´nome´).AsString;
dm.tbBairros.findkey([qrSorteio.FieldByName(´BAIRRO´).AsInteger]);
dm.tbSorteioBAIRRO.Value:=dm.tbBairrosNOME.AsString;
dm.tbSorteioRG.Value:=qrSorteio.fieldbyname(´rg´).AsString;
dm.tbSorteioTELEFONE.Value:=qrSorteio.fieldbyname(´telefone´).AsString;
dm.tbSorteioCELULAR.Value:=qrSorteio.fieldbyname(´celular´).AsString;
dm.tbSorteioEMAIL.Value:=qrSorteio.fieldbyname(´email´).AsString;
dm.tbSorteioPREMIO.Value:=dm.tbPremiosDESCRICAO.AsString;
dm.tbSorteioDATA.Value:=qrSorteio.fieldbyname(´data´).AsDateTime;
dm.tbSorteioHORA.Value:=qrSorteio.fieldbyname(´hora´).AsDateTime;
dm.tbSorteio.Post;
end;
qrSorteados.Close;
qrSorteados.SQL.Clear;
qrSorteados.SQL.Add(´ select nome, bairro, RG, TELEFONE, CELULAR, EMAIL, PREMIO, PROMOCAO, DATA, HORA from sorteio´);
qrSorteados.SQL.Add(´where data between :datai and :dataf´);
qrSorteados.ParamByName(´datai´).DataType:=ftdate;
qrSorteados.ParamByName(´datai´).ParamType:=ptInputOutput;
qrSorteados.ParamByName(´datai´).AsDate:=dtmini.Date;
qrSorteados.ParamByName(´dataf´).DataType:=ftdate;
qrSorteados.ParamByName(´dataf´).ParamType:=ptInputOutput;
qrSorteados.ParamByName(´dataf´).AsDate:=dtmfim.Date;
qrSorteados.SQL.Add(´and hora between :horai and :horaf´);
qrSorteados.ParamByName(´horai´).datatype:=fttime;
qrSorteados.ParamByName(´horai´).paramtype:=ptinputoutput;
qrSorteados.ParamByName(´horai´).AsTime:=dtmhorai.Time;
qrSorteados.ParamByName(´horaf´).DataType:=fttime;
qrSorteados.ParamByName(´horaf´).paramtype:=ptinputoutput;
qrSorteados.ParamByName(´horaf´).Astime:=dtmhoraf.Time;
qrSorteados.SQL.Add(´and premio=:premio´);
qrsorteados.ParamByName(´premio´).DataType:=ftstring;
qrsorteados.ParamByName(´premio´).ParamType:=ptInputOutput;
qrSorteados.ParamByName(´premio´).Asstring:=dm.tbPremiosDESCRICAO.asstring;
qrSorteados.Prepare;
qrSorteados.Open;
if frmSorteados = nil then
frmSorteados:=TfrmSorteados.create(self);
frmSorteados.showmodal;
end
else showmessage(´Não há dados para os parâmetros informados...´);
end;
Sarnhold
Curtidas 0
Respostas
Sarnhold
04/11/2005
Preciso sortear números aleatórios a partir do número 1, mas está considerando o número 0.
Alguém saber como posso fazer?
Obrigada.
if qrSorteio.RecordCount > 0 then
begin
i:=qrSorteio.RecordCount;
Randomize;
for j := 1 to spcount.Value do
begin
numsorteado:=Random(i);
ShowMessage(´Numero sorteado: ´ + IntToStr(numsorteado));
qrSorteio.First;
qrSorteio.MoveBy(numsorteado-1);
Alguém saber como posso fazer?
Obrigada.
if qrSorteio.RecordCount > 0 then
begin
i:=qrSorteio.RecordCount;
Randomize;
for j := 1 to spcount.Value do
begin
numsorteado:=Random(i);
ShowMessage(´Numero sorteado: ´ + IntToStr(numsorteado));
qrSorteio.First;
qrSorteio.MoveBy(numsorteado-1);
GOSTEI 0
Massuda
04/11/2005
Preciso sortear números aleatórios a partir do número 1, mas está considerando o número 0.
Random(N) retorna um valor entre 0 e N-1... se você quer ter um valor entre 1 e N, basta você somar um ao valor retornado por Random.GOSTEI 0
Sarnhold
04/11/2005
Muito bem, acho que é isto mesmo.
Só não entendi porque tive que subtrair 2 do número sorteado para posicionar no número de registro. Após o sorteio posiciona 2 registros p/ frente.
Vc sabe me dizer por quê?
Obrigada.
if qrSorteio.RecordCount > 0 then
begin
i:=qrSorteio.RecordCount;
Randomize;
for j := 1 to spcount.Value do
begin
numsorteado:=Random(i)+1;
ShowMessage(´Numero sorteado: ´ + IntToStr(numsorteado));
qrSorteio.First;
qrSorteio.MoveBy(numsorteado-2);
dm.tbSorteio.Append;
Só não entendi porque tive que subtrair 2 do número sorteado para posicionar no número de registro. Após o sorteio posiciona 2 registros p/ frente.
Vc sabe me dizer por quê?
Obrigada.
if qrSorteio.RecordCount > 0 then
begin
i:=qrSorteio.RecordCount;
Randomize;
for j := 1 to spcount.Value do
begin
numsorteado:=Random(i)+1;
ShowMessage(´Numero sorteado: ´ + IntToStr(numsorteado));
qrSorteio.First;
qrSorteio.MoveBy(numsorteado-2);
dm.tbSorteio.Append;
GOSTEI 0
Michael
04/11/2005
Olá!
Como vc garante que valores repetidos não serão sorteados? Pelo que vi no seu código, há chances de se repetirem números, pois Random não garante a unicidade de seus resultados a cada chamada.
[]´s
Como vc garante que valores repetidos não serão sorteados? Pelo que vi no seu código, há chances de se repetirem números, pois Random não garante a unicidade de seus resultados a cada chamada.
[]´s
GOSTEI 0
Sarnhold
04/11/2005
Que outra maneira poderia ser, sem Random?
GOSTEI 0
Emerson Nascimento
04/11/2005
crie um vetor onde vc guardará os números já sorteados.
tome esse código como exemplo e faça as devidas alterações/adaptações:
tome esse código como exemplo e faça as devidas alterações/adaptações:
procedure TForm1.Button1Click(Sender: TObject); var numsorteado, i, j: integer; Sorteado: array of integer; function JaSorteado(numero: integer): Boolean; var i: Integer; begin Result := False; for i := 0 to High(Sorteado) do if Sorteado[i] = numero then begin Result := True; Break; end; end; begin i := 200; for j := 1 to spcount.Value do begin repeat numsorteado := Random(i)+1; until not JaSorteado(numsorteado); ShowMessage(IntToStr(numsorteado)); SetLength(Sorteado,Length(Sorteado)+1); Sorteado[High(Sorteado)] := numsorteado; {ponha seu código aqui} end; end;
GOSTEI 0
Sarnhold
04/11/2005
Amigo, sou iniciante, não consegui entender estas 3 linhas:
for i := 0 to High(Sorteado) do
SetLength(Sorteado,Length(Sorteado)+1);
Sorteado[High(Sorteado)] := numsorteado;
O que faz o Set?
Obrigado.
for i := 0 to High(Sorteado) do
SetLength(Sorteado,Length(Sorteado)+1);
Sorteado[High(Sorteado)] := numsorteado;
O que faz o Set?
Obrigado.
GOSTEI 0
Emerson Nascimento
04/11/2005
comumente se vê:
[i:32d7f1e407]for i := 0 to 3 do[/i:32d7f1e407], mas nesse caso se sabe quantas iterações o [b:32d7f1e407]for[/b:32d7f1e407] terá
no nosso caso:
[i:32d7f1e407]for i := 0 to High(Sorteado) do[/i:32d7f1e407]
na linha acima, não sabemos quantos números foram sorteados e, como o vetor é dinâmico, não sabemos qual é o último elemento do mesmo. para pegar o último elemento utilizamos a função High().
o SetLength() altera o tamanho do vetor/string para um tamanho informado. No exemplo estamos pegando o vetor [i:32d7f1e407]Sorteado[/i:32d7f1e407], colocando mais um elemento nele e depois colocamos o número sorteado nesse novo elemento.
SetLength(Sorteado,Length(Sorteado)+1); // incrementa o vetor
Sorteado[High(Sorteado)] := numsorteado; // atribui o número sorteado ao último elemento criado
Note que há o uso de duas funções: High() e Length().
- High() retorna o último elemento do vetor e
- Length() retorna o tamanho do vetor.
ilustrando:
Vetor[0] := ´adbghg´
Vetor[1] := ´plerlsd´
Vetor[2] := ´ppllerss´
Vetor[3] := ´hhgssd´
High(Vetor) retornaria 3 e
Length(Vetor) retornaria 4
[i:32d7f1e407]for i := 0 to 3 do[/i:32d7f1e407], mas nesse caso se sabe quantas iterações o [b:32d7f1e407]for[/b:32d7f1e407] terá
no nosso caso:
[i:32d7f1e407]for i := 0 to High(Sorteado) do[/i:32d7f1e407]
na linha acima, não sabemos quantos números foram sorteados e, como o vetor é dinâmico, não sabemos qual é o último elemento do mesmo. para pegar o último elemento utilizamos a função High().
o SetLength() altera o tamanho do vetor/string para um tamanho informado. No exemplo estamos pegando o vetor [i:32d7f1e407]Sorteado[/i:32d7f1e407], colocando mais um elemento nele e depois colocamos o número sorteado nesse novo elemento.
SetLength(Sorteado,Length(Sorteado)+1); // incrementa o vetor
Sorteado[High(Sorteado)] := numsorteado; // atribui o número sorteado ao último elemento criado
Note que há o uso de duas funções: High() e Length().
- High() retorna o último elemento do vetor e
- Length() retorna o tamanho do vetor.
ilustrando:
Vetor[0] := ´adbghg´
Vetor[1] := ´plerlsd´
Vetor[2] := ´ppllerss´
Vetor[3] := ´hhgssd´
High(Vetor) retornaria 3 e
Length(Vetor) retornaria 4
GOSTEI 0
Motta
04/11/2005
Gere um TStringList e carregue uma sequencia de números
Escolha uma posição do TStringList
Delete esta posição do tString
Código semelhante em :
http://forum.clubedelphi.net/viewtopic.php?t=67444&highlight=random
Escolha uma posição do TStringList
Delete esta posição do tString
Código semelhante em :
http://forum.clubedelphi.net/viewtopic.php?t=67444&highlight=random
GOSTEI 0