Created
December 4, 2024 12:25
-
-
Save juanfal/fc24648f63998854949b4e11cac493ac to your computer and use it in GitHub Desktop.
center of vector
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// centrovector.cpp | |
// juanfc 2014-02-25 | |
// | |
// Consider a vector V that contains N natural values (an array of naturals of | |
// size N, being N any constant). Define the centre c of vector V as the index | |
// between 1 and N–2 that follows: | |
// | |
// This property is not always met; in that case we say that there is no centre. | |
// Design procedure centreOfVector that receives a vector V as parmeter and | |
// returns two values as parameters: first one says if there is a centre and | |
// second one, if so, the value of that index. | |
// Supposing N = 5: | |
// 1st Example: | |
// V is: 6 2 3 0 1 | |
// Then centre is 1 (cell with 2) because: | |
// - Left sum: (1-0)*V[0] = 1*6 = 6 | |
// - Right sum: (2-1)*V[2]+(3-1)*V[3]+(4-1)*V[4] = 1*3+2*0+3*1 = 6 | |
// 2nd Example: | |
// V is: 1 2 1 1 0 | |
// No centre | |
#include <iostream> | |
using namespace std; | |
const int N = 10; | |
typedef int TVector[N]; | |
int main() | |
{ | |
void centreOfVector(TVector v, bool& is, int& c); | |
int centreOfVector(TVector v); | |
bool ok; | |
int c; | |
centreOfVector((TVector){6, 2, 3, 0, 1}, ok, c); | |
if (ok) | |
cout << "{6, 2, 3, 0, 1} has a center in " << c << endl; | |
else | |
cout << "{6, 2, 3, 0, 1} has Not a center" << endl; | |
centreOfVector((TVector){1, 2, 1, 1, 0}, ok, c); | |
if (ok) | |
cout << "{1, 2, 1, 1, 0} has a center in " << c << endl; | |
else | |
cout << "{1, 2, 1, 1, 0} has NOT a center" << endl; | |
cout << centreOfVector((TVector){6, 2, 3, 0, 1}) << endl; | |
cout << centreOfVector((TVector){1, 2, 1, 1, 0}) << endl; | |
return 0; | |
} | |
void centreOfVector(TVector v, bool& is, int& c) | |
{ | |
int sumUpto(TVector a, int c); | |
int sumFrom(TVector a, int c); | |
c = 0; | |
is = false; | |
while (c < N and not (is = sumUpto(v, c) == sumFrom(v, c))) { | |
++c; | |
} | |
} | |
// also possible returning the index, -1 if not. | |
int centreOfVector(TVector v) | |
{ | |
int sumUpto(TVector a, int c); | |
int sumFrom(TVector a, int c); | |
int c = 0; | |
while (c < N and sumUpto(v, c) != sumFrom(v, c) ) { | |
++c; | |
} | |
if (c >= N) | |
c = -1; | |
return c; | |
} | |
int sumUpto(TVector a, int c) | |
{ | |
int s = 0; | |
for (int i = 0; i < c; i++) | |
s += a[i] * (c - i); | |
return s; | |
} | |
int sumFrom(TVector a, int c) | |
{ | |
int s = 0; | |
for (int i = c + 1; i < N; i++) | |
s += a[i] * (i - c); | |
return s; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment