c - Efficient comparison of small integer vectors -


i have small vectors. each of them made of 10 integers between 0 , 15. means every element in vector can written using 4 bits. hence can concatenate vector elements , store whole vector in single long type (in c, c++, java...)

vector v1 dominates vector v2 if each in 0,...,9, v1[i] >= v2[i]

i want write method compare(long v1, long v2) return 0 if non of vectors dominates other, 1 if first 1 dominates , -1 if second 1 dominates.

is there efficient way implement compare other getting every component , doing 10 times normal integer comparison?

edit

if v1 same v2 returning 1 or -1 both fine

it's possible using bit-manipulation. space values out each takes 5 bits, 4 bits value , empty 0 in significant position kind of spacing bit.

placing spacing bit between each value stops borrows/carries propagating between adjacent values , means can simd-like arithmetic operations on vector using regular integer addition or subtraction. can use subtraction vector comparison.

to test can set spacing bits 1 in 1 of vectors , subtract second one. if value in 4 bits below spacing bit greater in second 1 carry bit spacing bit , set 0 in result, if not remain 1 (the first value greater or equal second). if first vector dominates second spacing bits 1 after subtraction.

simple demonstration using ints:

#define spacing_bits ((1<<4)|(1<<9)|(1<<14)|(1<<19)) int createvector(int v0, int v1, int v2, int v3) {     return v0 | (v1 << 5) | (v2 << 10) | (v3 << 15); }  int vectordominates(int vectora, int vectorb) {      // returns 1 if vectora dominates vectorb:      return (((vectora | spacing_bits) - vectorb) & spacing_bits) == spacing_bits; }  int compare(int vectora, int vectorb) {     if(vectordominates(vectora, vectorb))         return 1;     else if(vectordominates(vectorb, vectora))         return -1;     return 0; } 

you can extend use 64 bit values using 50 bits store 10 values. can inline calls vectordominates in compare function.

demo


Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -