コード例 #1
0
ファイル: main.c プロジェクト: yuga-92/MergeLogs
void sorting(struct list items[],long l,long u)
{
    //i`m not perfectly familiar with implementing of quick sorting algorithm, but i know that it performs quick
    //so i decided to do some google search about how to implement it correctly
    long j;
    if(l<u)
    {
        j=partArr(items,l,u);
        sorting(items,l,j-1);
        sorting(items,j+1,u);
    }
}
コード例 #2
0
ファイル: listmodel.cpp プロジェクト: Pandahisham/outliner
void ListModel::sort(ListItem* parent, App::SortMode mode)
{
    int count = parent->childCount();

    QVector<QPair<ListItem*, int>> sorting(count);
    for (int i = 0; i < count; ++i) {
        sorting[i].first = parent->child(i);
        sorting[i].second = i;
    }

    if (!parent->sort(mode))
        return;

    QModelIndexList oldIndexes;
    QModelIndexList newIndexes;
    for (QModelIndex idx : persistentIndexList()) {
        ListItem* item = itemFromIndex(idx);
        if (!item)
            continue;
        if (idx.row() != item->row()) {
            oldIndexes.append(idx);
            newIndexes.append(indexFromItem(item));
        }
    }

    qDebug() << __FUNCTION__ << oldIndexes;
    qDebug() << __FUNCTION__ << newIndexes;

    changePersistentIndexList(oldIndexes, newIndexes);
    emit layoutChanged();
}
コード例 #3
0
inline
void
GenEigsSolver<eT, SelectionRule, OpType>::sort_ritzpair()
  {
  arma_extra_debug_sigprint();
  
  // SortEigenvalue< std::complex<eT>, EigsSelect::LARGEST_MAGN > sorting(ritz_val.memptr(), nev);
  
  // sort Ritz values according to SelectionRule, to be consistent with ARPACK
  SortEigenvalue< std::complex<eT>, SelectionRule > sorting(ritz_val.memptr(), nev);
  
  std::vector<uword> ind = sorting.index();
  
  Col< std::complex<eT> > new_ritz_val(ncv);
  Mat< std::complex<eT> > new_ritz_vec(ncv, nev);
  std::vector<bool>       new_ritz_conv(nev);
  
  for(uword i = 0; i < nev; i++)
    {
    new_ritz_val(i) = ritz_val(ind[i]);
    new_ritz_vec.col(i) = ritz_vec.col(ind[i]);
    new_ritz_conv[i] = ritz_conv[ind[i]];
    }
  
  ritz_val.swap(new_ritz_val);
  ritz_vec.swap(new_ritz_vec);
  ritz_conv.swap(new_ritz_conv);
  }
コード例 #4
0
inline
void
GenEigsSolver<eT, SelectionRule, OpType>::retrieve_ritzpair()
  {
  arma_extra_debug_sigprint();
  
  UpperHessenbergEigen<eT> decomp(fac_H);
  
  Col< std::complex<eT> > evals = decomp.eigenvalues();
  Mat< std::complex<eT> > evecs = decomp.eigenvectors();
  
  SortEigenvalue< std::complex<eT>, SelectionRule > sorting(evals.memptr(), evals.n_elem);
  std::vector<uword> ind = sorting.index();
  
  // Copy the ritz values and vectors to ritz_val and ritz_vec, respectively
  for(uword i = 0; i < ncv; i++)
    {
    ritz_val(i) = evals(ind[i]);
    ritz_est(i) = evecs(ncv - 1, ind[i]);
    }
  for(uword i = 0; i < nev; i++)
    {
    ritz_vec.col(i) = evecs.col(ind[i]);
    }
  }
