-
Notifications
You must be signed in to change notification settings - Fork 0
/
listsex.erl
743 lines (676 loc) · 24.4 KB
/
listsex.erl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
%%%----------------------------------------------------------------------
%%%
%%% @author chenduo
%%% @date 2013-11-13
%%% @doc lists的扩展
%%%
%%%----------------------------------------------------------------------
-module(listsex).
-export([for/2, foracc/3, while/2, while/3, untilerror/2, untilerror/3]).
-export([find/2, mapfind/2, mapfind/3, foldlwhile/3, foldwhile/4]).
-export([classify/2, classify/4]).
-export([count/2, fcount/2, takecount/1, nmerge/1]).
-export([indexof/2, findexof/2, insertat/3, removeat/2, takeat/2, replaceat/3]).
-export([insertsorted/2, insertsortedf/3]).
-export([keycount/3, keyfoldl/5, keyfoldr/5, keyupdate/4, keyupdate/5]).
-export([keyclassify/2, keyclassify/4, keyclassifyl/2, keyclassifyl/4]).
-export([randallot/2, randallot2/2, shuffle/1, shuffle2/1]).
-export([randstuff/2, randstuff_withlimit/3, randstuff_withlimit/4]).
-export([rand/1, rand/2, rand_pick/1, rand_pick/2]).
-export([pick_by_weight/1, pick_by_prob/1]).
-export([drawrand/1, drawrand/2, drawrand_index/1, drawrand_index/2]).
-export([rand_dissimilar_from_deeplist/1]).
-export([priority_accept/3, remove_duplicates/1, subtract_rmdup/2]).
-export([isallsame/1, key_isallsame/2]).
-export([ets_take/2, pmap/2, split_into/2, divide_every_two/1]).
%% @doc 执行指定函数N次
for(_Fun, N) when N =< 0 ->
ok;
for(Fun, N) ->
Fun(),
for(Fun, N - 1).
%% @doc 执行指定函数N次并fold结果
foracc(_, 0, Acc) ->
Acc;
foracc(Fun, N, Acc) ->
foracc(Fun, N-1, Fun(Acc)).
%% @doc 执行指定函数直至条件不满足
while(F, Acc) ->
case F(Acc) of
false ->
Acc;
Acc2 ->
while(F, Acc2)
end.
%% @doc 执行指定函数直至条件不满足
while(Pred, F, Acc) ->
while(Pred, F, F(Acc), Acc).
while(Pred, F, Next, Acc) ->
case Pred(Next) of
true ->
while(Pred, F, F(Next), Next);
false ->
Acc
end.
%% @doc 执行指定函数直至出错
untilerror(Fun, Acc) ->
case catch Fun(Acc) of
{error, Reason} ->
{Reason, Acc};
Acc2 ->
untilerror(Fun, Acc2)
end.
%% @doc 执行指定函数直至出错或次数达到
untilerror(_, Acc, 0) ->
{normal, Acc};
untilerror(Fun, Acc, N) ->
case catch Fun(Acc) of
{error, Reason} ->
{Reason, Acc};
Acc2 ->
untilerror(Fun, Acc2, N - 1)
end.
%% @doc 返回第一个匹配的元素
find(Pred, [H|T]) ->
case Pred(H) of
true ->
H;
false ->
find(Pred, T)
end;
find(_, []) ->
false.
%% @doc 返回第一个执行指定函数后结果不为Default的结果
mapfind(Fun, [H|T]) ->
mapfind(Fun, [H|T], false);
mapfind(_Fun, []) ->
false.
mapfind(Fun, [H|T], Default) ->
case Fun(H) of
Default ->
mapfind(Fun, T, Default);
Val ->
Val
end;
mapfind(_, [], Default) ->
Default.
%% @doc 数个数
count(E, L) ->
count(E, L, 0).
count(_E, [], Acc) ->
Acc;
count(E, [E|T], Acc) ->
count(E, T, Acc + 1);
count(E, [_|T], Acc) ->
count(E, T, Acc).
%% @doc 数个数
fcount(F, L) ->
fcount(F, L, 0).
fcount(_F, [], Acc) ->
Acc;
fcount(F, [H|T], Acc) ->
case F(H) of
true ->
fcount(F, T, Acc + 1);
false ->
fcount(F, T, Acc)
end.
%% @doc 统计列表各元素个数
%% e.g [1, 2, 3, 4, 2, 1, 3] -> [{1,2},{2,2},{3,2},{4,1}]
takecount(L) ->
takecount(L, []).
takecount([], Acc) ->
Acc;
takecount([H|T], Acc) ->
case lists:keytake(H, 1, Acc) of
false ->
takecount(T, [{H, 1} | Acc]);
{value, {H, N}, Acc2} ->
takecount(T, [{H, N + 1} | Acc2])
end.
%%---------------------------------------------------------------
%% 位置相关
%%---------------------------------------------------------------
%% @doc 返回给定元素在列表中的位置,从1开始
indexof(Ele, L) ->
indexof(Ele, L, 1).
indexof(Ele, [Ele|_T], Idx) ->
Idx;
indexof(Ele, [_|T], Idx) ->
indexof(Ele, T, Idx + 1);
indexof(_, [], _) ->
false.
%% @doc 返回符合给定条件的元素在列表中的位置,从1开始
findexof(Fun, L) when is_function(Fun, 1) ->
findexof(Fun, L, 1).
findexof(Fun, [H|T], Idx) ->
case Fun(H) of
true ->
Idx;
false ->
findexof(Fun, T, Idx + 1)
end;
findexof(_, [], _) ->
false.
%% @doc 向list中指定位置插入元素
insertat(E, Idx, L) ->
insertat(E, Idx, L, [], 1).
insertat(_, _, [], Acc, _) ->
lists:reverse(Acc);
insertat(E, Idx, [_|T], Acc, Count) when Count =:= Idx ->
lists:reverse([E|Acc], T);
insertat(E, Idx, [H|T], Acc, Count) ->
insertat(E, Idx, T, [H|Acc], Count+1).
%% @doc 从list中删除指定位置的元素
removeat(Idx, L) ->
removeat(Idx, L, [], 1).
removeat(_, [], Acc, _) ->
lists:reverse(Acc);
removeat(Idx, [_|T], Acc, Count) when Count =:= Idx ->
lists:reverse(Acc, T);
removeat(Idx, [H|T], Acc, Count) ->
removeat(Idx, T, [H|Acc], Count+1).
%% @doc 从list中删除指定位置的元素,返回删除后的列表和删掉的元素
takeat(Idx, L) ->
takeat(Idx, L, [], 1).
takeat(_, [], Acc, _) ->
{false, lists:reverse(Acc)};
takeat(Idx, [H|T], Acc, Count) when Count =:= Idx ->
{H, lists:reverse(Acc, T)};
takeat(Idx, [H|T], Acc, Count) ->
takeat(Idx, T, [H|Acc], Count+1).
%% @doc 替换list中指定位置的元素
replaceat(Idx, L, Val) ->
replaceat(Idx, L, [], 1, Val).
replaceat(_, [], Acc, _, _) ->
lists:reverse(Acc);
replaceat(Idx, [_|T], Acc, Count, Val) when Count =:= Idx ->
lists:reverse(Acc, [Val|T]);
replaceat(Idx, [H|T], Acc, Count, Val) ->
replaceat(Idx, T, [H|Acc], Count+1, Val).
%%-------------------------------------------------------------
%% 顺序相关
%%-------------------------------------------------------------
%% @doc 将元素插入一个列表,要求两个参数均有序,这样结果仍然保持有序
insertsorted(NewGoods, L) ->
insertsorted(NewGoods, L, [], 1, []).
insertsorted([], T, Acc, _, Counts) ->
{lists:reverse(Acc, T), lists:reverse(Counts, [])};
insertsorted([NH|NT], [H|_T]=L, Acc, Count, Counts) when NH < H ->
insertsorted(NT, L, [NH|Acc], Count+1, [Count|Counts]);
insertsorted(Adds, [H|T], Acc, Count, Counts) ->
insertsorted(Adds, T, [H|Acc], Count+1, Counts).
%% @doc 将元素插入一个列表,要求两个参数均有序,这样结果仍然保持有序
%% 返回值是新列表和插入的几个元素被插入的位置列表
%% @end
insertsortedf(Pred, NewGoods, L) ->
insertsortedf(Pred, NewGoods, L, [], 1, []).
insertsortedf(_, NewGoods, [], Acc, Count, Counts) ->
{lists:reverse(Acc, NewGoods), lists:reverse(Counts, lists:seq(Count, Count+length(NewGoods)-1))};
insertsortedf(_, [], T, Acc, _, Counts) ->
{lists:reverse(Acc, T), lists:reverse(Counts, [])};
insertsortedf(Pred, [NH|NT] = Adds, [H|T]=L, Acc, Count, Counts) ->
case Pred(NH, H) of
true ->
insertsortedf(Pred, NT, L, [NH|Acc], Count+1, [Count|Counts]);
false ->
insertsortedf(Pred, Adds, T, [H|Acc], Count+1, Counts)
end.
%% @doc 直到Pred返回false之前一直fold
foldlwhile(Pred, Acc0, [H|T]) ->
case Pred(H, Acc0) of
{true, Acc} ->
foldlwhile(Pred, Acc, T);
{false, Acc} ->
Acc
end;
foldlwhile(_Pred, Acc, []) ->
Acc.
%% @doc 直到Pred返回default之前一直fold,注意返回的列表逆序
foldwhile(Pred, Acc0, [H|T], Default) ->
case Pred(H) of
Default -> Default;
Val -> foldwhile(Pred, [Val| Acc0], T, Default)
end;
foldwhile(_Pred, Acc, [], _Default) ->
Acc.
%% @doc 将一个列表分成几个子列表
%% e.g. [{a,1},{b,1},{a,2},{b,3},{c,1}] -> [{c,[1]},{b,[1,3]},{a,[1,2]}]
%% @end
classify(FC, L) ->
classify(FC, L, [], fun(E, Acc) -> [E|Acc] end).
classify(_, [], _, _) ->
[];
classify(FC, L, Acc0, FA) ->
lists:foldr(fun(Ele, Acc) ->
Key = FC(Ele),
case lists:keytake(Key, 1, Acc) of
false ->
[{Key, FA(Ele, Acc0)}|Acc];
{value, {Key, OldVal}, T} ->
[{Key, FA(Ele, OldVal)}|T]
end
end, [], L).
%% @doc 以Tuple中的第N个元素为Key,将一个列表分成几个子列表
%% e.g. [{a,1},{b,1},{a,2},{b,3},{c,1}] -> [{c,[1]},{b,[1,3]},{a,[1,2]}]
%% @end
keyclassify(N, L) ->
keyclassify(N, L, [], fun(E, Acc) -> [E|Acc] end).
keyclassify(_, [], _, _) ->
[];
keyclassify(N, L, Acc0, F) ->
lists:foldr(fun(Ele, Acc) ->
Key = element(N, Ele),
case lists:keytake(Key, 1, Acc) of
false ->
[{Key, F(Ele, Acc0)}|Acc];
{value, {Key, List}, NewAcc} ->
[{Key, F(Ele, List)}|NewAcc]
end
end, [], L).
%% @doc 与keyclassify的差别只在于顺序会倒过来,元素数量大(百万条以上?)时效率较高
%% 也许这个函数没有什么用
%% @end
keyclassifyl(N, L) ->
keyclassifyl(N, L, [], fun(E, Acc) -> [E|Acc] end).
keyclassifyl(_, [], _, _) ->
[];
keyclassifyl(N, L, Acc0, F) ->
lists:foldl(fun(Ele, Acc) ->
Key = element(N, Ele),
case lists:keytake(Key, 1, Acc) of
false ->
[{Key, F(Ele, Acc0)}|Acc];
{value, {Key, List}, NewAcc} ->
[{Key, F(Ele, List)}|NewAcc]
end
end, [], L).
%% @doc 按Key数个数
keycount(Key, N, L) when is_integer(N), N > 0 ->
keycount(Key, N, L, 0).
keycount(_Key, _N, [], Acc) ->
Acc;
keycount(Key, N, [H|T], Acc) when element(N, H) =:= Key ->
keycount(Key, N, T, Acc + 1);
keycount(Key, N, [_|T], Acc) ->
keycount(Key, N, T, Acc).
%% @doc 按Key做fold
keyfoldl(_, _, _, Acc, []) ->
Acc;
keyfoldl(Key, N, F, Acc, [H|T]) when element(N, H) =:= Key ->
keyfoldl(Key, N, F, F(H, Acc), T);
keyfoldl(Key, N, F, Acc, [_|T]) ->
keyfoldl(Key, N, F, Acc, T).
%% @doc 按Key做fold, 从右向左
keyfoldr(_, _, _, Acc, []) ->
Acc;
keyfoldr(Key, N, F, Acc, [H|T]) when element(N, H) =:= Key ->
F(H, keyfoldr(Key, N, F, Acc, T));
keyfoldr(Key, N, F, Acc, [_|T]) ->
keyfoldr(Key, N, F, Acc, T).
%% @doc 按key更新
keyupdate(Key, N, L, Fun) when is_function(Fun, 1) ->
case lists:keyfind(Key, N, L) of
false ->
false;
Tuple ->
lists:keyreplace(Key, N, L, Fun(Tuple))
end.
%% @doc 更新List中的某一项的某一项
%% e.g: -record(troop, {pos, fac_id, round}).
%% keyupdate(2, #troop.fac_id, #troop.round, [{troop, 1, 1101, 2}, {troop, 2, 1103, 1}], 3) ->
%% [{troop, 1, 1101, 2}, {troop, 2, 1103, 3}]
%% @end
keyupdate(Key, KN, EN, L, Fun) when is_function(Fun, 1) ->
case lists:keyfind(Key, KN, L) of
false -> L;
Tuple ->
Tuple2 = setelement(EN, Tuple, Fun(element(EN, Tuple))),
lists:keyreplace(Key, KN, L, Tuple2)
end;
keyupdate(Key, KN, EN, L, NewEle) ->
case lists:keyfind(Key, KN, L) of
false -> L;
Tuple ->
Tuple2 = setelement(EN, Tuple, NewEle),
lists:keyreplace(Key, KN, L, Tuple2)
end.
%% @doc 按tuple的第一个元素进行数量合并
%% eg. [{a, 1}, {b, 2}, {a, 3}, {c, 2}, {b, 1}] -> [{a, 4}, {b, 3}, {c, 2}].
nmerge(L) ->
classify(fun({X, _}) -> X end, L, 0, fun({_, N}, Acc) -> N + Acc end).
%%----------------------------------------------------------------------------
%% 优先级条件取子列表
%%----------------------------------------------------------------------------
%% @doc 按优先级过滤列表,要求得到N个元素;
%% 当满足所有条件的元素不足N个时,降格以求,去掉第一个条件继续检索;
%% 仍不足时,继续降格以求,但最后一个条件必须满足;
%% 得到N个元素时返回
%% 一个很重要的考虑是,List可能很大,发现N个时立即返回以满足性能要求,不要对List做全遍历
%% @end
priority_accept(L, FilterList, N) ->
priority_accept(L, FilterList, N, []).
priority_accept([], _, _, Acc) -> % 只有这些了
Acc;
priority_accept(_, [], _, Acc) -> % 只能这样了,不能再降格以求了
Acc;
priority_accept(_, _, 0, Acc) -> % 找齐了
Acc;
priority_accept(L, [_|T] = FilterList, N, Acc) ->
{Left, GotN, Got} = take(L, N, FilterList),
priority_accept(Left, T, N - GotN, Got ++ Acc).
%% @doc 从列表里取符合所有条件的N个元素
take(L, TargetN, FilterList) ->
take(L, TargetN, FilterList, 0, [], []).
take([], _, _, AccN, Acc, LeftAcc) -> % 只有这些
{LeftAcc, AccN, Acc};
take(_, TargetN, _, TargetN, Acc, LeftAcc) -> % 找齐了
{LeftAcc, TargetN, Acc};
take([H|T], TargetN, FilterList, AccN, Acc, LeftAcc) ->
case multi_filter(H, FilterList) of
true ->
take(T, TargetN, FilterList, AccN + 1, [H|Acc], LeftAcc);
false ->
take(T, TargetN, FilterList, AccN, Acc, [H|LeftAcc])
end.
%% @doc 判断一个元素是否符合一个条件列表
multi_filter(Item, FilterList) ->
lists:all(fun(Filter) -> Filter(Item) end, FilterList).
%% 没有想到这个实现还没有上面的实现效率高, 差了一倍
% %% @doc 按优先级过滤列表,要求得到N个元素;
% %% 当满足所有条件的元素不足N个时,降格以求,去掉第一个条件继续检索;
% %% 仍不足时,继续降格以求,但最后一个条件必须满足;
% %% 得到N个元素时返回
% %% @end
% priority_accept2(L, FilterList, Must, N) ->
% priority_accept2(L, FilterList, Must, N, []).
% priority_accept2([], _, _, _, Acc) -> % 只有这些了
% Acc;
% priority_accept2(_, _, _, 0, Acc) -> % 找齐了
% Acc;
% priority_accept2(L, [], Must, N, Acc) -> % 只能这样了,不能再降格以求了
% {_, _, Got} = take2(L, N, [], Must),
% Got ++ Acc;
% priority_accept2(L, [_|T] = FilterList, Must, N, Acc) ->
% {Left, GotN, Got} = take2(L, N, FilterList, Must),
% priority_accept2(Left, T, Must, N - GotN, Got ++ Acc).
%
% %% @doc 从列表里取符合所有条件的N个元素
% take2(L, TargetN, FilterList, Must) ->
% take2(L, TargetN, FilterList, Must, 0, [], []).
% take2([], _, _, _, AccN, Acc, LeftAcc) -> % 只有这些
% {LeftAcc, AccN, Acc};
% take2(_, TargetN, _, _, TargetN, Acc, LeftAcc) -> % 找齐了
% {LeftAcc, TargetN, Acc};
% take2([H|T], TargetN, FilterList, Must, AccN, Acc, LeftAcc) ->
% case multi_filter2(H, FilterList, Must) of
% true ->
% take2(T, TargetN, FilterList, Must, AccN + 1, [H|Acc], LeftAcc);
% false ->
% take2(T, TargetN, FilterList, Must, AccN, Acc, [H|LeftAcc]);
% dead ->
% take2(T, TargetN, FilterList, Must, AccN, Acc, LeftAcc)
% end.
%
% %% @doc 判断一个元素是否符合一个条件列表
% multi_filter2(Item, FilterList, Must) ->
% case Must(Item) of
% false ->
% dead;
% true ->
% lists:all(fun(Filter) -> Filter(Item) end, FilterList)
% end.
%% @doc 去除重复的元素
remove_duplicates(L) ->
sets:to_list(sets:from_list(L)).
%% @doc 减集并去重, 不保持原顺序
%% e.g. ([3,4,5,6], [1,2,3,3,4]) -> [6,5]
%% ([1,2,3,3,4], [3,4,5,6]) -> [2,1]
subtract_rmdup(L1, L2) ->
sets:to_list(sets:subtract(sets:from_list(L1), sets:from_list(L2))).
%%----------------------------------------------------------------------------
%% 随机相关
%%----------------------------------------------------------------------------
%% @doc 将数随机地分配给列表中的元素
%% e.g: 5, [a,b,c] -> [{a,1},{b,4}]
%% @end
randallot(Val, L) ->
N = length(L),
randallot(Val, L, N, lists:zip(L, lists:duplicate(N, 0))).
randallot(0, _, _, Acc) ->
Acc;
randallot(Val, L, N, Acc) ->
Key = lists:nth(random:uniform(N), L),
{_, OldVal} = lists:keyfind(Key, 1, Acc),
Acc2 = lists:keyreplace(Key, 1, Acc, {Key, OldVal+1}),
randallot(Val-1, L, N, Acc2).
%% @doc 将数随机地分配给列表中的元素, 另一种算法
%% e.g: 5, [a,b,c] -> [{a,1},{b,2},{c,2}]
%% @end
randallot2(_, []) ->
[];
randallot2(Val, [H]) ->
[{H,Val}];
randallot2(0, L) ->
N = length(L),
lists:zip(L, lists:duplicate(N, 0));
randallot2(Val, [H|T]) ->
V = random:uniform(Val+1)-1, % 直接用uniform范围是[1-Val],这样写的范围是[0-Val]
[{H, V}|randallot(Val - V, T)].
%% @doc 随机打乱一个列表
shuffle(L) ->
List1 = [{random:uniform(), X} || X <- L],
List2 = lists:keysort(1, List1),
[E || {_, E} <- List2].
%% @doc 另一种算法,随机打乱一个列表
shuffle2(L) ->
shuffle2(L, []).
shuffle2([], Acc) -> Acc;
shuffle2(L, Acc) ->
{Leading, [H | T]} = lists:split(random:uniform(length(L)) - 1, L),
shuffle2(Leading ++ T, [H | Acc]).
%% @doc 随机填充,即从候选列表中随机取数得到一个新列表,
%% Size表示目标列表的长度
%% @end
randstuff(Candidates, Size) when Size >= 0 ->
randstuff(Candidates, length(Candidates), Size, []).
randstuff(_, _, 0, Acc) ->
Acc;
randstuff(Candidates, N, Size, Acc) ->
randstuff(Candidates, N, Size - 1, [lists:nth(random:uniform(N), Candidates)|Acc]).
%% @doc 随机填充,即从候选列表中随机取数得到一个新列表,
%% Size表示目标列表的长度,
%% Limit表示每个候选值能出现的最大次数,
%% Size和Limit冲突时以Limit为准
%% @end
randstuff_withlimit(Candidates, Size, Limit, Tail) ->
L1 = randstuff_withlimit(Candidates, Size, Limit),
L = if length(Tail) > Size -> L1 ++ Tail; true -> Tail ++ L1 end,
shuffle(L).
randstuff_withlimit(Candidates, Size, Limit) when Size >= 0, Size =< Limit ->
% Size =< Limit 此时Limit无效
randstuff(Candidates, Size);
randstuff_withlimit(Candidates, Size, Limit) when Size >= 0, Size >= length(Candidates) * Limit ->
% 此情况下把所有能出的值出完也不够Size指定的数, 也就不用随机了
shuffle(lists:append([lists:duplicate(Limit, C) || C <- Candidates]));
randstuff_withlimit(Candidates, Size, Limit) when Size >= 0, is_list(Candidates) ->
randstuff_withlimit(Candidates, length(Candidates), Size, Limit, [], []).
randstuff_withlimit(_, _, 0, _, _, Acc) ->
% 达到目标Size
Acc;
randstuff_withlimit(_, 0, _, _, _, Acc) ->
% Candidates耗尽
Acc;
randstuff_withlimit(Candidates, N, Size, Limit, AccLimit, Acc) ->
C = lists:nth(random:uniform(N), Candidates),
{NewCount, AccLimit2} = case lists:keytake(C, 1, AccLimit) of
false ->
{1, AccLimit};
{value, {C, Count}, AccLimitTemp} ->
{Count + 1, AccLimitTemp}
end,
case NewCount >= Limit of
true ->
% 已达到Limit, 去除该候选值
randstuff_withlimit(Candidates -- [C], N - 1, Size - 1, Limit, [{C, NewCount}|AccLimit2], [C|Acc]);
false ->
randstuff_withlimit(Candidates, N, Size - 1, Limit, [{C, NewCount}|AccLimit2], [C|Acc])
end.
%% @doc 从附有概率的列表中抽取几个值,每得到一个值即将其从列表中移除再进行下一次抽取,使用相对概率
%% 例如: drawrand([{a, 1000}, {b, 2000}, {c, 500}, {d, 4000}], 2) -> [b, d]
%% @end
drawrand(L) ->
drawrand(L, 1).
drawrand(L, Round) ->
drawrand(L, Round, []).
drawrand([], _, Acc) -> % 牌抽完了,没得抽了
Acc;
drawrand(_, 0, Acc) -> % 抽够了,不抽了
Acc;
drawrand(L, Round, Acc) ->
{Obj, Pos} = pick_by_weight(L),
L2 = removeat(Pos, L),
drawrand(L2, Round - 1, [Obj | Acc]).
%% @doc 例: drawrand_index([3000,2000,300,100,50], 3) -> [1,2,4]
drawrand_index(L) ->
drawrand_index(L, 1).
drawrand_index(L, Round) ->
L2 = lists:zip(lists:seq(1, length(L)), L),
drawrand(L2, Round).
%% @doc 返回0到某个数,或两个数之间的随机数
rand(0) -> 0;
rand(N) when N > 0 ->
random:uniform(N).
rand(Min, Min)->
Min;
rand(Min, Max) when Min < Max ->
rand(Max - Min + 1) + Min - 1.
%% @doc 在列表中返回1个
rand_pick([_|_] = List) ->
Pos = rand(length(List)),
lists:nth(Pos, List);
rand_pick(Contents) when is_tuple(Contents) ->
element(rand:uniform(tuple_size(Contents)), Contents).
%% @doc 在列表中随机返回N个
rand_pick(L, N) ->
rand_pick(L, N, []).
rand_pick(_, 0, Result) -> % 已得到N个值
Result;
rand_pick([], _, Result) -> % 遍历结束,直接返回Result
Result;
rand_pick(L, N, Result) ->
Pos = rand(erlang:length(L)),
Val = lists:nth(Pos, L),
rand_pick(L--[Val], N-1, [Val|Result]).
%% @doc 依据权值选择
%% 列表格式:[{对象, 权值}]
%% 返回{对象,位置}
%% 每项的概率为 权值/权值总和
pick_by_weight(L) ->
pick_by_prob(L, lists:sum([W || {_, W} <- L])).
%% @doc 依据概率选择, 以10000为基准
%% 列表格式:[{对象,概率}]
%% 返回{对象,位置}
pick_by_prob(L) ->
pick_by_prob(L, 10000).
pick_by_prob(L, W) ->
Point = rand(W),
pick_by_prob(L, 0, Point, 1).
pick_by_prob([], _, _, _)->
false;
pick_by_prob([{Obj, Range} | _], Cur, Point, Index) when Cur < Point andalso Point =< (Range + Cur) ->
{Obj, Index};
pick_by_prob([{_, Range} | Rest], Cur, Point, Index) ->
pick_by_prob(Rest, Range + Cur, Point, Index + 1).
%% @doc 对每个元素随机选择
%% e.g. ([[{411002,6000},{411003, 4000}],[{411001, 3000}, {411002, 3000}, {411006, 4000}]]) -> [411002, 411006]
%% @end
rand_dissimilar_from_deeplist(L) when is_list(L) ->
rand_dissimilar_from_deeplist(L, []);
rand_dissimilar_from_deeplist(L) when is_tuple(L) ->
rand_dissimilar_from_deeplist(tuple_to_list(L), []).
rand_dissimilar_from_deeplist([], Acc) ->
lists:reverse(Acc);
rand_dissimilar_from_deeplist([H|T], Acc) ->
case lists:foldl(fun(Id, R) -> lists:keydelete(Id, 1, R) end, H, Acc) of
[] ->
rand_dissimilar_from_deeplist(T, Acc);
L ->
{Id, _} = pick_by_weight(L),
rand_dissimilar_from_deeplist(T, [Id | Acc])
end.
%% 列表元素是否完全一样
isallsame([]) ->
false;
isallsame([H]) ->
H;
isallsame([H|T]) ->
case lists:all(fun(I) -> I =:= H end, T) of
true -> H;
false -> false
end.
%% 列表元素tuple的某一项是否完全一样
key_isallsame(_N, []) ->
false;
key_isallsame(N, [H]) ->
element(N, H);
key_isallsame(N, [H|T]) ->
Key = element(N, H),
case lists:all(fun(I) -> element(N, I) =:= Key end, T) of
true -> Key;
false -> false
end.
ets_take(Ets, N) ->
ets_take(Ets, N, ets:first(Ets), 0, []).
ets_take(_Ets, _N, '$end_of_table', _, Acc) ->
Acc;
ets_take(_Ets, N, _, N, Acc) ->
Acc;
ets_take(Ets, N, Key, AccN, Acc) ->
ets_take(Ets, N, ets:next(Ets, Key), AccN + 1, [Key|Acc]).
%% 将列表按类型和顺序切分成多个子列表
split_into(F, [H|T]) ->
split_into2(F, T, F(H), [H], []).
split_into2(_F, [], Tag, AccSub, Acc) ->
Acc2 = [{Tag, lists:reverse(AccSub)} | Acc],
lists:reverse(Acc2);
split_into2(F, [H|T], Tag, AccSub, Acc) ->
TagCur = F(H),
case TagCur of
Tag ->
% 类型相同
split_into2(F, T, Tag, [H|AccSub], Acc);
_ ->
% 类型不同
AccSub2 = {Tag, lists:reverse(AccSub)},
split_into2(F, T, TagCur, [H], [AccSub2|Acc])
end.
%% 两两分组
divide_every_two(L) ->
divide_every_two(L, []).
divide_every_two([], Acc) ->
{lists:reverse(Acc), []};
divide_every_two([H], Acc) ->
{lists:reverse(Acc), [H]};
divide_every_two([H1, H2|T], Acc) ->
Acc2 = [{H1, H2}|Acc],
divide_every_two(T, Acc2).
%% 多线程执行lists:map
pmap(F, L) ->
S = self(),
%% make_ref() returns a unique reference
%% we'll match on this later
Ref = erlang:make_ref(),
Pids = lists:map(fun(I) ->
spawn(fun() -> do_f(S, Ref, F, I) end)
end, L),
%% gather the results
gather(Pids, Ref).
do_f(Parent, Ref, F, I) ->
Parent ! {self(), Ref, (catch F(I))}.
gather([Pid|T], Ref) ->
receive
{Pid, Ref, Ret} -> [Ret|gather(T, Ref)]
end;
gather([], _) ->
[].