C++で乱数を重複しないように発生させる

このQ&Aのポイント
  • C++で乱数を重複しないように発生させるようにプログラムを変更しろと言われたのですが、できません。
  • #C++ #乱数 #重複防止
  • C++のプログラムで乱数を発生させる際、重複しないようにする方法を教えてください。
回答を見る
  • ベストアンサー

C++で乱数を重複しないように発生させる

C++で乱数を重複しないように発生させるようにプログラムを変更しろと言われたのですが、できません。 教えていただきたいです。 #include<iostream> #include<cstdlib> #include<cstring> #include<ctime> using namespace std; int main() { int i,n; int *p; cout<<"何個記憶しますか?"<<endl; cin>>n; p=new int[n]; if(p==NULL){ cout<<"記憶域の確保に失敗しました。"<<endl; return 1; } srand((unsigned)time(NULL)); rand(); i=0; while(i<n){ p[i]=1+(int)((double)rand()/(RAND_MAX+1.0)*75); if(p[i]==p[i]) cout<<"p["<<i<<"]の値"<<p[i]<<endl; i++; } delete[] p; return 0; }

質問者が選んだベストアンサー

  • ベストアンサー
回答No.1

if(p[i]==p[i]) 同じものを比較しているからです。 i が、0以外(今回の場合はi>0)の時は、 それ以前の物すべてと比較するようにすれば、OK アルゴリズムとしては、あまりよくないですが。 それで、要件定義は満たしますよ。