コード例 #5
0
ファイル: main.c プロジェクト: bsuir250502/lab1_Savich
int main( int argc, char *argv[])
{
    if(argc>1)
    {
        if(!strcmp(argv[1],"-h"))
            info();
    }
    int records = 0, i;
    char *string;
    struct staff *person;

    do {
        string = (char *) calloc(30, sizeof(char));
        person = (struct staff *) calloc(25, sizeof(struct staff));
    }
    while (!person && !string);
    puts("ATTENCION: maximum length of record cannot exceed 29 symbols");
    while (records < 25) {
        input(person, string, records);
        records++;
        puts("enter stop to quit");
        fgets(string, 5, stdin);
        if (strcmp(string, "stop") == 0)
            break;
    }
    if (records == 24)
        puts("you can enter only 25 persons");

    else
        person = (struct staff *) realloc(person, records);
    sorting(person, records);
    display(person, records);
    return 0;
}
コード例 #6
0
void TableEditor::columnClicked(int col)
{
    if(!sorting()) return;
    //if(col==lastSortCol) asc=!asc; else lastSortCol=col,asc=TRUE;
    sortColumn(col,1,1);
	emit sorted();
}
コード例 #7
0
ファイル: Search.cpp プロジェクト: JeMaCheHi/deling
bool Search::findPrevScript()
{
	int sav;
	bool found = false;
	FieldArchive::Sorting sort = sorting();

	if(typeScriptChoice->currentIndex() == 0) {
		found = fieldArchive->searchScriptTextReverse(regexp(), fieldID, groupID, methodID, opcodeID, sort);
	}
	else if(typeScriptChoice->currentIndex() == 1) {
		found = fieldArchive->searchScriptReverse(1, searchOpcode->currentIndex(), fieldID, groupID, methodID, opcodeID, sort);
	}
	else if(typeScriptChoice->currentIndex() == 2) {
		found = fieldArchive->searchScriptReverse(2, (popScriptVar->isChecked() << 31) | (selectScriptVar->currentIndex() & 0x7FFFFFFF), fieldID, groupID, methodID, opcodeID, sort);
	}
	else if(typeScriptChoice->currentIndex() == 3) {
		found = fieldArchive->searchScriptReverse(3, selectScriptGroup->value() | (selectScriptLabel->value() << 16), fieldID, groupID, methodID, opcodeID, sort);
	}

	if(found)
	{
		sav = opcodeID;
		emit foundOpcode(fieldID, groupID, methodID, opcodeID);
		// "found" signal may change 'opcodeID' value
		opcodeID = sav - 1;
		return true;
	}

	fieldID = groupID = methodID = opcodeID = -1;

	return false;
}
コード例 #8
0
ファイル: qsort.cpp プロジェクト: AidaKadyrova/homeworks2
void QSort::sorting(int array[], int start, int end)
{
    int i = start;
    int j = end;
    int x = (start + end) / 2;
    do
    {
        while (array[i] < array[x])
            i++;
        while (array[x] < array[j])
            j--;
        if (i <= j)
            swap(array[i++], array[j--]);
    }
    while (i <= j);
        sorting(array, start, j);
        sorting(array, i, end);
}
コード例 #9
0
int Q3Table::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
    _id = Q3ScrollView::qt_metacall(_c, _id, _a);
    if (_id < 0)
        return _id;
    if (_c == QMetaObject::InvokeMetaMethod) {
        if (_id < 58)
            qt_static_metacall(this, _c, _id, _a);
        _id -= 58;
    }
#ifndef QT_NO_PROPERTIES
      else if (_c == QMetaObject::ReadProperty) {
        void *_v = _a[0];
        switch (_id) {
        case 0: *reinterpret_cast< int*>(_v) = numRows(); break;
        case 1: *reinterpret_cast< int*>(_v) = numCols(); break;
        case 2: *reinterpret_cast< bool*>(_v) = showGrid(); break;
        case 3: *reinterpret_cast< bool*>(_v) = rowMovingEnabled(); break;
        case 4: *reinterpret_cast< bool*>(_v) = columnMovingEnabled(); break;
        case 5: *reinterpret_cast< bool*>(_v) = isReadOnly(); break;
        case 6: *reinterpret_cast< bool*>(_v) = sorting(); break;
        case 7: *reinterpret_cast< SelectionMode*>(_v) = selectionMode(); break;
        case 8: *reinterpret_cast< FocusStyle*>(_v) = focusStyle(); break;
        case 9: *reinterpret_cast< int*>(_v) = numSelections(); break;
        }
        _id -= 10;
    } else if (_c == QMetaObject::WriteProperty) {
        void *_v = _a[0];
        switch (_id) {
        case 0: setNumRows(*reinterpret_cast< int*>(_v)); break;
        case 1: setNumCols(*reinterpret_cast< int*>(_v)); break;
        case 2: setShowGrid(*reinterpret_cast< bool*>(_v)); break;
        case 3: setRowMovingEnabled(*reinterpret_cast< bool*>(_v)); break;
        case 4: setColumnMovingEnabled(*reinterpret_cast< bool*>(_v)); break;
        case 5: setReadOnly(*reinterpret_cast< bool*>(_v)); break;
        case 6: setSorting(*reinterpret_cast< bool*>(_v)); break;
        case 7: setSelectionMode(*reinterpret_cast< SelectionMode*>(_v)); break;
        case 8: setFocusStyle(*reinterpret_cast< FocusStyle*>(_v)); break;
        }
        _id -= 10;
    } else if (_c == QMetaObject::ResetProperty) {
        _id -= 10;
    } else if (_c == QMetaObject::QueryPropertyDesignable) {
        _id -= 10;
    } else if (_c == QMetaObject::QueryPropertyScriptable) {
        _id -= 10;
    } else if (_c == QMetaObject::QueryPropertyStored) {
        _id -= 10;
    } else if (_c == QMetaObject::QueryPropertyEditable) {
        _id -= 10;
    } else if (_c == QMetaObject::QueryPropertyUser) {
        _id -= 10;
    }
