https://codereview.stackexchange.com/a/253314/30419

Created Diff never expires
45 removals
55 lines
43 additions
55 lines
#define queueSize 16
let queueSize = 16




#define increaseIndex(x) ({x++; if(x >= queueSize) x = 0;})
func increaseIndex(_ x: Int) -> Int {
let x = x + 1
return x < queueSize
? x
: 0
}




int rssiArray[queueSize] = {0};
var rssiArray = [0]
int sortRssi[queueSize] = {0};
var sortRssi = [0]
int rssiIndex = 0;
var rssiIndex = 0




static double getDistance(double rssi, int txPower) {
private func getDistance(rssi: Double, txPower: Int) -> Double? {
if (rssi == 0) {
return rssi == 0
return -1.0; // if we cannot determine accuracy, return -1.
? nil
}
: pow(10, (Double(txPower) - rssi) / 20)
return pow(10, ((double) txPower - rssi) / (10 * 2));
}
}




static double calculateAccuracy(double rssi, int txPower) {
private func calculateAccuracy(rssi: Double, txPower: Int) -> Double? {
if (rssi == 0) {
guard rssi != 0 else {
return -1.0; // if we cannot determine accuracy, return -1.
return nil
}
double ratio = rssi * 1.0 / txPower;
if (ratio < 1.0) {
return pow(ratio, 10);
} else {
double accuracy = (0.89976) * pow(ratio, 7.7095) + 0.111;
return accuracy;
}
}
let ratio = rssi * (1 / Double(txPower))
return ratio < 1
? pow(ratio, 10)
: (0.89976) * pow(ratio, 7.7095) + 0.111
}
}




int cmpfunc (const void * a, const void * b) {
private func calculateAverage() -> Double {
return ( *(int*)a - *(int*)b );
sortRssi = Array(rssiArray.sorted(by: >).dropFirst(3))
return sortRssi.averaged(while: { $0 != 0 })
}
}




static double calculateAverage() {

double average = 0;
extension Collection where Element: BinaryInteger {
int i = 0;
func averaged(while allowedPrefixPredicate: (Element) -> Bool) -> Double {
int drop = 3;
lazy
memcpy(sort_rssi, rssi_array, queueSize * sizeof(int));
.prefix(while: allowedPrefixPredicate)
qsort(sort_rssi, queueSize, sizeof(int), cmpfunc);
.map(Double.init)
for (i = 0; i < queueSize - drop; ++i) {
.reduce(into: 0, +=)
if(sort_rssi[i + drop] == 0) break;
/ Double(count)
average += sort_rssi[i];
}
}
return average / i;
}
}


// For adding new rssi we can use this code:
// For adding new rssi we can use this code:
rssiArray[rssiIndex] = rssi;
rssiArray[rssiIndex] = rssi
increaseIndex(rssiIndex);
rssiIndex = increaseIndex(rssiIndex)
double meanRssi = calculateAverage();
let meanRssi = calculateAverage()