-
Notifications
You must be signed in to change notification settings - Fork 0
/
array.h
56 lines (45 loc) · 2.45 KB
/
array.h
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
#pragma once
#include <stdint.h>
#include "random.h"
/*
combsort(A,length) sort array with combsort
usort(A,length) fast unsigned integer radix sort
reduce(func,arr,len) return accumulated value from func(accum,arr[i])
formap(func,arr,len) set len elements to func(arr[i])
foreach(func,arr,len) execute func(arr[i]) for len elements
dupfilter(arr,len) check if array(or its first len members) has duplicates(1) or not (0)
uniqueset(arr,len,rangestart) set len elements of array to rangestart+i
uniquesetrand(arr,len,rangemin,rangemax) set array elements to unique values in range
*/
#define combsort(A,lenx) ({size_t i,j, gap=lenx,len=gap;;;\
do{gap = gap<10 ? gap-1 : (gap*7)/9+1;\
for (i=0,j=gap; j<len; i++,j++){\
const typeof(A[0]) tmp=A[i];\
const int cnd=tmp>A[j];\
A[i]=cnd?A[j]:tmp;A[j]=cnd?tmp:A[j];};}while (gap);})
#define radix3(byte,siz,A,TEMP) ({ ;\
i64 count[256]={0};int sh=byte*8;\
for(i64 i=0;i<siz;i++){ ;\
count[((A[i]>>sh)&255)]++;};\
for(i64 i=1;i<256;i++)count[i] +=count[i-1];\
for(i64 i=siz-1;i>-1;i--){;TEMP[(--count[((A[i] >> (sh))&0xff)])] = A[i];} ;;})
//for bytes use counting sort
#define usort(arr,elems) ({\
typeof(arr[0])* tarr=malloc(sizeof(arr[0])*elems);\
for(int i=0;i<sizeof(arr[0]);i++){\
if(i&1){radix3(i, elems,tarr,arr); }else{\
radix3(i, elems,arr,tarr);}};free(tarr) ;})
#define reduce(func,arr,len) ({ typeof(arr[0]) accum=arr[0];\
for(size_t i=1;i<len;i++)accum=func(accum,arr[i]); accum;})
#define formap(func,arr,len) ({for(size_t i=0;i<len;i++){arr[i]=func(arr[i]);};arr;})
#define foreach(func,arr,len) ({for(size_t i=0;i<len;i++){func(arr[i]);};arr;})
#define dupfilter(arr,len) ({size_t location=-1;\
for(size_t i=0;i<len;i++){ typeof(arr[0]) t=arr[i]; for(size_t x=i+1;x<len;x++)if(t==arr[x]){location=x;break;} if(location!=-1)break; }location;})
#define uniqueset(arr,len,rangestart) ({typeof(rangemax) cur=rangestart;\
for(size_t i=0;i<len;i++){arr[i]=cur++;};arr; })
#define uniquesetrand(arr,len,rangemin,rangemax) ({size_t loc=-1; \
for(size_t i=0;i<len;i++){arr[i]=rrange(rangemin,rangemax);};\
for(loc=dupfilter(arr,len);loc!=-1;loc=dupfilter(arr,len)){ arr[loc]=rrange(rangemin,rangemax); };arr; })
#define arrcopy(dest,src,len) ({for(size_t i=0;i<len;i++)dest[i]=src[i];dest;})
#define arr2copy(dest,locs,src,len) ({for(size_t i=0;i<len;i++)dest[locs[i]]=src[i];dest;})
#define arrcopy2(dest,src,locs,len) ({for(size_t i=0;i<len;i++)dest[i]=src[locs[i]];dest;})