#endif // QT_NO_PROPERTIES
    return _id;
}
コード例 #10
0
ファイル: prac3-9.c プロジェクト: Sakuya9461/2015_Probsolv
int main()
{
	//for security reason..
	char* string1 = (char*)malloc(sizeof(char)*MAX);
	char* string2 = (char*)malloc(sizeof(char)*MAX);

	printf("First String  > ");
	scanf("%4095s",string1);	
	printf("Second String > ");
	scanf("%4095s",string2);

	sorting(string1);
	sorting(string2);

	if(strcmp((const char*)string1,(const char*)string2))
		printf("It is not anagram.\n");
	else
		printf("Two strings are anagram.\n");

}
コード例 #11
0
ファイル: card.c プロジェクト: choiking10/gostopC
void cardShuffleStart(PLAYER player[],PCARD *board,PCARD* dummy)	
//initialize card deck and give card from deck to player and board
{
	int i,j;
	
	
	initializeDummy(dummy);		

	for( i = 0 ; i < 3 ; i++ )						
		for( j = 0 ; j < 7 ; j++ )
		{
			giveCard(dummy,&(player[i].playerHead),0);
			sorting(&(player[i].playerHead));
		}

	for( i = 0 ; i < 6 ; i++ )						
	{
		giveCard(dummy,board,0);
		sorting(board);
	}
	
	return;
}
コード例 #12
0
void main ( )

   {
	 void create ();
	 void traverse ();
	 void sorting ( );
	 clrscr ( );
	 create ( );
	 traverse( );
	 sorting ( );
	 printf ("\n After SORTING");
	 traverse( );
     getch ( );
    }
コード例 #13
0
void KFileInfoContents::setSorting(QDir::SortSpec new_sort)
{
    QDir::SortSpec old_sort = 
	static_cast<QDir::SortSpec>(sorting() & QDir::SortByMask);
    QDir::SortSpec sortflags = 
	static_cast<QDir::SortSpec>(sorting() & (~QDir::SortByMask));
    
    if (mySortMode == Switching) {
	if (new_sort == old_sort)
	    reversed = !reversed;
	else
	    reversed = false;
    } else 
	reversed = (mySortMode == Decreasing);
    
    mySorting = static_cast<QDir::SortSpec>(new_sort | sortflags);
   
    if (count() <= 1) // nothing to do in this case
	return;

    if ( mySorting & QDir::DirsFirst )
        keepDirsFirst = true;
    else
        keepDirsFirst = false;

    setAutoUpdate(false);
    clearView();

    debugC("qsort %ld", time(0));
    QuickSort(sortedArray, 0, sorted_length - 1);
    debugC("qsort %ld", time(0));
    for (uint i = 0; i < sorted_length; i++)
	insertItem(sortedArray[i], -1);
    debugC("qsort %ld", time(0));
    setAutoUpdate(true);
    repaint(true);
}
コード例 #14
0
ファイル: sort.cpp プロジェクト: ZiminGrigory/University_HW
void Sort::sorting(int numberOfColumns, int **array)
{
    int i = 0;
    int j = numberOfColumns;
    int basicAl = array[numberOfColumns / 2][0];
    do
    {
        while (array[i][0] < basicAl)
            i = i + 1;
        while (array[j][0] > basicAl)
            j = j - 1;
        if (i <= j)
        {
            swap(array[i], array[j]);
            i = i + 1;
            j = j - 1;
        }
    }
   while (i <= j);
   if (j > 0)
        sorting(j, array);
   if (numberOfColumns > i)
        sorting(numberOfColumns - i, array + i);
}
コード例 #15
0
int main()
{
    int a , b ,i,j,k;
    scanf("%d",&a);
    for(i=0;i<a;i++)
    {
        scanf("%d",&b);
        int res[b];
        for(j=0;j<b;j++)
            scanf("%d",&res[j]);
        sorting(res,b);
        printf("Case %d: %d\n",i+1,res[b-1]);
    }
    return 0;
}
コード例 #16
0
int main()
{
    int a[3] , i , j , t ;
    scanf("%d",&t);
    for(i=0 ; i<t ; i++)
    {
        for(j=0 ; j<3 ; j++)
            scanf("%d",&a[j]);
        sorting(a,3);
        if((a[0] + a[1]) > a[2])
            printf("OK\n");
        else
            printf("Wrong!!\n");
    }
    return 0;
}
コード例 #17
0
ファイル: main.c プロジェクト: yuga-92/MergeLogs
int main(int argc, const char * argv[])
{
    long listSize;
    listSize = numberOfEntries(); //calculates size of list array
    /*in future we can implement some functions that will add new elements into list array
     like in ArrayList in Java, so then we do not need to calculate the size of the array :)*/
    struct list items[listSize];
    openFileAndAddToList(items, listSize);
    printf("Merging...\n");
    // sorting(items, listSize);
    sorting(items,0 , listSize-1);
    writeToFile(items,listSize);
    printf("Done!\n");
    printf("___________________________________________________________\n");
    printf("All data written in \"all.log\" file at program root folder.\n");
    printf("___________________________________________________________\n");
    return 0;
}
コード例 #18
0
ファイル: Search.cpp プロジェクト: JeMaCheHi/deling
bool Search::findNextScript()
{
	int sav;
	bool found = false;
	FieldArchive::Sorting sort = sorting();

	if(typeScriptChoice->currentIndex() == 0) {
		found = fieldArchive->searchScriptText(regexp(), fieldID, groupID, methodID, opcodeID, sort);
	}
	else if(typeScriptChoice->currentIndex() == 1) {
		found = fieldArchive->searchScript(1, searchOpcode->currentIndex() | (searchOpcodeValue->value() << 16), fieldID, groupID, methodID, opcodeID, sort);
	}
	else if(typeScriptChoice->currentIndex() == 2) {
		found = fieldArchive->searchScript(2, (popScriptVar->isChecked() << 31) | (selectScriptVar->currentIndex() & 0x7FFFFFFF), fieldID, groupID, methodID, opcodeID, sort);
	}
	else if(typeScriptChoice->currentIndex() == 3) {
		Field *field = fieldArchive->getField(fieldID);
		if(field != NULL && field->hasJsmFile()) {
			found = field->getJsmFile()->search(3, (selectScriptGroup->value() & 0xFFFF) | ((selectScriptLabel->value() & 0xFFFF) << 16), groupID, methodID, opcodeID);
		}
		if(!found) {
			groupID = methodID = opcodeID = 0;
			return false;
		}
	}

	if(found)
	{
		sav = opcodeID;
		emit foundOpcode(fieldID, groupID, methodID, opcodeID);
		// "found" signal may change 'opcodeID' value
		opcodeID = sav + 1;
		return true;
	}

	groupID = methodID = opcodeID = 0;
	fieldID = -1;

	return false;
}
コード例 #19
0
ファイル: TMISC.CPP プロジェクト: cdaffara/symbiandump-os2
static void MainL()
	{
	TheTest.Start(_L(" @SYMTestCaseID:SYSLIB-STDLIB-LEGACY-TMISC-0001 TMISC tests "));

	random_numbers();
	sorting();
	searching();
	setjmp_longjmp();
	casecmp();
	sscanf_test();

	int argsc = 5;
	char *argsv[]=
		{
		"tmisc", "This", "is", "a", "test.",
		};
	arguments(argsc, argsv);

	strtod_test();
	va_args_test();
	sprintf_test();
	}
