Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: function creation using array

Tags:

c++

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?

like image 572
kilonet Avatar asked Nov 30 '10 20:11

kilonet


People also ask

Can we use array in function in C?

An array can be passed to functions in C using pointers by passing reference to the base address of the array, and similarly, a multidimensional array can also be passed to functions in C.

How can we pass array to function in C?

To pass an entire array to a function, only the name of the array is passed as an argument. result = calculateSum(num); However, notice the use of [] in the function definition. This informs the compiler that you are passing a one-dimensional array to the function.

Can we pass array as argument in C?

Just like normal variables, Arrays can also be passed to a function as an argument, but in C/C++ whenever we pass an array as a function argument then it is always treated as a pointer by a function.

How do you pass an array to a function with pointer?

A whole array cannot be passed as an argument to a function in C++. You can, however, pass a pointer to an array without an index by specifying the array's name. In C, when we pass an array to a function say fun(), it is always treated as a pointer by fun().


1 Answers

Assuming a good enough random number generator:

  • Sum the weights (total_weight)
  • Repeat K times:
    • Pick a number between 0 and total_weight (selection)
    • Find the first pair where the sum of all the weights from the beginning of the array to that pair is greater than or equal to selection
    • Write the first part of the pair to the output

You need enough storage to store the total weight.

like image 192
MSN Avatar answered Oct 26 '22 23:10

MSN