関連するQ&A

  • C++で,配列に計算した値を入れたいです.

    C++で疑似乱数を発生させてサイコロをつくったのですが, サイコロを5回転がしたときのそれぞれの値をソートしたいと思い,配列に入れれば簡単だと考えてとりあえず配列に入れるプログラムを書いてみました. しかし,int array[i] = Dice(); のところでエラーが出てしまいます. ローベルのC++入門講座という本を使って独学で勉強している初心者なため,配列の使い方がいまいちよくわかりません. ご教授よろしくお願いします. 以下ソースコード #include <iostream> #include <cstdlib> #include <ctime> using namespace std; void InitRand(){ srand((unsigned int) time (NULL)); } int Dice(){ return rand() % 6 + 1; } int main(void){ int n = 0; //nはサイコロを転がす回数 cout <<"サイコロを何回転がしますか?" << flush; cin >> n; cout << "回転がします" << endl; InitRand(); for(int i = 0; i < n; ++i){ cout << Dice() << endl; int array[i] = Dice(); //エラーが発生する.i回目のサイコロの値をi番目の配列に入れたい. } }

  • 自分で作成したプログラムについて…。

    visual stdio 2013 デスクトップ版のものを使い、下に書くプログラムを作ったのですが、 visual stdio 2013では、ファイルが開けませんとなり、途中で、終了してしまうのですが、mingwでは、ちゃんとファイルが開けて、プログラムが、最後まで動作するのですが、なぜでしょうか? 原因を詳しく教えてください。また、改善方法も教えてください。 プログラム #include <iostream> #include <fstream> #include <ctime> #include <cstdlib> #include <list> #include <string> using namespace std; int main() { srand((unsigned)time(NULL)); list<string> str; char sstr[255]; int count = 0; int i; ifstream in("ttest", ios::in | ios::binary); if (!in){ cout << "入力ファイルが開けません\n"; getchar(); return 1; } while (!in.eof()){ in.getline(sstr, 255); str.push_back(sstr); count++; } i = rand() % count ; list<string>::iterator p; p = str.begin(); for (int j = 2; j <= i; j++)p++; cout << *p; cout << endl; getchar(); return 0; }

  • C++

    今、下のようなプログラムを作っています #include <iostream> #include <iostream> using namespace std; int i=0, c=0, n; char str[10]; class X16karax10{ //16進から10進ヘ public: void keisan(); }; void X16karax10::keisan(void){ cout<<"16進を入力して下さい"<<endl; cout<<"英数字は大文字で入力してください(F→○ f→×)" <<endl; scanf("%s",str); while(str[i] != '\0'){ n = n * 0x10; c = str[i++]; if((c >= '0') && (c <= '9')){ n += c - '0'; } else if((c >= 'A') && (c <= 'F')){ n += c - 'A' + 10; } } cout<<("%d\n",n)<<"です\n"<<endl; } int main(){ for(i=0; ; i++){ X16karax10 p; p.keisan(); } } 16進を十進に変えるものなのですがreturn 0を使うと「X16karax10::keisan()' は値を返せない」と、でてしまうのですがどうしたらよいでしょうか?

  • プログラムの説明

    C++の初心者です。 ↓のプログラムの動作はさっぱりわかりませんが、それについての説明は具体的に教えていただきたいです。(できれば、詳しく) #include <iostream> #include <string> int getNinzu(int ARGC, char *ARGV[]) throw (char const *){ if(ARGC!=2){ throw "Needs only one argument."; } int ninzu=std::atoi(ARGV[1]); if(ninzu<=0){ throw "Value is too small."; } return ninzu; } #include <cstdlib> #include <ctime> int randfive(){ static bool firsttime=true; if(firsttime){ firsttime=false; std::srand(std::time(NULL)); } return static_cast<int>(static_cast<double>(std::rand())/RAND_MAX*(5+1)); } #include <iomanip> int main(int ARGC, char* ARGV[]){ std::string cmdname=ARGV[0]; int ninzu; try{ ninzu=getNinzu(ARGC,ARGV); std::cout << std::setfill('0'); for (int i = 1; i <= ninzu; ++i) { int score = 0; for (int k = 0; k < 20; ++k) score += randfive(); std::cout << "C" << std::setw(5) << i << " " << score << '\n'; } }catch(char const *str){ std::cerr << str << std::endl << "Usage: " << cmdname << " ninzu" << std::endl; return 1; } }

  • 単純挿入法を入れたいんですけど・・・

    #include <iostream> #include <iomanip> #include <cstdlib> //rand関数を使うので using namespace std; void Sort(int *s, int n); //プロトタイプ int main() { const int N = 100; int a[N], i, r, temp; for(i = 0; i < N; i++) a[i] = i; for(i = 0; i < N; i++){ r = rand() % N; temp = a[i]; a[i] = a[r]; a[r] = temp; } cout << "整列前\n----\n"; for(i = 0; i < N; i++) cout << setw(4) << a[i]; cout << '\n'; Sort(a, N); cout << "整列後\n----\n"; for(i = 0; i < N; i++) cout << setw(4) << a[i]; cout << '\n'; return 0; } void Sort(int *s, int n) { //この部分を補って完成させること }

  • C++で分からないプログラムがあるんですが

    #include <iostream> #include <cmath> using namespace std; int main() { static const int N = 2; double va[N]={3,-4}; double vb[N]={4,3}; double a,b; double p; for (int i = 0; i < N; ++i) { for (int i = 0; i < N; ++i) { } } cout << "va + vb = (" ; for (int i = 0; i < N; ++i) { cout << va[i] + vb[i]; if (i < N - 1) { cout << ", "; } } cout << ")" << '\n'; cout << "va - vb = (" ; for (int i = 0; i < N; ++i) { cout << va[i] - vb[i]; if (i < N - 1) { cout << ", "; } } cout << ")" << '\n'; p = 0; for (int i = 0; i < N; ++i) { p += va[i] * vb[i]; } cout << "va・vb = " << p << '\n'; a = 0; for (int i = 0; i < N; ++i) { a += va[i] * va[i]; } a = sqrt(a); b = 0; for (int i = 0; i < N; ++i) { b += vb[i] * vb[i]; } b = sqrt(b); if (a * b != 0) { cout << "cosθ = " << p / (a * b) << '\n'; } return 0; } これで、ベクトルの加減とベクトルの内積とcosθが出るんですが、2つのベクトルを適当に初期化しないといけないんですが、初期化ってこれで初期化ってできてますか?

  • C++のポインタの動作を教えてください

    ちょっと長いですが、ある部分の動作がわかりません そこを詳しく教えてください。 void queue::store(int i)の//リスト末尾に置くっていうところからで なぜ、if(tail)tail->next=item; tail=item; こう書くのかわからないです。 tail->next=itemの次にtail=itemを実行すると、tail->nextの内容も変わるのでは?と思っているのですがどうなっているのかわからないのでお願いします。 説明が下手ですがすみませんが教えてください。 //仮想関数の実例 #include <iostream> #include <cstdlib> #include <cctype> using namespace std; class list{ public: list *head; //リスト先頭へのポインタ list *tail; //リスと末尾へのポインタ list *next; //次項目へのポインタ int num; //格納される値 list(){ head=tail=next=NULL; } virtual void store(int i)=0; virtual int retrieve()=0; }; //キュー型リストの作成 class queue:public list{ public: void store(int i); int retrieve(); }; void queue::store(int i) { list *item; item=new queue; if(!item){ cout << "メモリ割り当てエラー" << endl; exit(1); } item->num=i; //リスト末尾に置く if(tail)tail->next=item; tail=item; item->next=NULL; if(!head)head=tail; } int queue::retrieve() { int i; list *p; if(!head){ cout << "リストは空です" << endl; return 0; } //リスト先頭から取り除く i=head->num; p=head; head=head->next; delete p; return i; } //スタック型リストの作成 class stack:public list{ public: void store(int i); int retrieve(); }; void stack::store(int i) { list *item; item=new stack; if(!item){ cout << "メモリ割り当てエラー" << endl; exit(1); } item->num=i; //スタックのような操作になるよう、リスト最前部におく if(head)item->next=head; head=item; if(!tail)tail=head; } int stack::retrieve() { int i; list *p; if(!head){ cout << "リストは空です" << endl; return 0; } //リスト先頭から取り除く i=head->num; p=head; head=head->next; delete p; return i; } class sorted:public list{ public: void store(int i); int retrieve(); }; void sorted::store(int i) { list *item; list *p,*p2; item=new sorted; if(!item){ cout << "メモリ割り当てエラー" << endl; exit(1); } item->num=i; //次項目のおき場所を見つける p=head; p2=NULL; while(p){ //中へ if(p->num>i){ item->next=p; if(p2)p2->next=item; //先頭要素ではない if(p==head)head=item; //新しい先頭要素 break; } p2=p; p=p->next; } if(!p){ //終わりへ if(tail)tail->next=item; tail=item; item->next=NULL; } if(!head)//先頭要素 head=item; } int sorted::retrieve() { int i; list *p; if(!head){ cout << "リストは空です" << endl; return 0; } //リスト先頭から取り除く i=head->num; p=head; head=head->next; delete p; return i; } int main() { list *p; //キューのデモ queue q_ob; p=&q_ob; //キューをさす p->store(1); p->store(2); p->store(3); cout << "キュー:"; cout << p->retrieve(); cout << p->retrieve(); cout << p->retrieve(); cout << endl; //スタックのデモ stack s_ob; p=&s_ob; //スタックをさす p->store(1); p->store(2); p->store(3); cout << "スタック:"; cout << p->retrieve(); cout << p->retrieve(); cout << p->retrieve(); cout << endl; //ソート済みリストのデモ sorted sorted_ob; p=&sorted_ob; p->store(4); p->store(1); p->store(3); p->store(9); p->store(5); cout << "ソ\ート:"; cout << p->retrieve(); cout << p->retrieve(); cout << p->retrieve(); cout << p->retrieve(); cout << p->retrieve(); cout << endl; return 0; }

  • C++で縦の棒グラフ

    #include<iostream> #include<ctime> using namespace std; int main() { int a[7]; int k; int j; srand(time(NULL)); for(k = 0; k < 7; k++) a[k] = rand() % 10 + 1; for(k = 0; k < 7; k++){ cout << "a[" << k << "] = "; for(j = 0; j < a[k]; j++) cout << "*"; cout << "\n"; } cout << "-------------\n"; cout << "0 1 2 3 4 5 6\n"; return 0; } グラフを作ってみようと挑戦したんですけど 横の棒グラフは作ることはできたんですけど 縦の棒グラフを作ろうして、下の部分はできたんですけど その上に*をランダムの数だけ表示さす方法がわかりません。 どうしてらよいでしょうか?

  • 乱数

    #include<stdio.h> #include<stdlib.h> #include<time.h> int main(void) { double n,end; printf("いくつ以上の値が出たら終了しますか?:"); scanf("%lf",&end); srand((unsigned)time(NULL)); for( ; ; ){ n=(double)rand(); printf("%f\n",n); if(n>=end) break; } return 0; } これなんですが、このまま実行すると.00000になってしまいます。 自分的には0.~にしたいのですが、どう変えればいいでしょうか? 回答お願いします。

  • C++ の while ループ

    C++の基本学習者です。Windows 10 で Visual Studio Community 2015 を使っています。 教本に載っている、機械語のプログラムをC++でシミュレーションする、というものを作ろうと、途中まで下のようなコードを書き込み、そこまで間違いがないかを確かめるために、コンパイルして実行したら、添付の写真のようなエラーメッセージが出てきました。 // ConsoleApplication65.cpp : メイン プロジェクト ファイルです。 #include "stdafx.h" #include <iostream> #include <iomanip> #include <cstdlib> #include <ctime> #include <cmath> #include <cstring> using namespace System; using namespace std; int main() { // variables int program = 0; int accumulator = 0; int count = 0; int instructionRegister = 0; int operationCode = 0; int operand = 0; int location[100]; cout << "*** Welcome to Simpletron ***" << endl; cout << "*** Please enter your program ***" << endl; cout << "*** one instruction at a time,***" << endl; cout << "*** after the location number and and the prompt of '?' ***" << endl; cout << "*** To stop entering instructions, ***" << endl; cout << "*** enter -9999 . ***" << endl << endl; cout << setfill('0') << internal; cout << setw(3) << count << " ? "; cin >> program; while (program != -9999) { location[count] = program; count++; } return 0; } while ループに問題がありそうですが、コンパイルはちゃんとできたのに、何が悪いのでしょうか? 詳しい方、どうぞ教えてください。お願いします。

専門家に質問してみよう