mirror of
https://github.com/aljazceru/lightning.git
synced 2025-12-21 08:04:26 +01:00
common/random_select: central place for reservoir sampling.
Turns out we can make quite a simple API out of it. Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
This commit is contained in:
@@ -57,6 +57,7 @@ COMMON_SRC_NOGEN := \
|
||||
common/ping.c \
|
||||
common/psbt_open.c \
|
||||
common/pseudorand.c \
|
||||
common/random_select.c \
|
||||
common/read_peer_msg.c \
|
||||
common/setup.c \
|
||||
common/socket_close.c \
|
||||
|
||||
11
common/random_select.c
Normal file
11
common/random_select.c
Normal file
@@ -0,0 +1,11 @@
|
||||
#include <common/pseudorand.h>
|
||||
#include <common/random_select.h>
|
||||
|
||||
bool random_select(double weight, double *tot_weight)
|
||||
{
|
||||
*tot_weight += weight;
|
||||
if (weight == 0)
|
||||
return false;
|
||||
|
||||
return pseudorand_double() <= weight / *tot_weight;
|
||||
}
|
||||
20
common/random_select.h
Normal file
20
common/random_select.h
Normal file
@@ -0,0 +1,20 @@
|
||||
#ifndef LIGHTNING_COMMON_RANDOM_SELECT_H
|
||||
#define LIGHTNING_COMMON_RANDOM_SELECT_H
|
||||
#include "config.h"
|
||||
#include <stdbool.h>
|
||||
|
||||
/* Use weighted reservoir sampling, see:
|
||||
* https://en.wikipedia.org/wiki/Reservoir_sampling#Algorithm_A-Chao
|
||||
* But (currently) the result will consist of only one sample (k=1)
|
||||
*/
|
||||
|
||||
/**
|
||||
* random_select: return true if we should select this one.
|
||||
* @weight: weight for this option (use 1.0 if all the same)
|
||||
* @tot_wieght: returns with sum of weights (must be initialized to zero)
|
||||
*
|
||||
* This always returns true on the first non-zero weight, and weighted
|
||||
* randomly from then on.
|
||||
*/
|
||||
bool random_select(double weight, double *tot_weight);
|
||||
#endif /* LIGHTNING_COMMON_RANDOM_SELECT_H */
|
||||
Reference in New Issue
Block a user