কম্পিউটার

কিভাবে C++ এ একটি std::vector এলোমেলো করবেন


ফিশার-ইয়েটস শাফেল অ্যালগরিদমে একটি ভেক্টর শাফেল করা যেতে পারে।

এই অ্যালগরিদমে, একটি ভেক্টরের একটি রৈখিক স্ক্যান করা হয় এবং তারপর উপাদানটি সহ বাকি সমস্ত উপাদানগুলির মধ্যে একটি এলোমেলো উপাদানের সাথে প্রতিটি উপাদানকে অদলবদল করা হয়।

অ্যালগরিদম

Begin
  Declare a function show().
      Pass a constructor of a vector as a parameter within show() function.
      for (auto const& i: input)
         Print the value of variable i.
      Declare v of vector type.
         Initialize some values into v vector in array pattern.
      Declare a variable size of the integer datatype.
      Call size() function to get the size of the vector.
         Initialize size = v.size().
      for (int i = 0; i < size - 1; i++)
         int j = i + rand() % (size - i).
         call swap() function to swap the values of v[i] and v[j].
      print “Elements after getting shuffled”.
      Call show() function to display the suffled value of v vector.
End.
এর suffled মান প্রদর্শন করতে show() ফাংশনকে কল করুন

উদাহরণ কোড

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void show(vector<int> const &input) {
   for (auto const& i: input) {
      std::cout << i << " ";
   }
}
int main() {
   vector<int> v = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
   int size = v.size();
   for (int i = 0; i < size - 1; i++) {
      int j = i + rand() % (size - i);
      swap(v[i], v[j]);
   }
   cout<<"Elements after getting shuffled"<<endl;
   show(v);
   return 0;
}

আউটপুট

Elements after getting shuffled
2 8 5 3 1 9 4 7 6

  1. কিভাবে একটি std::string এবং একটি int C++ এ সংযুক্ত করবেন?

  2. কিভাবে C++ এ একটি ফাংশনে অ্যারের প্যারামিটারের আকার প্রিন্ট করবেন?

  3. কিভাবে একটি একক অক্ষর সি++ এ স্ট্রিং এ রূপান্তর করবেন?

  4. কিভাবে C++ এ একটি ভেক্টরের বিষয়বস্তু মুদ্রণ করবেন?