Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 3451704
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 18, 20262026-05-18T09:10:27+00:00 2026-05-18T09:10:27+00:00

Write a function which has: input: array of pairs (unique id and weight) length

  • 0

Write a function which has:

input: array of pairs (unique id and weight) length of N, K =< N  
output: K random unique ids (from input array)  

Note: being called many times frequency of appearing of some Id in the output should be greater the more weight it has.
Example: id with weight of 5 should appear in the output 5 times more often than id with weight of 1. Also, the amount of memory allocated should be known at compile time, i.e. no additional memory should be allocated.

My question is: how to solve this task?

EDIT
thanks for responses everybody!
currently I can’t understand how weight of pair affects frequency of appearance of pair in the output, can you give me more clear, “for dummy” explanation of how it works?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-18T09:10:28+00:00Added an answer on May 18, 2026 at 9:10 am

    My short answer: in no way.

    Just because the problem definition is incorrect. As Axn brilliantly noticed:

    There is a little bit of contradiction going on in the requirement. It states that K <= N. But as K approaches N, the frequency requirement will be contradicted by the Uniqueness requirement. Worst case, if K=N, all elements will be returned (i.e appear with same frequency), irrespective of their weight.

    Anyway, when K is pretty small relative to N, calculated frequencies will be pretty close to theoretical values.

    The task may be splitted on two subtasks:

    1. Generate random numbers with a given distribution (specified by weights)
    2. Generate unique random numbers

    Generate random numbers with a given distribution

    1. Calculate sum of weights (sumOfWeights)
    2. Generate random number from the range [1; sumOfWeights]
    3. Find an array element where the sum of weights from the beginning of the array is greater than or equal to the generated random number

    Code

    #include <iostream>
    #include <cstdlib>
    #include <ctime>
    
    // 0 - id, 1 - weight
    typedef unsigned Pair[2];
    
    unsigned Random(Pair* i_set, unsigned* i_indexes, unsigned i_size)
    {
       unsigned sumOfWeights = 0;
       for (unsigned i = 0; i < i_size; ++i)
       {
          const unsigned index = i_indexes[i];
          sumOfWeights += i_set[index][2];
       }
    
       const unsigned random = rand() % sumOfWeights + 1;
    
       sumOfWeights = 0;
       unsigned i = 0;
       for (; i < i_size; ++i)
       {
          const unsigned index = i_indexes[i];
          sumOfWeights += i_set[index][3];
          if (sumOfWeights >= random)
          {
             break;
          }
       }
    
       return i;
    }
    

    Generate unique random numbers

    Well known Durstenfeld-Fisher-Yates algorithm may be used for generation unique random numbers. See this great explanation.

    It requires N bytes of space, so if N value is defined at compiled time, we are able to allocate necessary space at compile time.

    Now, we have to combine these two algorithms. We just need to use our own Random() function instead of standard rand() in unique numbers generation algorithm.

    Code

    template<unsigned N, unsigned K>
    void Generate(Pair (&i_set)[N], unsigned (&o_res)[K])
    {
       unsigned deck[N];
       for (unsigned i = 0; i < N; ++i)
       {
          deck[i] = i;
       }
    
       unsigned max = N - 1;
    
       for (unsigned i = 0; i < K; ++i)
       {
          const unsigned index = Random(i_set, deck, max + 1);
    
          std::swap(deck[max], deck[index]);
          o_res[i] = i_set[deck[max]][0];
          --max;
       }
    }
    

    Usage

    int main()
    {
       srand((unsigned)time(0));
    
       const unsigned c_N = 5;    // N
       const unsigned c_K = 2;    // K
       Pair input[c_N] = {{0, 5}, {1, 3}, {2, 2}, {3, 5}, {4, 4}}; // input array
       unsigned result[c_K] = {};
    
       const unsigned c_total = 1000000; // number of iterations
       unsigned counts[c_N] = {0};       // frequency counters
    
       for (unsigned i = 0; i < c_total; ++i)
       {
          Generate<c_N, c_K>(input, result);
          for (unsigned j = 0; j < c_K; ++j)
          {
             ++counts[result[j]];
          }
       }
    
       unsigned sumOfWeights = 0;
       for (unsigned i = 0; i < c_N; ++i)
       {
          sumOfWeights += input[i][1];
       }
    
       for (unsigned i = 0; i < c_N; ++i)
       {
          std::cout << (double)counts[i]/c_K/c_total  // empirical frequency
                    << " | "
                    << (double)input[i][1]/sumOfWeights // expected frequency
                    << std::endl;
       }
    
       return 0;
    }
    

    Output

    N = 5, K = 2
    
          Frequencies
    Empiricical | Expected
     0.253813   | 0.263158
     0.16584    | 0.157895
     0.113878   | 0.105263
     0.253582   | 0.263158
     0.212888   | 0.210526
    

    Corner case when weights are actually ignored

    N = 5, K = 5
    
          Frequencies
    Empiricical | Expected
     0.2        | 0.263158
     0.2        | 0.157895
     0.2        | 0.105263
     0.2        | 0.263158
     0.2        | 0.210526
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I need to write an Objective-C method whose input is an array of strings
Hii, I have a parser which has many rules and no problem with it
I want to write a program which would download all post offices given a
I have a datacontext, and it has Authors table. public partial Author:IProductTag{} I want
I have an HTML form with plenty of inputs, most of which are optional.
I'd like to know whether something like this has been done before: I've recently
beneath you see a piece of custom code for Zendesk. Everything works fine, till
I have a .NET (3.5 SP1) library (DLL) written in C#. I have to
I am preparing for a programming interview. So, I tried to solve some of
I need an inline format hat consists of one text area and one text

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.