CAVC Posted March 29, 2012 at 04:02 PM Report Share #446375 Posted March 29, 2012 at 04:02 PM Olá! Peço desde já desculpa se este tópico já existir e eu não o consigo encontrar!! Eu sou novo nesta coisa de programação. Queria saber como é que em c++ conseguimos, gerando uma chave aleatória num array, conseguimos verificar se existe nºs repetidos e eliminá-los??? Estou com dificuldades nisso! Se alguem puder ajudar, agradeço desde já 👍 Link to comment Share on other sites More sharing options...
polska Posted March 29, 2012 at 04:17 PM Report Share #446381 Posted March 29, 2012 at 04:17 PM Para começar, tens de gerar os números aleatorios, para isso chamas a biblioteca <time.h> e a <stdlib.h>, asseguir ao main tens de declarar o tempo a 0, assim: srand(time(NULL)); .. O próximo passo é declarares a variavel que vai conter os numeros aleatórios, por exemplo int numero . Depois disto, vais ter de por a variavel a receber numeros aleatorios, assim: numero = rand() % 10 + 1; (assim os numeros vao variar de 1 a 10, podes mudar trocando o 10 por outro valor) .. De seguida, tens de os colocar no vector, para isso utilizas um ciclo for de 1 até ao tamanho do vector e metes a cada poisção a receber o numero.. que vai variar.. ou seja: for(int i=1;i<=50;i++){ v[i]=numero; } assim vao ser declarados numeros variados no vector.. para verificares se existem iguais.. apenas tens de fazer dois ciclos for, um para correr as posições do vector, e outro para o fazer com 1 numero em particular... para o trocares basta pedires o numero se na posição já se encontrar um existente.. for(int i=1;i<=50;i++){ for(int j=i+1;j<50;j++){ if(v[j]==v[i]){ scanf("%d",v[i]); } } } Poderá estar confuso.. mas se ajudar ;D Corrige um sábio e ele mais sábio ficará. Corrige um ignorante e um inimigo ganharás. Link to comment Share on other sites More sharing options...
pikax Posted March 29, 2012 at 04:18 PM Report Share #446382 Posted March 29, 2012 at 04:18 PM Tens que fazer por passos: 1º- geras um numero aleatório - http://www.cplusplus.com/reference/clibrary/cstdlib/rand/ 2º- verificas se esse numero existe no array. 3º- apagar de um array estático não é possivel, podes é deslocar os elementos "à frente" menos uma posição do array.(claro que podes usar memoria dinâmica para apagar um valor num array) Por muito mais que que estude só aprendo uma coisa, que ainda tenho muita coisa para aprender. A beleza de um código está em decompor problemas complexos em pequenos blocos simples. "learn how to do it manually first, then use the wizzy tool to save time." "Kill the baby, don't be afraid of starting all over again. Fail soon, learn fast." Link to comment Share on other sites More sharing options...
CAVC Posted March 29, 2012 at 04:26 PM Author Report Share #446388 Posted March 29, 2012 at 04:26 PM Mas por exemplo, eu tenho 7 nºs num array, e o numero na posição 2 é o mesmo que o da posição 5, por exemplo, como faço para o mudar?? Eu consigo mudar caso o da posição 0 for igual a qualquer outro mas aquele exemplo não sei :S Link to comment Share on other sites More sharing options...
polska Posted March 29, 2012 at 04:37 PM Report Share #446395 Posted March 29, 2012 at 04:37 PM É igual... tu ao fazeres os dois ciclos for como te disse, estas a percorrer os 7 numeros verificando 1 a 1.. por exmplo, numero 1.. verifica se é igual ao 2 , depois ao 3, depois ao 4... E se for igual, aquilo para, e pede outro numero, scanf("%d", v); .. ou seja, na posição onde o numero é igual, tu pedes outro e ele é automaticamente substituido.. Eu não me importo de te fazer o programa, se preferiries, para tirares as dúvidas Corrige um sábio e ele mais sábio ficará. Corrige um ignorante e um inimigo ganharás. Link to comment Share on other sites More sharing options...
CAVC Posted March 29, 2012 at 04:40 PM Author Report Share #446397 Posted March 29, 2012 at 04:40 PM Sim se não te importares sff... 👍 Não estou mesmo a ver Link to comment Share on other sites More sharing options...
pikax Posted March 29, 2012 at 04:49 PM Report Share #446405 Posted March 29, 2012 at 04:49 PM fiz um pouco à presa, mas é mais ou menos isto: #include<iostream> #include<cstring> using namespace std; //return new size array int removeElemArray(int *arr,int pos,int size_arr) { for(int i=pos+1;i<size_arr;i++) //mover os elementos da array menos uma posicao arr[i-1]=arr[i]; size_arr--; //decrementar o tamanho do array return size_arr; } int main() { int arr[10]={1,2,3,4,2,5,6,7,8,9}; int size_arr=10;//tamanho do array //remover o 5º elemento do array que é 2 size_arr=removeElemArray(arr,4,size_arr); for(int i=0;i<size_arr;i++) cout<<arr[i]<<" - "; cout<<endl; } Por muito mais que que estude só aprendo uma coisa, que ainda tenho muita coisa para aprender. A beleza de um código está em decompor problemas complexos em pequenos blocos simples. "learn how to do it manually first, then use the wizzy tool to save time." "Kill the baby, don't be afraid of starting all over again. Fail soon, learn fast." Link to comment Share on other sites More sharing options...
CAVC Posted March 29, 2012 at 05:13 PM Author Report Share #446414 Posted March 29, 2012 at 05:13 PM Continuo com a mesma dúvida!! ? Tu criaste uma função para eliminar um elemento do array mas eu não quero ter um array e eliminar um elemento... quero gerar nºs aleatórios que ficam num array e que se houver repetidos trocar um numero. e isto tudo fica num ficheiro Link to comment Share on other sites More sharing options...
pikax Posted March 29, 2012 at 05:20 PM Report Share #446416 Posted March 29, 2012 at 05:20 PM Continuo com a mesma dúvida!! ? Tu criaste uma função para eliminar um elemento do array mas eu não quero ter um array e eliminar um elemento... quero gerar nºs aleatórios que ficam num array e que se houver repetidos trocar um numero. e isto tudo fica num ficheiro Tens que fazer por passos: 1º- geras um numero aleatório - http://www.cplusplus.com/reference/clibrary/cstdlib/rand/ ... para gravar num ficheiro - http://www.cplusplus.com/doc/tutorial/files/ Por muito mais que que estude só aprendo uma coisa, que ainda tenho muita coisa para aprender. A beleza de um código está em decompor problemas complexos em pequenos blocos simples. "learn how to do it manually first, then use the wizzy tool to save time." "Kill the baby, don't be afraid of starting all over again. Fail soon, learn fast." Link to comment Share on other sites More sharing options...
CAVC Posted March 29, 2012 at 05:23 PM Author Report Share #446418 Posted March 29, 2012 at 05:23 PM for (i=0; i<=4; i++) { chave[i] = rand() % 50 + 1; for (j=i+1; j<=4; j++) { if (chave[i]==chave[j]) { chave[i] = rand() % 50 + 1; este aqui é o meu código, eu fiz assim mas mesmo assim continua-me a aparecer numeros repetidos (falta um parentese mas nao ligues) ? Link to comment Share on other sites More sharing options...
pikax Posted March 29, 2012 at 06:58 PM Report Share #446448 Posted March 29, 2012 at 06:58 PM devias de dizer quais são os erros que te aparecem, ou meter o código fonte aqui. eu fiz assim: #include<iostream> #include<ctime> #include <cstdlib> #define MAX_CHAVES 4 using namespace std; bool verificaArray(int *chave,int valor,int size_arr) { for(int i=0;i<size_arr;i++) if(chave[i]==valor) return true; return false; } int main() { int chave[MAX_CHAVES]; int temp; /* initialize random seed: */ srand ( time(NULL) ); for(int i=0; i<MAX_CHAVES;i++) { temp = rand() % 50 + 1; while(verificaArray(chave,temp,MAX_CHAVES)) { temp=rand()%50+1; } chave[i]=temp; } for(int i=0;i<MAX_CHAVES;i++) cout<<chave[i]<<" - "; cout<<endl; } Por muito mais que que estude só aprendo uma coisa, que ainda tenho muita coisa para aprender. A beleza de um código está em decompor problemas complexos em pequenos blocos simples. "learn how to do it manually first, then use the wizzy tool to save time." "Kill the baby, don't be afraid of starting all over again. Fail soon, learn fast." Link to comment Share on other sites More sharing options...
CAVC Posted March 29, 2012 at 08:30 PM Author Report Share #446458 Posted March 29, 2012 at 08:30 PM Hummm!! Obrigado! Ajudou! E desculpa não ser tão claro 😕 Link to comment Share on other sites More sharing options...
KTachyon Posted March 29, 2012 at 09:03 PM Report Share #446472 Posted March 29, 2012 at 09:03 PM Se a tua dúvida está relacionada com jogos tipo totoloto e euromilhões, o ideal é utilizares uma estrutura que te permita retirar os números que já saíram e calcular um valor aleatório dentro da quantidade de existentes. “There are two ways of constructing a software design: One way is to make it so simple that there are obviously no deficiencies, and the other way is to make it so complicated that there are no obvious deficiencies. The first method is far more difficult.” -- Tony Hoare Link to comment Share on other sites More sharing options...
CAVC Posted March 29, 2012 at 10:03 PM Author Report Share #446491 Posted March 29, 2012 at 10:03 PM Sim é para o jogo euromilhões!! A parte de ordenar já consegui fazer usando uma maneira diferente. Agora a parte de ordenar é que me está a confundir. Não sei como fazer. Alguma ideia?? 😕 Link to comment Share on other sites More sharing options...
KTachyon Posted March 29, 2012 at 10:29 PM Report Share #446496 Posted March 29, 2012 at 10:29 PM Para além dos vários algoritmos já implementados nas bibliotecas do C++, porque não tentas implementar uma coisa simples? Percorres o array todo, registando a posição do elemento mais pequeno e fazes um swap para a primeira posição. Depois percorres o array a partir da segunda posição, registando o elemento mais pequeno e fazes um swap para a segunda posição. Depois percorres o array a partir da terceira (...) “There are two ways of constructing a software design: One way is to make it so simple that there are obviously no deficiencies, and the other way is to make it so complicated that there are no obvious deficiencies. The first method is far more difficult.” -- Tony Hoare Link to comment Share on other sites More sharing options...
pikax Posted March 29, 2012 at 11:31 PM Report Share #446513 Posted March 29, 2012 at 11:31 PM podes usar bubble sort http://www.di.ubi.pt/~fsilva/palg/Alg_Ordenacao1.pdf https://www.youtube.com/embed/lyZQPjUT5B4?feature=oembed -> video muito engraçado http://www.algolist.net/Algorithms/Sorting/Bubble_sort Por muito mais que que estude só aprendo uma coisa, que ainda tenho muita coisa para aprender. A beleza de um código está em decompor problemas complexos em pequenos blocos simples. "learn how to do it manually first, then use the wizzy tool to save time." "Kill the baby, don't be afraid of starting all over again. Fail soon, learn fast." Link to comment Share on other sites More sharing options...
polska Posted March 30, 2012 at 01:29 PM Report Share #446588 Posted March 30, 2012 at 01:29 PM Sim se não te importares sff... 😕 Não estou mesmo a ver Com base no que te respondi, eu fazia assim: #include <stdio.h> #include <stdlib.h> #include <time.h> #define MAX 7 void main(){ srand(time(NULL)); int v[MAX],numeros; for(int i=0;i<MAX;i++){ //Colocar numeros aleatorios no array numeros = rand() % 50 + 1; v[i]=numeros; } for(int i=0;i<MAX;i++){ printf("%d ",v[i]); } printf("\n"); for(int i=0;i<MAX;i++){ //Verificar se á numeros iguais e trocar for(int j=i;j<MAX;j++){ if(i!=j){ if(v[i]==v[j]){ scanf("%d",&v[i]); } } } } system("pause"); } Ao executares o programa, ele vai gerar os numeros aleatorios no array e vai depois mostrar esse mesmo array, se tiver algum numero repetido o programa nao para e tu teras de inserir um numero para substituir o que é repetido.. Os numero estão gerados de 1 a 50.. Eu vi que queres guarda-los num ficheiro á parte... Mas eu isso já não sei fazer xb ;D Corrige um sábio e ele mais sábio ficará. Corrige um ignorante e um inimigo ganharás. Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now