int main (int argc, char **argv) { eliminate(argv[1]); printf("%s", argv[1]); return 0; }
int main() { int i, it, len; freopen(FIN, "r", stdin); freopen(FOUT, "w", stdout); scanf("%d",&n); len = n; for(i = 1; i <= n; i++) scanf("%d", &arr[i]); create_heap(); for(it = 1; it <= len; it++ ) { printf("%d ", eliminate()); } print(); return(0); };
/* pA: the pointer of the Matrix A|b rowMax,colMax:size of matirx pX: solution vector return value: -1 solving equation failed 1 resolve result successfully */ int gaussLesung(double *pA, int rowMax,int colMax, double *pX) { double *pMatrix = pA; int i; double product; product = 1; if((1+rowMax)!=colMax) return -1; for(i = 0; i < rowMax; i++) { int l; printf("%d,\n",i); l = findMax(pMatrix, rowMax, colMax, i,i); exchangeRow(pMatrix, rowMax, colMax, l, i); eliminate(pMatrix, rowMax, colMax, i, i); outputMatrix(pMatrix, rowMax, colMax); } for(i = 0; i < rowMax; i++)product = product * pMatrix[i*colMax+i]; if(product==0)return -1; solveX(pMatrix, rowMax,colMax, pX); return 1; }
static int eliminate(char* board, const int strides[2], char color, int x, int y) { int n_eliminated = 1; board[x*strides[0] + y*strides[1]] = ' '; // Visit adjacent cells for(int dx=-1; dx<=1; dx++) { for(int dy=-1; dy<=1; dy++) { if(abs(dx+dy) != 1 || x+dx<0 || x+dx>=6 || y+dy<0 || y+dy>=12) { continue; } int cell_idx = (x+dx)*strides[0] + (y+dy)*strides[1]; if(board[cell_idx] == color) { n_eliminated += eliminate(board, strides, color, x+dx, y+dy); } else if(board[cell_idx] == 'k') { board[cell_idx] = ' '; } } } return n_eliminated; }
void eliminate(std::vector<size_t> indexes) { std::cout << "Input: " << endl << getResult() << endl << endl; auto pivotingPtr = Pivoting<Inequalities>::create(parameters.pivotingType, indexes); while (!pivotingPtr->isOver()) { size_t index = pivotingPtr->getNext(inequalities); eliminate(index); std::cout << "Result after index " << index << ":\n"; std::cout << getResult() << endl << endl; } }
void unifier::operator()(const type_operator& x, const type_variable& y) { if(occurs(x, y)) throw recursive_unification(y, x); /*for(const auto& i : x) { type ty = type(y); type ti = type(i); boost::apply_visitor(*this, ty, ti); }*/ eliminate(y, x); }
int solve(Matrix *m, double *X) { int rc = eliminate(m); if (rc) return rc; int j,k; int r=m->rows, c=m->cols; double t, *dv=m->dv; for (j=r-1; j>=0; j--) { if (dv[jj] == 0) return -1; t=0; for (k=j+1; k<c-1; k++) t += dv[jk] * X[k]; X[j] = (dv[j*c + (c-1)] - t) / dv[jj]; } return 0; }
int reduceMSP(MSP* msp){ int** matrix = msp->matrix; char** label = msp->label; int cols = msp->cols; int rows = msp->rows; int** new_matrix = calloc(rows, sizeof(int*)); { int i = 0; for(i; i < rows; i++){ new_matrix[i] = calloc(rows, sizeof(int)); new_matrix[i][i] = 1; } } // Gauss-Jordan int i_row = 0; int i_col = 0; while( i_row < rows && i_col < cols ){ //look for a non-zero entry in col i_col at or below row i_row int k = i_row; while( k < rows && matrix[k][i_col] == 0 ) k++; if( k <= rows ){ if( k != i_row ){ //swap swap_vector(matrix, i_row, k); swap_vector(new_matrix, i_row, k); swap_label(label, i_row, k); } if( matrix[i_row][i_col] != 1){ //divide int div = matrix[i_row][i_col] / 1; divide_row_by_n( matrix, i_row, cols, div); divide_row_by_n( new_matrix, i_row, rows, div); } //eliminate eliminate(matrix, i_row, i_col, rows, cols, new_matrix); i_row++; } i_col++; } msp->matrix = new_matrix; msp -> cols = msp -> rows; return 1; }
void unifier::operator()(const type_variable& x, type_variable& y) { /*if(x.id() != y.id() || !x.same_ctx(y)) { y.insert(x.begin(), x.end()); eliminate(x, y); }*/ if(x != y) { auto it = _ctxs.find(x.id()); if(it != _ctxs.end()) { //auto& s = it->second; //_ctxs[y.id()].insert(s.begin(), s.end()); _ctxs[y.id()].insert(it->second.begin(), it->second.end()); } eliminate(x, y); } }
static int propogate(puzzle_t *puz) { int row, col/*, i*/; char *vals; //for (i = 0; i < NUM_DIGITS; i++) { for (row = 0; row < NUM_ROWS; row++) { for (col = 0; col < NUM_COLS; col++) { vals = puz->squares[row][col].vals; if (strlen(vals) == 1) { if (!eliminate(puz, row, col)) return 0; } } } //} return 1; }
lbool SimpSolver::solve(const vec<Lit>& assumps, bool do_simp, bool turn_off_simp) { vec<Var> extra_frozen; lbool result = l_True; do_simp &= use_simplification; do_simp &= (decisionLevel() == 0); if (do_simp){ // Assumptions must be temporarily frozen to run variable elimination: for (int i = 0; i < assumps.size(); i++){ Var v = var(assumps[i]); // If an assumption has been eliminated, remember it. if (isEliminated(v)) remember(v); if (!frozen[v]){ // Freeze and store. setFrozen(v, true); extra_frozen.push(v); } } if(eliminate(turn_off_simp)) result = l_True; else result = l_False; } if (result == l_True) result = Solver::solve(assumps); if (result == l_True) { extendModel(); #ifndef NDEBUG verifyModel(); #endif } if (do_simp) // Unfreeze the assumptions that were frozen: for (int i = 0; i < extra_frozen.size(); i++) setFrozen(extra_frozen[i], false); return result; }
/* solve a linear system whose coefficient matrix is upper triangular */ void solve_triangular(size_t n, num *equation) { size_t k; for (k = n - 1; k < n; --k) { const size_t h = find_first_nonzero( k + 1, equation + k * (n + 1) + k, -(ptrdiff_t)(n + 1) ); if (h != (size_t)(-1)) { size_t j; const size_t i = k - h; for (j = i - 1; j < k; --j) { eliminate(n, equation, i, j, k); } } } }
int main(int argc, char **argv) { int n; double **pFile, **e, **s; if (argc == 1) { printf("Please enter the file name which contain Matrix data!\n\nUsage: %s <filename>\n", argv[0]); exit(EXIT_FAILURE); } pFile = readMatrix(argv[1], &n, 1); #ifdef DEBUG output_A(pFile, n, n); #endif e = eliminate((const double **)pFile, n, n+1); if (!e) exit(EXIT_FAILURE); printf("RESULT...\n"); output_A(e, n, n+1); s = solve(e, n); printf("方程的解为:\n"); output_A(s, 1, n); // 求逆阵 double **T = readMatrix("gauss_inverse", &n, 0); double **M_I = matrix_I(n); output_A(T, n, n); #ifdef DEBUG_INVERSE printf("输出单位矩阵:\n"); output_A(M_I, n, n); #endif double **II = invers(T, M_I, n); revers(II, n, n); printf("输出逆阵:\n"); output_A(II, n, n); printf("测试:\n"); output_A(multi(T, II, n), n, n); return 0; }
void eliminateMatrix( char* str, int nthrds, int method, int affinity, uint32 blocksize, int dimension, int outerloop, int pivoting, int cacheOblivious, uint64 prime, int print) { Matrix A; // read files, stores matrices, etc FILE* file = fopen(str,"rb"); // take A from file A.read(file); eliminate(A, nthrds, blocksize, method, dimension, affinity, outerloop, pivoting, cacheOblivious, prime); if (print) A.print(); // clear memory A.clear(); }
/* reduce to row echelon form */ void row_echelon(size_t n, num *equation) { size_t i = 0, k; for (k = 0; k != n; ++k) { const size_t h = find_first_nonzero( n - i, equation + i * (n + 1) + k, (ptrdiff_t)(n + 1) ); if (h != (size_t)(-1)) { size_t j; el_swap(n, equation, i, i + h); for (j = i + 1; j < n; ++j) { eliminate(n, equation, i, j, k); } ++i; } } }
void VarElim::processFactorList (const VarIds& vids) { totalFactorSize_ = 0; largestFactorSize_ = 0; for (size_t i = 0; i < elimOrder_.size(); i++) { if (Globals::verbosity >= 2) { if (Globals::verbosity >= 3) { Util::printDashedLine(); printActiveFactors(); } cout << "-> summing out " ; cout << fg.getVarNode (elimOrder_[i])->label() << endl; } eliminate (elimOrder_[i]); } Factor* finalFactor = new Factor(); for (size_t i = 0; i < factorList_.size(); i++) { if (factorList_[i]) { finalFactor->multiply (*factorList_[i]); delete factorList_[i]; factorList_[i] = 0; } } VarIds unobservedVids; for (size_t i = 0; i < vids.size(); i++) { if (fg.getVarNode (vids[i])->hasEvidence() == false) { unobservedVids.push_back (vids[i]); } } finalFactor->reorderArguments (unobservedVids); finalFactor->normalize(); factorList_.push_back (finalFactor); if (Globals::verbosity > 0) { cout << "total factor size: " << totalFactorSize_ << endl; cout << "largest factor size: " << largestFactorSize_ << endl; cout << endl; } }
ExecStatus GqInt<VY>::propagate(Space& home, const ModEventDelta& med) { if (IntView::me(med) == ME_INT_VAL) add(home); // Eliminate subsumed views eliminate(home); GECODE_ME_CHECK(y.lq(home, x.size() + vs.size())); if (x.size() == 0) return home.ES_SUBSUMED(*this); if (vs.size() >= y.max()) return home.ES_SUBSUMED(*this); GECODE_ES_CHECK(prune_upper(home,g)); return ES_NOFIX; }
void SolveGEIP(const Matrix& A, Vector &x, const Vector& b) { // Verify that the system is well-formed const int size = A.Rows(); if ((A.Cols() != size) || (b.Size() != size)) { throw NonconformableShapesError(); } // Prepare the augmented matrix Matrix aug(size, size+1, NaN()); for (int i = 0; i < size; ++i) { aug.Col(i) = A.Col(i); } aug.Col(size) = b; // Go to town... eliminate(aug, size, fabs(1e-14)); back_substitute(aug, size); x = aug.Col(size); }
/** * C implementation of `Board._eliminate_beans()`. */ void board_eliminate_beans(char* board, const int strides[2], unsigned int* n_beans_out, unsigned int* n_colors_out, unsigned int* group_bonus_out) { unsigned int n_beans = 0; unsigned int group_bonus = 0; bool colors_eliminated[5] = {false, false, false, false, false}; int n_colors = 0; bool visited[6][12]; for(int x=0; x<6; x++) { for(int y=0; y<12; y++) { visited[x][y] = false; } } for(int x=0; x<6; x++) { for(int y=0; y<12; y++) { if(should_eliminate(board, strides, visited, x, y)) { char color = board[x*strides[0] + y*strides[1]]; int n = eliminate(board, strides, color, x, y); n_beans += n; group_bonus += group_bonus_table[MIN(n, group_bonus_table_len-1)]; int color_idx = get_color_idx(color); if(!colors_eliminated[color_idx]) { n_colors++; } colors_eliminated[color_idx] = true; } } } *n_beans_out = n_beans; *n_colors_out = n_colors; *group_bonus_out = group_bonus; }
int main(int argc, char *argv[]) { int i; for (i = 0; i < NUM_TUNES; ++i) unhash(unhash_table[i], i); strcpy(guess_this, "AABBC"); num_possible = NUM_TUNES; for (i = 0; i < NUM_TUNES; ++i) is_possible[i] = 1; for (i = 1; i < argc; ++i) { int g = next_guess(i); int result = ((argv[i][0]-'0') << 3) + (argv[i][1]-'0'); eliminate(g, result); } if (num_possible < 1) { printf("ACK!"); } else if (num_possible == 1) { for (i = 0; i < NUM_TUNES; ++i) if (is_possible[i]) break; printf("%.5s 1\n", unhash_table[i]); } else { printf("%.5s %d\n", unhash_table[next_guess(i)], num_possible); } return 0; }
void update_grid() { int i, j; int count = 0; recursion_count++; for(i=0; i<9; i++) { for(j=0;j<9;j++) { if(grid[i][j] == 0) { count += update_cell(i,j); } } } if(count > 0) update_grid(); else { if(resolved_cells == 81) { printf("\nSolution:\n"); display(); } else { if(eliminate()) update_grid(); else { display(); printf("\nAfter %d recursive steps cells resolved: %d.\n\n", recursion_count, resolved_cells); } } } }
/* * Readout editfield & calculate the polynomial factors. */ void read_editfield(int *polyfactors) { int marker_w, marker_h, zy, w,h,i; double *mp; OBJECT *tree; tree = rs_trindex[POLY_ED]; marker_w = ObW(P_P1)/2; /* half marker width in pixels */ marker_h = ObH(P_P1)/2; w = ObW(P_EDITFIELD)-ObW(P_P1); h = ObH(P_EDITFIELD)-ObH(P_P1); zy = ObY(P_ZEROLINE); /* read marker positions */ mp = &mat_p[0][0]; *mp++ = (double)(ObX(P_P1)+marker_w); *mp++ = (double)(zy-ObY(P_P1)+marker_h); *mp++ = (double)(ObX(P_P2)+marker_w); *mp++ = (double)(zy-ObY(P_P2)+marker_h); *mp++ = (double)(ObX(P_P3)+marker_w); *mp++ = (double)(zy-ObY(P_P3)+marker_h); /* convert marker positions into real float data */ for (i=0; i<PDEGREE; i++) { mat_p[i][0] = (XSCALE*mat_p[i][0])/(double)w; mat_p[i][1] = (YSCALE*mat_p[i][1])/(double)h; }; /* calculate the polynomial parameters */ build_equations(); eliminate(); substitute(); /* convert into CKBD format */ for (i=0; i<4; i++) polyfactors[i]=0; for (i=0; i<PDEGREE; i++) polyfactors[i+(4-PDEGREE)]=(int)(256.0*mat_x[i]); }
void factor_subgroup (struct pcp_vars *pcp) { register int *y = y_address; FILE * Subgroup; int flag; int cp; int i; Subgroup = fopen ("ISOM_Subgroup", "r"); if (Subgroup == (FILE *) NULL) return; while (!feof (Subgroup)) { if (fscanf (Subgroup, "%d", &flag) == -1) continue; /* should we eliminate (in order to renumber the generators)? */ if (flag == ELIMINATE) eliminate (FALSE, pcp); if (fscanf (Subgroup, "%d", &flag) == -1) continue; setup_symbols (pcp); cp = pcp->lused; setup_word_to_collect (Subgroup, PRETTY, WORD, cp, pcp); for (i = 1; i <= pcp->lastg; ++i) y[cp + pcp->lastg + i] = 0; echelon (pcp); } CloseFile (Subgroup); }
ExecStatus Prop<View>::propagate(Space& home, const ModEventDelta& med) { // Add assigned views to value set if (View::me(med) == ME_INT_VAL) add(home,vs,x); // Eliminate views from x eliminate(home); if (x.size() == 0) { // y must have values in the value set ValSet::Ranges vsr(vs); GECODE_ME_CHECK(y.inter_r(home,vsr,false)); return home.ES_SUBSUMED(*this); } // Constrain y to union of x and value set Region r(home); assert(x.size() > 0); ValSet::Ranges vsr(vs); ViewRanges<View> xsr(x[x.size()-1]); Iter::Ranges::NaryUnion u(r,vsr,xsr); for (int i=x.size()-1; i--; ) { ViewRanges<View> xir(x[i]); u |= xir; } GECODE_ME_CHECK(y.inter_r(home,u,false)); // Check whether all values in y are already in the value set if (vs.subset(y)) return home.ES_SUBSUMED(*this); return ES_FIX; }
int lux_decomp(LUX *lux, int (*col)(void *info, int j, int ind[], mpq_t val[]), void *info) { int n = lux->n; LUXELM **V_row = lux->V_row; LUXELM **V_col = lux->V_col; int *P_row = lux->P_row; int *P_col = lux->P_col; int *Q_row = lux->Q_row; int *Q_col = lux->Q_col; LUXELM *piv, *vij; LUXWKA *wka; int i, j, k, p, q, t, *flag; mpq_t *work; /* allocate working area */ wka = xmalloc(sizeof(LUXWKA)); wka->R_len = xcalloc(1+n, sizeof(int)); wka->R_head = xcalloc(1+n, sizeof(int)); wka->R_prev = xcalloc(1+n, sizeof(int)); wka->R_next = xcalloc(1+n, sizeof(int)); wka->C_len = xcalloc(1+n, sizeof(int)); wka->C_head = xcalloc(1+n, sizeof(int)); wka->C_prev = xcalloc(1+n, sizeof(int)); wka->C_next = xcalloc(1+n, sizeof(int)); /* initialize LU-factorization data structures */ initialize(lux, col, info, wka); /* allocate working arrays */ flag = xcalloc(1+n, sizeof(int)); work = xcalloc(1+n, sizeof(mpq_t)); for (k = 1; k <= n; k++) { flag[k] = 0; mpq_init(work[k]); } /* main elimination loop */ for (k = 1; k <= n; k++) { /* choose a pivot element v[p,q] */ piv = find_pivot(lux, wka); if (piv == NULL) { /* no pivot can be chosen, because the active submatrix is empty */ break; } /* determine row and column indices of the pivot element */ p = piv->i, q = piv->j; /* let v[p,q] correspond to u[i',j']; permute k-th and i'-th rows and k-th and j'-th columns of the matrix U = P*V*Q to move the element u[i',j'] to the position u[k,k] */ i = P_col[p], j = Q_row[q]; xassert(k <= i && i <= n && k <= j && j <= n); /* permute k-th and i-th rows of the matrix U */ t = P_row[k]; P_row[i] = t, P_col[t] = i; P_row[k] = p, P_col[p] = k; /* permute k-th and j-th columns of the matrix U */ t = Q_col[k]; Q_col[j] = t, Q_row[t] = j; Q_col[k] = q, Q_row[q] = k; /* eliminate subdiagonal elements of k-th column of the matrix U = P*V*Q using the pivot element u[k,k] = v[p,q] */ eliminate(lux, wka, piv, flag, work); } /* determine the rank of A (and V) */ lux->rank = k - 1; /* free working arrays */ xfree(flag); for (k = 1; k <= n; k++) mpq_clear(work[k]); xfree(work); /* build column lists of the matrix V using its row lists */ for (j = 1; j <= n; j++) xassert(V_col[j] == NULL); for (i = 1; i <= n; i++) { for (vij = V_row[i]; vij != NULL; vij = vij->r_next) { j = vij->j; vij->c_prev = NULL; vij->c_next = V_col[j]; if (vij->c_next != NULL) vij->c_next->c_prev = vij; V_col[j] = vij; } } /* free working area */ xfree(wka->R_len); xfree(wka->R_head); xfree(wka->R_prev); xfree(wka->R_next); xfree(wka->C_len); xfree(wka->C_head); xfree(wka->C_prev); xfree(wka->C_next); xfree(wka); /* return to the calling program */ return (lux->rank < n); }
void Scene::keyPressEvent(QKeyEvent *key){ dong = new QSound(":/sound/sound/dong.wav"); ka = new QSound(":/sound/sound/ka.wav"); op = new QSound(":/sound/sound/opening.wav"); if(screenMode==0){ setbg_0(); if(key->key()==Qt::Key_J || key->key()==Qt::Key_F){ dong->play(); op->play(); screenMode = 1; setbg_1(); showscene1(); } if(key->key()==Qt::Key_D || key->key()==Qt::Key_K){ ka->play(); } if(key->key()==Qt::Key_Escape){ exit(1); } } else if(screenMode==1){ if(key->key()==Qt::Key_D){ ka->play(); scene1left(); } if(key->key()==Qt::Key_K){ ka->play(); scene1right(); } if(key->key()==Qt::Key_J || key->key()==Qt::Key_F){ dong->play(); screenMode=2; unsetbg_1(); setbg_2(); } if(key->key()==Qt::Key_Escape){ screenMode=0; unsetbg_1(); setbg_0(); } } else if(screenMode==2){ if(key->key()==Qt::Key_D){ ka->play(); now_on-=1; nowOn(); } if(key->key()==Qt::Key_K){ ka->play(); now_on+=1; nowOn(); } if(key->key()==Qt::Key_J || key->key()==Qt::Key_F){ dong->play(); checked(); } if(key->key()==Qt::Key_Escape){ unsetbg_2(); screenMode=1; setbg_1(); showscene1(); } } else if(screenMode==3){ if(key->key()==Qt::Key_F){ dong->play(); eliminate(1); emit PlayLdong(); } if(key->key()==Qt::Key_J){ dong->play(); eliminate(1); emit PlayRdong(); } if(key->key()==Qt::Key_D){ ka->play(); eliminate(2); emit PlayLka(); } if(key->key()==Qt::Key_K){ ka->play(); eliminate(2); emit PlayRka(); } if(key->key()==Qt::Key_P){ p++; if(p==1){ track->pause(); timer1->stop(); timer2->stop(); AniTimer1->stop(); AniTimer3->stop(); AniTimer4->stop(); if(set30secMode==true)countdown->stop(); } else if(p==2){ track->play(); timer1->start(); timer2->start(); AniTimer1->start(); AniTimer3->start(); AniTimer4->start(); if(set30secMode==true)countdown->start(); p=0; } } if(key->key()==Qt::Key_Escape){ track->stop(); unsetbg_3(); setbg_2(); screenMode=2; } if(key->key()==Qt::Key_Equal && (VOL+5)<=100){ VOL+=5; track->setVolume(VOL); } if(key->key()==Qt::Key_Minus && (VOL-5)>=0){ VOL-=5; track->setVolume(VOL); } if(key->key()==Qt::Key_BracketRight){ timer1->start(test+=1); } if(key->key()==Qt::Key_BracketLeft){ timer1->start(test-=1); } } else if(screenMode==4){ if(key->key()==Qt::Key_J || key->key()==Qt::Key_F){ dong->play(); } if(key->key()==Qt::Key_D || key->key()==Qt::Key_K){ ka->play(); } if(key->key()==Qt::Key_Escape){ unsetbg_4(); setbg_1(); showscene1(); screenMode=1; } } }
void start(){ initscr(); srand(time(0)); init_background(0,0); refresh(); keypad(stdscr,TRUE); pthread_t keyboard; //键盘监听线程 int err = init_network(); //初始化网络模块 if(err!=0){ mvprintw(5,60,"Network model init failed!"); } start: initpanel(); //把两个panel清空 initblock(b1);initblock(b2); printpanel(PANELSTARTX,PANELSTARTY); err = pthread_create(&keyboard,NULL,keylistener,NULL); if(err !=0){ printf("can't create thread keyboard listener!"); exit(1); } //main thread make the block moving down until the gameover while(!over){ movemid(); if(caninput(b1)){ //可以放下当前块说明游戏未结束 while( canmovedown() ){ //直到不能下落位置 //继续下落 goahead(); //显示一次 printpanel(PANELSTARTX,PANELSTARTY); usleep(sleeptime); } //save temp panel to preview panel and create new block savetoprev(); printpanel(PANELSTARTX,PANELSTARTY); //停止下落后要消除 eliminate(); //把下一个块替换上来 nextblock(); } else over=true; } attrset(COLOR_PAIR(7)); mvprintw(21,37,"YOU DEAD!Try again?(y/n):"); int input; int quit = 1; while(quit){ input=getch(); //判断用户还要不要玩下去 switch(input){ case 'y': over = 0; attrset(COLOR_PAIR(0)); mvprintw(21,37," "); goto start; //重新开始 break; case 'n': endwin();quit = 0;break; default: mvprintw(21,37,"YOU DEAD!Try again?(y/n):"); } } }
void solve_system (double* m, int N, double* b, double* x) { eliminate (m, N, b); bks (m, N, b, x); }
float Environment::evolutionCycle(){ createIntermediatePopulation(); eliminate(); return bestWorm->getDistanceAfterNMoves(movementSteps); }
main(int argc, char **argv) { //declare the required data structures int N =32; /* Matrix size */ /* Matrices and vectors */ float *A= malloc(MAXN*MAXN); int i,j; //code commented. was used for testing. /* float temp[64] = {1,2,3,4,5,6,7,8, 2,3,4,1,7,4,5,6, 2,3,2,1,2,2,1,1, 4,5,4,5,5,3,4,2, 1,4,8,4,3,7,6,6, 9,7,7,3,2,8,5,4, 8,6,4,1,1,5,3,3, 8,3,2,6,4,6,9,7}; for(i=0;i<N;i++){ for(j=0;j<N;j++) { *(A+((N*i)+j))=temp[i*N+j]; //printf(" %f",*(A+((8*i)+j))); } //printf("\n"); } */ float B[MAXN];// = {5,6,7,3,5,2,9,5}; float X[MAXN];// = {0,0,0,0,0,0,0,0}; int my_rank=0; /* My process rank */ int p; /* The number of processes */ //clock time recording variables double start_time,end_time=0.0; ///////////////////MPI code starts//////////////////// //status variable used to check status of communication operation. MPI_Status status; /* Let the system do what it needs to start up MPI */ MPI_Init(&argc, &argv); /* Get my process rank */ MPI_Comm_rank(MPI_COMM_WORLD, &my_rank); /* Find out how many processes are being used */ MPI_Comm_size(MPI_COMM_WORLD, &p); if(my_rank==0) { /* Process program parameters */ N = parameters(argc, argv); /* Initialize A and B */ initialize_inputs(A, B, X,N); /* Print input matrices */ print_inputs(A, B,N); //Start clock and record the start time. start_time = MPI_Wtime(); } //broadcast the size of the matrix read by the to all processes. MPI_Bcast(&N, 1, MPI_INT, 0, MPI_COMM_WORLD); //we need all processes to wait here until all others arrive. //we need to make sure that the input matrix has been initialized //by process 0 and the marix size has been propogated to all processes. MPI_Barrier(MPI_COMM_WORLD); //declare the local variables int local_no_of_rows; //number of rows to be processesd by each process int local_matrix_size; //size of the matrix float local_norm_row[N]; //the current normaization row float local_matrix_A[N][N]; //the part of A matrix on which each process will work float local_matrix_B[N]; //the part of B matrix on which each process will work int rows_per_process[p]; //the number of rows distributed to each process float local_norm_B; //the element on which B will be normalized int displ[p]; //displacement variable int norm=0; //the index of the current normalizing row //lets begin. The loop is outermost loop of Gaussian elimination operation. for (norm = 0; norm < N - 1; norm++) { //lets scatter the data accross all processes. //This method scatters the matrix A, and broadcasts the current normalizing row, // number of rows each process will work on. scatter_data(norm, my_rank, p, A, N, &local_no_of_rows, &local_matrix_size, local_norm_row, &(local_matrix_A[0][0]), &rows_per_process[0]); //lets calculate the send counts and displacement vector for scatter of B matrix. if(my_rank==0) { //printf(" %d", *(rows_per_process)); *(displ)=0; for(j=1;j<p;j++) { *(displ+j) = rows_per_process[j-1]+ *(displ+j-1); //printf(" %d", *(rows_per_process+j)); } } //This method call scatter the matrix B. Different processes may have different //number of elements to work on, when the size of matrix is not completely divisible //by number of processes. Hence we have used MPI_Scatterv(), instead of MPI_Scatter MPI_Scatterv(B+norm+1, rows_per_process, displ, MPI_FLOAT,local_matrix_B,local_no_of_rows, MPI_FLOAT, 0, MPI_COMM_WORLD); //lets broadcast the element against which matrix B will be normalized. local_norm_B = B[norm]; MPI_Bcast(&local_norm_B, 1, MPI_FLOAT, 0, MPI_COMM_WORLD); //each process performs the following elimination operation on their //share of the matrix A and B. eliminate(local_matrix_size, local_no_of_rows, &local_norm_row[0], &(local_matrix_A[0][0]), norm, &(local_matrix_B[0]), local_norm_B); //we need to calculate the counts and displacement for the Gather operation //of the processed matrix A, after each iteration. int counts_for_gather[p]; int displacements_for_gather[p]; if(my_rank==0) { *(displacements_for_gather)=0; counts_for_gather[0] = rows_per_process[0]*local_matrix_size; for(j=1;j<p;j++) { counts_for_gather[j] = rows_per_process[j]*local_matrix_size; *(displacements_for_gather+j) = counts_for_gather[j-1]+ *(displacements_for_gather+j-1); } } //here we gather the processed matrix A from all processes and store it locally MPI_Gatherv(local_matrix_A, local_no_of_rows*local_matrix_size, MPI_FLOAT, A+(N*(norm+1)), counts_for_gather, displacements_for_gather, MPI_FLOAT, 0, MPI_COMM_WORLD); //similarly we gather the processed matrix B. MPI_Gatherv(local_matrix_B, local_no_of_rows, MPI_FLOAT, B+norm+1, rows_per_process, displ, MPI_FLOAT, 0, MPI_COMM_WORLD); } //We need to wait for al processes to complete before we go ahead with //back subsitution. MPI_Barrier(MPI_COMM_WORLD); //perform the back substitution operation only by process 0. int row,col; if(my_rank==0){ /* Back substitution */ for (row = N - 1; row >= 0; row--) { X[row] = B[row]; for (col = N-1; col > row; col--) { X[row] -= *(A+(N*row)+col) * X[col]; } X[row] /= *(A+(N*row)+col); } //Stop clock as operation is finished. end_time = MPI_Wtime(); //display X in matrix size is small. if (N < 100) { printf("\nX = ["); for (row = 0; row < N; row++) { printf("%5.2f%s", X[row], (row < N-1) ? "; " : "]\n"); } } //print the execution time for performance analysis purpose. printf("\n\nThe total execution time as recorded on process 0 = %f seconds!!\n!",end_time-start_time); } MPI_Finalize(); }