【问题标题】:How to check equivalent of randomly generated alphabets?如何检查等效随机生成的字母?
【发布时间】:2014-03-23 08:58:05
【问题描述】:
//This code gives randomly generated alphabets and if equal will
//cout the alphabet which is equal  
1 #include <iostream>
2 #include <cstdlib>
3 #include <ctime>
4 using namespace std;
5 int main()
6 {
7 int a;
8 char array[10];
9 srand (time(0));
10 for (int i=0; i<10; i++)
11 {
12 a=rand() %26;
13 a=a+97;
14 array[i]=char(a);
15 }
16 for (int i=0; i<10; i++)
17 {
18 for (int j=0; j<10; j++)
19     {
20     if (array [i]==array [j]);
21     {
22     cout <<array[i] <<" " <<array[j];//if alphabet 'c' is at indecis 2,5,8
                                       //then output should be like that of
                                       // only 22 no statement but actually it does
                                       // not give this answer but gives wrong output
                                       //c c
                                       //c c
                                       //c c 

23      }
24          cout << endl;
25     }
26 }
27 return 0;
28 } //program end

我的问题是如何检查随机生成的字母是否相等,例如在 22 个数字行中,如果它们相等,它应该输出相等的字母,但它没有给出相等的字母此代码中有什么错误提及错误的语句或帮助我我将如何得到正确的答案

其实我想做一个程序,告诉我一个生成的字母表在一个数组中出现了多少次

【问题讨论】:

  • 请添加具有预期输出的示例输入。
  • 对不起,我还是不明白你的意思。
  • 哪种说法你看不懂
  • 我想制作一个程序,告诉我哪个字母在一个数组中出现了多少次?
  • 哦,所以你得到的是“c c c c”而不是“2 5 8”?

标签: visual-c++ random g++ srand


【解决方案1】:

根据您的评论,您正在寻找可以做到这一点的东西:

#include <random>
#include <iostream>
#include <vector>
#include <functional>
#include <algorithm>


int main(){
   ::std::vector<char> letters(10);
   ::std::vector<char> unique;
   ::std::random_device rd;
   ::std::mt19937 mt(rd());
   ::std::uniform_int_distribution<char> dis('a', 'z');
   auto random = ::std::bind(dis, mt);

   // fill the vector with random letters
   for(char & l : letters){
       l = random();
   }

   int max_count = 0;
   char appeared_most = ' ';

   // get a vector of all the unique values
   ::std::unique_copy(letters.cbegin(), letters.cend(), ::std::back_inserter(unique));

   // find the first value to appear most if two values appear equally
   // the first will be chosen
   for(const char & l : unique){
       int count = ::std::count(letters.cbegin(), letters.cend(), l);
       if(count > max_count){
           max_count = count;
           appeared_most = l;
       }
   }
   ::std::cout << appeared_most << " " << max_count ;
}

我在这里有一个工作示例:http://coliru.stacked-crooked.com/a/53c953576e0db756

【讨论】:

    猜你喜欢
    • 2021-02-20
    • 2012-12-29
    • 2018-12-13
    • 2018-08-11
    • 2021-04-05
    • 1970-01-01
    • 1970-01-01
    • 2014-05-10
    相关资源
    最近更新 更多