コード例 #20
0
ファイル: Search.cpp プロジェクト: JeMaCheHi/deling
bool Search::findPrevText()
{
	int index, size;
	FieldArchive::Sorting sort = sorting();

	--from;

	if(fieldArchive->searchTextReverse(regexp(), fieldID, textID, from, index, size, sort))
	{
//		qDebug() << "from=" << from << "(Search::findPrevText::from=index)";
		emit foundText(fieldID, textID, index, size);
		return true;
	}

	fieldID = textID = 2147483647;
	from = 0;
//	qDebug() << "FieldID=" << fieldID << "(Search::findPrevText::0)";
//	qDebug() << "textID=" << textID << "(Search::findPrevText::0)";
//	qDebug() << "from=" << from << "(Search::findPrevText::0)";

	return false;
}
コード例 #21
0
ファイル: searchtrie.cpp プロジェクト: climberpi/Lexicons
// @brief: search words, results store at results[tot]
int searchTrie::searchWords(char s[])
{
    int i;
    int num57,num58;
    strcpy(Str,s);
    clearRep(Str);
    // eliminate duplicate * notations
    if(convert(Str)) {
        tot=0;
        return 0;
    }
    // mapping s to the number series, return 1 if the word is illegal
    StrLen=strlen(Str);
    for(i=num57=num58=0;i<StrLen;i++) {
        if(Str[i]==57) num57++;
        if(Str[i]==58) num58++;
    }
    // note the number of both ? and *
    if(num57==0 && num58==0) {
        Str[StrLen]=58;
        Str[StrLen+1]='\0';
        StrLen++;
    }
    tot=0;
    dfs(0,0);
    // search any wildcard for possible target string
    if(tot==0 && num57==0 && num58==0) {
        Str[StrLen-1]='\0';
        StrLen--;
        dfs_vague(0,0,Max_edit);
    // vague searching
    }
    sorting();
    // eliminate target words and sorting it
    if(tot>M_top)
        tot=M_top;
    return 0;
}
コード例 #22
0
ファイル: method_list.cpp プロジェクト: stereo069/queue_list
void sorting_all(list **start)				// sorting all list ascending
{
	int n = 1;


	if (!*start)
	{
		return;
	}
	else
	{
		if (!(*start)->next_adres)
		{
			return;
		}
	}

	while (size_list(*start) - n)
	{
		sorting(start);
		n++;
	}
}
コード例 #23
0
ファイル: Search.cpp プロジェクト: JeMaCheHi/deling
bool Search::findNextText()
{
	int size;
	FieldArchive::Sorting sort = sorting();

	++from;

	if(fieldArchive->searchText(regexp(), fieldID, textID, from, size, sort))
	{
//		qDebug() << "from=" << from << "(MsdFile::findNextText::from=index)";
		emit foundText(fieldID, textID, from, size);
		// "found" signal may change 'from' value
//		qDebug() << "from=" << from << "(MsdFile::findNextText::from++)";
		return true;
	}

	textID = from = fieldID = -1;
//	qDebug() << "FieldID=" << fieldID << "(Search::findNextText::0)";
//	qDebug() << "textID=" << textID << "(Search::findNextText::0)";
//	qDebug() << "from=" << from << "(MsdFile::findNextText::0)";

	return false;
}
コード例 #24
0
ファイル: main.cpp プロジェクト: Feliasfogg/HomeWorks
int main()
{
    const int size =10;
    int arrayM[size];
    int arrayN[size];
    int arrayMN[2*size];
    generator(arrayM,size);
    generator1(arrayN,size);
    /* используются два генератора не спроста, т.к вначале была одна функция.
    Видимо передача и заполнение обоих массивов проходит в течение одной миллисекунды и
    потому, даже передавая оба массива одной функции, на выходе получается, что точка отсчета одна и та же, следовательно два абсолютно одинаковых массива.
    Чтобы этого избежать используется вторая функция в качестве точки отсчета там не srand, а srand48*/
    cout<<"массив M\n";
    display(arrayM, size);
    cout<<"массив N\n";
    display(arrayN, size);
    rewrite(arrayM, arrayN, arrayMN, size);
    cout<<"Общий массив\n";
    display(arrayMN, 2*size);
    sorting(arrayMN, 2*size);
    cout<<"упорядоченный массив\n";
    display(arrayMN, 2*size);
    return 0;
}
コード例 #25
0
void KFilePreview::setFileView( KFileView *view )
{
    Q_ASSERT( view );

    // Why copy the actions? --ellis, 13 Jan 02.
    //if ( left ) { // remove any previous actions
    //    for ( uint i = 0; i < left->actionCollection()->count(); i++ )
    //        actionCollection()->take( left->actionCollection()->action( i ));
    //}

    delete left;
    view->widget()->reparent( this, QPoint(0,0) );
    view->KFileView::setViewMode(All);
    view->setParentView(this);
    view->setSorting( sorting() );
    left = view;

    connect( left->signaler(), SIGNAL( fileHighlighted(const KFileItem*) ),
             SLOT( slotHighlighted( const KFileItem * )));

    // Why copy the actions? --ellis, 13 Jan 02.
    //for ( uint i = 0; i < view->actionCollection()->count(); i++ )
    //    actionCollection()->insert( view->actionCollection()->action( i ));
}
コード例 #26
0
void FastSimpleHierarchyLayout::doCall(const HierarchyLevels &levels, GraphCopyAttributes &AGC)
{
	const Hierarchy &H  = levels.hierarchy();
	const GraphCopy &GC = H;

	node v;
	NodeArray<node> align(GC);
	NodeArray<node> root(GC);

#ifdef DEBUG_OUTPUT
	for(int i = 0; i <= levels.high(); ++i) {
		cout << "level " << i << ": ";
		const Level &L = levels[i];
		for(int j = 0; j <= L.high(); ++j)
			cout << L[j] << " ";
		cout << endl;
	}
#endif

	if (m_balanced) {
		// the x positions; x = -infinity <=> x is undefined
		NodeArray<double> x[4];
		NodeArray<double> blockWidth[4];
		NodeArray<node> root[4];
		double width[4];
		double min[4];
		double max[4];
		int minWidthLayout = 0;

		// initializing
		for (int i = 0; i < 4; i++) {
			min[i] =  numeric_limits<double>::max();
			max[i] = -numeric_limits<double>::max();
		}

		// calc the layout for down/up and leftToRight/rightToLeft
		for (int downward = 0; downward <= 1; downward++) {
			NodeArray<NodeArray<bool> > type1Conflicts(GC);
			markType1Conflicts(levels, downward == 0, type1Conflicts);
			for (int leftToRight = 0; leftToRight <= 1; leftToRight++) {
				int k = 2 * downward + leftToRight;
				root[k].init(GC);
				verticalAlignment(levels, root[k], align, type1Conflicts, downward == 0, leftToRight == 0);
				computeBlockWidths(GC, AGC, root[k], blockWidth[k]);
				horizontalCompactation(align, levels, root[k], blockWidth[k], x[k], leftToRight == 0, downward == 0);
			}
		}

		/*
		* - calc min/max x coordinate for each layout
		* - calc x-width for each layout
		* - find the layout with the minimal width
		*/
		for (int i = 0; i < 4; i++) {
			forall_nodes(v, GC) {
				double bw = 0.5 * blockWidth[i][root[i][v]];
				double xp = x[i][v] - bw;
				if (min[i] > xp) {
					min[i] = xp;
				}
				xp = x[i][v] + bw;
				if (max[i] < xp) {
					max[i] = xp;
				}
			}
			width[i] = max[i] - min[i];
			if (width[minWidthLayout] > width[i]) {
				minWidthLayout = i;
			}
		}

		/*
		* shift the layout so that they align with the minimum width layout
		* - leftToRight: align minimum coordinate
		* - rightToLeft: align maximum coordinate
		*/
		double shift[4];
		for (int i = 0; i < 4; i++) {
			if (i % 2 == 0) {
				// for leftToRight layouts
				shift[i] = min[minWidthLayout] - min[i];
			} else {
				// for rightToLeft layouts
				shift[i] = max[minWidthLayout] - max[i];
			}
		}

		/*
		* shift the layouts and use the
		* median average coordinate for each node
		*/
		Array<double> sorting(4);
		forall_nodes(v, GC) {
			for (int i = 0; i < 4; i++) {
				sorting[i] = x[i][v] + shift[i];
			}
			sorting.quicksort();
			AGC.x(v) = 0.5 * (sorting[1] + sorting[2]);
		}

	} else {
コード例 #27
0
ファイル: glpapi17.c プロジェクト: emersonxsu/glpk
double glp_cpp(glp_graph *G, int v_t, int v_es, int v_ls)
{     glp_vertex *v;
      glp_arc *a;
      int i, j, k, nv, *list;
      double temp, total, *t, *es, *ls;
      if (v_t >= 0 && v_t > G->v_size - (int)sizeof(double))
         xerror("glp_cpp: v_t = %d; invalid offset\n", v_t);
      if (v_es >= 0 && v_es > G->v_size - (int)sizeof(double))
         xerror("glp_cpp: v_es = %d; invalid offset\n", v_es);
      if (v_ls >= 0 && v_ls > G->v_size - (int)sizeof(double))
         xerror("glp_cpp: v_ls = %d; invalid offset\n", v_ls);
      nv = G->nv;
      if (nv == 0)
      {  total = 0.0;
         goto done;
      }
      /* allocate working arrays */
      t = xcalloc(1+nv, sizeof(double));
      es = xcalloc(1+nv, sizeof(double));
      ls = xcalloc(1+nv, sizeof(double));
      list = xcalloc(1+nv, sizeof(int));
      /* retrieve job times */
      for (i = 1; i <= nv; i++)
      {  v = G->v[i];
         if (v_t >= 0)
         {  memcpy(&t[i], (char *)v->data + v_t, sizeof(double));
            if (t[i] < 0.0)
               xerror("glp_cpp: t[%d] = %g; invalid time\n", i, t[i]);
         }
         else
            t[i] = 1.0;
      }
      /* perform topological sorting to determine the list of nodes
         (jobs) such that if list[k] = i and list[kk] = j and there
         exists arc (i->j), then k < kk */
      sorting(G, list);
      /* FORWARD PASS */
      /* determine earliest start times */
      for (k = 1; k <= nv; k++)
      {  j = list[k];
         es[j] = 0.0;
         for (a = G->v[j]->in; a != NULL; a = a->h_next)
         {  i = a->tail->i;
            /* there exists arc (i->j) in the project network */
            temp = es[i] + t[i];
            if (es[j] < temp) es[j] = temp;
         }
      }
      /* determine the minimal project duration */
      total = 0.0;
      for (i = 1; i <= nv; i++)
      {  temp = es[i] + t[i];
         if (total < temp) total = temp;
      }
      /* BACKWARD PASS */
      /* determine latest start times */
      for (k = nv; k >= 1; k--)
      {  i = list[k];
         ls[i] = total - t[i];
         for (a = G->v[i]->out; a != NULL; a = a->t_next)
         {  j = a->head->i;
            /* there exists arc (i->j) in the project network */
            temp = ls[j] - t[i];
            if (ls[i] > temp) ls[i] = temp;
         }
         /* avoid possible round-off errors */
         if (ls[i] < es[i]) ls[i] = es[i];
      }
      /* store results, if necessary */
      if (v_es >= 0)
      {  for (i = 1; i <= nv; i++)
         {  v = G->v[i];
            memcpy((char *)v->data + v_es, &es[i], sizeof(double));
         }
      }
      if (v_ls >= 0)
      {  for (i = 1; i <= nv; i++)
         {  v = G->v[i];
            memcpy((char *)v->data + v_ls, &ls[i], sizeof(double));
         }
      }
      /* free working arrays */
      xfree(t);
      xfree(es);
      xfree(ls);
      xfree(list);
done: return total;
}
コード例 #28
0
ファイル: htc_util.c プロジェクト: Bigtime1267/HTC-C525c
void htc_kernel_top(void)
{
	struct task_struct *p;
	int top_loading[NUM_BUSY_THREAD_CHECK], i;
	unsigned long user_time, system_time, io_time;
	unsigned long irq_time, idle_time, delta_time;
	ulong flags;
	struct task_cputime cputime;
	int dump_top_stack = 0;

	if (task_ptr_array == NULL ||
			curr_proc_delta == NULL ||
			prev_proc_stat == NULL)
		return;

	spin_lock_irqsave(&lock, flags);
	get_all_cpu_stat(&new_cpu_stat);

	/* calculate the cpu time of each process */
	for_each_process(p) {
		thread_group_cputime(p, &cputime);

		if (p->pid < MAX_PID) {
			curr_proc_delta[p->pid] =
				(cputime.utime + cputime.stime)
				- (prev_proc_stat[p->pid]);
			task_ptr_array[p->pid] = p;
		}
	}

	/* sorting to get the top cpu consumers */
	sorting(curr_proc_delta, top_loading);

	/* calculate the total delta time */
	user_time = (unsigned long)((new_cpu_stat.user + new_cpu_stat.nice)
			- (old_cpu_stat.user + old_cpu_stat.nice));
	system_time = (unsigned long)(new_cpu_stat.system - old_cpu_stat.system);
	io_time = (unsigned long)(new_cpu_stat.iowait - old_cpu_stat.iowait);
	irq_time = (unsigned long)((new_cpu_stat.irq + new_cpu_stat.softirq)
			- (old_cpu_stat.irq + old_cpu_stat.softirq));
	idle_time = (unsigned long)
	((new_cpu_stat.idle + new_cpu_stat.steal + new_cpu_stat.guest)
	 - (old_cpu_stat.idle + old_cpu_stat.steal + old_cpu_stat.guest));
	delta_time = user_time + system_time + io_time + irq_time + idle_time;

	/*
	 * Check if we need to dump the call stack of top CPU consumers
	 * If CPU usage keeps 100% for 90 secs
	 */
	if ((full_loading_counter >= 9) && (full_loading_counter % 3 == 0))
		 dump_top_stack = 1;

	/* print most time consuming processes */
	printk("[K] CPU Usage\t\tPID\t\tName\n");
	for (i = 0 ; i < NUM_BUSY_THREAD_CHECK ; i++) {
		printk("[K] %lu%%\t\t%d\t\t%s\t\t\t%d\n",
				curr_proc_delta[top_loading[i]] * 100 / delta_time,
				top_loading[i],
				task_ptr_array[top_loading[i]]->comm,
				curr_proc_delta[top_loading[i]]);
	}

	/* check if dump busy thread stack */
	if (dump_top_stack) {
	   struct task_struct *t;
	   for (i = 0 ; i < NUM_BUSY_THREAD_CHECK ; i++) {
		if (task_ptr_array[top_loading[i]] != NULL && task_ptr_array[top_loading[i]]->stime > 0) {
			t = task_ptr_array[top_loading[i]];
			/* dump all the thread stack of this process */
			do {
				printk("\n[K] ###pid:%d name:%s state:%lu ppid:%d stime:%lu utime:%lu\n",
				t->pid, t->comm, t->state, t->real_parent->pid, t->stime, t->utime);
				show_stack(t, t->stack);
				t = next_thread(t);
			} while (t != task_ptr_array[top_loading[i]]);
		}
	   }
	}
	/* save old values */
	for_each_process(p) {
		if (p->pid < MAX_PID) {
			thread_group_cputime(p, &cputime);
			prev_proc_stat[p->pid] = cputime.stime + cputime.utime;
		}
	}

	old_cpu_stat = new_cpu_stat;

	memset(curr_proc_delta, 0, sizeof(int) * MAX_PID);
	memset(task_ptr_array, 0, sizeof(int) * MAX_PID);

	spin_unlock_irqrestore(&lock, flags);

}
コード例 #29
0
ファイル: prog4.c プロジェクト: vteori/CSED101
//1번 선택 함수
void menu1(int *indicator1/*1번 기능 실행 여부*/)
{
	FILE *file; //파일 포인터
	int choice/* 메뉴 선택 변수*/, i, j, n/*루프에 쓰이는 변수*/;
	int line[32];//information.txt에서 읽을 data의 line
	char fileName[20]/*파일 이름 변수*/,  mark = 'A'/*파일명에서 다른 부분*/, group[] = "_Group.txt"/*파일명에서 같은 부분*/;
	char data[4][20]/*나라이름*/, temp[20]/*임시 저장*/;
	
	while(1){
		//메뉴
		printf("\n1. 기존의 조편성	2. 새로운 조편성\n");
		printf("작업을 선택하세요 : ");
		//메뉴선택
		fflush(stdin);
		choice = 0;
		scanf("%d", &choice);
		//파일 열기(읽기)
		file = fopen("information.txt", "r");
		//1번을 선택하였을 경우
		if(choice == 1){	
			while(1){
				//data 읽기
				for(i = 0 ; i < 4 ; i++){
					fscanf(file, "%s", data[i]);
					//필요없는 데이터 skip
					for(j = 0 ; j < 5 ; j++){
						fscanf(file, "%s", temp);
					}
				}
				//파일 이름 생성
				fileName[0] = mark;
				fileName[1] = '\0';
				strcat(fileName, group);
				//sorting함수 호출
				sorting(data);
				//data저장함수 호출
				saving(fileName, data);
			
				mark++; //파일 이름 바꾸기
				//파일이름 앞이 H가 되었을때
				if(mark > 72){
					fclose(file);
					break;
				}
			}
		}
		//2번을 선택하였을 경우
		else if(choice == 2){
			//파일에서 몇번째줄 data를 읽을것인가를 임의로 생성
			n = 0;
			do{
				line[n] = rand() % 32 + 1;
				i = 0;
				while(i < n){
					if(line[i] == line[n]){
						line[n] = rand() % 32 + 1;
						i = -1;
					}
					i++;
				}
				n++;
			}while(n < 32);
			
			n = 0;
			while(1){
				//원하는 data 읽기
				for(i = 0 ; i < line[n] ; i++){
					fscanf(file, "%s", data[0]);
					for(j = 0 ; j < 5; j++){
						fscanf(file, "%s", temp);
					}
				}
				rewind(file); //파일의 처음으로 돌아가기
				for(i = 0 ; i < line[n+1] ; i++){
					fscanf(file, "%s", data[1]);
					for(j = 0 ; j < 5 ; j++){
						fscanf(file, "%s", temp);
					}
				}
				rewind(file);
				for(i = 0 ; i < line[n+2] ; i++){
					fscanf(file, "%s", data[2]);
					for(j = 0 ; j < 5 ; j++){
						fscanf(file, "%s", temp);
					}
				}
				rewind(file);
				for(i = 0 ; i < line[n+3] ; i++){
					fscanf(file, "%s", data[3]);
					for(j = 0 ; j < 5 ; j++){
						fscanf(file, "%s", temp);
					}
				}
				rewind(file);
				//파일 이름 생성
				fileName[0] = mark;
				fileName[1] = '\0';
				strcat(fileName, group);
				//sorting함수 호출
				sorting(data);
				//data저장 함수 호출
				saving(fileName, data);
				
				n += 4; //읽어 들일 줄수 변화
				mark++; //파일 이름 바꾸기
				//파일 이름 앞이 H일 경우
				if(mark > 72){
					fclose(file);
					break;
				}
			}
		}
		//오류 처리
		else{
			printf("\n잘못 입력하셨습니다. 다시 입력하세요.\n");
		}
		//1,2번을 선택하였을 경우 함수 끝내기
		if(choice == 1) break;
		if(choice == 2) break;
	}
	*indicator1 = 1; //1번기능이 실행되었다는 표시
}
void displaygraphics(int n, struct process *pr1) {
  int gd = DETECT, gm = 100800;
  int x, y, i, j;
  struct process *base = pr1;

  char m[] = "FCFS";
  char p[100];
  char id[50];
  initgraph(&gd, &gm, 0);
  moveto(0, 0);
  x = getmaxx();
  y = getmaxy();
  setcolor(BLUE);
  rectangle(0, 0, x, y);
  line(0, y / 3, x, y / 3);
  setfontcolor(RED);

  for (i = 0; i < n; ++i, ++base) {
    sprintf(p, "Process %d", i + 1);
    outtextxy(x / n * i, 20, p);
    sprintf(p, "ID %5u", base->pid);
    outtextxy(x / n * i, 50, p);
    sprintf(p, "AT%5u", base->at);
    outtextxy(x / n * i, 60, p);
    sprintf(p, "BT %5u", base->bt);
    outtextxy(x / n * i, 70, p);
    line(x / n * i, 0, x / n * i, y / 3);
  }
  outtextxy(x / 3, 5 + y / 3, m);
  setcolor(BLUE);
  bar(x / 3 + 20, y / 3 + 30, x / 3 + 100, y / 3 + 100);
  sorting(n, pr1, 20);
  for (i = 0; i < n; i++) {
    for (j = 0; j < n; j++) {
      if ((pr1[i].at) == (pr2[j].at)) {
        setcolor(BLUE);
        bar(x / 3 + 20, y / 3 + 30, x / 3 + 100, y / 3 + 100);
        sprintf(id, "pid%d", pr2[j].pid);
        outtextxy(x / 3 + 30, y / 3 + 55, id);
        delay(2000);
        setfontcolor(BLUE);
      }
    }
    setfontcolor(RED);
  }

  setcolor(BLUE);
  line(0, 2 * y / 3, x, 2 * y / 3);
  for (i = 0; i < n; i++) {
    for (j = 0; j < n; j++) {
      if ((pr1[i].at) == (pr2[j].at)) {
        sprintf(id, "pid%d", pr2[j].pid);
        outtextxy(x / n * i, 2 * (y / 3) + 50, id);
        delay(2000);
      }
    }
    line(x / n * i, 2 * y / 3, x / n * i, y);
  }
  delay(2000);
  outtextxy(x - 150, y - 20, "Tapasweni Pathak");
  while (!kbhit())
    ;
  closegraph();
}