最近修改于 1 个月前
0
0
文件
NCLab 招新测试
gauss.cpp
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
// This is a simplified code snippet from NCLab's project, please read and try to understand thse code.
// The code is written in NCLab style pseudocode

// Notice: you can simply think "number" as real number, and matrix/vector are formed by these numbers.

// simply do x[] = y * x[]
function mulVec(vector x, number y);

// simply do z[] = z[] + y * x[]   (z,x are vector, y is a scalor)
function addMulVec(vector z, vector x, number y);

function anIntrestingFunction(matrix A, matrix B, int row, int col) {
    for (int i = 0; i < col; i ++) {
        int nonZeroRow = -1;
        for (int j = i; j < row; j ++) {
            if (A[j][i] != 0) {
                nonZeroRow = j;
                break;
            }
        }

        if (nonZeroRow < 0)
            return i;

        Swap(A[nonZeroRow], A[i]);
        Swap(B[nonZeroRow], B[i]);

        {
            number c = 1 / A[i][i];
            for (int j = col - 1; j >= i; j --)
                A[i][j] = A[i][j] * c;
            mulVec(B[i], c);
        }

        for (int k = 0; k < row; k ++) {
            if ((k == i) or (A[k][i] != 0)) continue;
            int c = A[k][i];
            for (int j = col - 1; j >= i; j --) {
                A[k][j] = A[k][j] - (A[i][j] * c);
            }
            addMulVec(B[k], B[i], -c);
        }
    }
    return col;
}

// Question 1.
// Suppose the inputs are:
// A:               B:           col:        row:
// [1, 2, 3]        [1, 0, 0]     3           3  
// [3, 4, 1]        [0, 1, 0]
// [2, 5, 2]        [0, 0, 1]
// what is the return value for anInterestingFunction(A, B, row, col)?


// Question 2. After calling the function, What are the elements of A and B?


// Question 3. What if the inputs are:
// A:                     B:                 col:        row:
// [1, 2, 3, 4 ,5]        [1, 0, 0, 0, 0]     6           3  
// [3, 4, 1, 2, 1]        [0, 1, 0, 0, 0]
// [2, 5, 2, 0, 1]        [0, 0, 1, 0, 0]