int main( int argc, char **argv ) { int n, nn; int_list one_to_n; perm_list m, m2; long sum; int k; #if MACINTOSH n = 9; #else if (argc != 2 || sscanf( argv[1], "%d%c", &n ) != 1) { n = 9; } #endif printf( "n = %d\n\n", n ); /* Create the list [1, 2, ..., n]. */ one_to_n = 0; nn = n; while (nn > 0) { int_CONS( nn--, one_to_n, one_to_n ); } m = permutations( one_to_n ); #if PRINT printperms( m ); #endif for ( k = 5; k > 0; --k ) { /* * For C only, we are recreating the list [1, 2, ..., n] each time. * This means C will allocate more storage than the garbage-collected * languages, but it avoids sharing of structure between the results * of each iteration. Shared structure would hurt C a lot more than * a little extra allocation. */ one_to_n = 0; nn = n; while (nn > 0) { int_CONS( nn--, one_to_n, one_to_n ); } m2 = permutations( one_to_n ); reclaim_storage( m ); m = m2; } sum = sumperms( m ); if (sum != (n * (n + 1) * factorial (n)) / 2) printf ("*** wrong result ***\n"); reclaim_storage( m ); #if STATS printf( "Pairs allocated: %d\n", conscount ); printf( "Pairs deallocated: %d\n", freecount ); printf( "Segments allocated: %d\n\n", segcount ); #endif return 0; }
void permutations(int *p, size_t n, void (*callback)(int *)) { size_t i; if (n == 1) { return callback(p); } for (i = 0; i < n - 1; i++) { permutations(p, n - 1, callback); swap(&p[(n & 1 ? 0 : i)], &p[n - 1]); } permutations(p, n - 1, callback); }
unsigned char f_function( unsigned char text, unsigned char key ) { unsigned char buffer1 ; unsigned char buffer2 ; unsigned char result = 0 ; int i ; int row = 0; int row1 = 0; int col = 0; int col1 = 0 ; //Permute P8 buffer1 = permutations( text, 2 ) ; //Add to key buffer2 = buffer1 ^ key ; //SO if (GetBit( buffer2, 7 )) SetBit( row, 1 ) ; if (GetBit( buffer2, 4 )) SetBit( row, 0 ) ; if (GetBit( buffer2, 6 )) SetBit( col, 1 ) ; if (GetBit( buffer2, 5 )) SetBit( col, 0 ) ; //S! if (GetBit( buffer2, 3 )) SetBit( row1, 1 ) ; if (GetBit( buffer2, 0 )) SetBit( row1, 0 ) ; if (GetBit( buffer2, 2 )) SetBit( col1, 1 ) ; if (GetBit( buffer2, 1 )) SetBit( col1, 0 ) ; //Input to boxes buffer1 = s_box( row, col, row1, col1 ) ; //Permute P4 buffer2 = permutations( buffer1, 3 ) ; //Add to L and append right result = text ^ buffer2 ; return result ; }
void permutations(int elements[], int index,int dim, vector<int> &v_AllPerm) { register int i,j; int app; if(index >= 1) { for(i=index; i >= 0; i--) { app=elements[i]; elements[i]=elements[index]; elements[index] = app; permutations(elements, index-1, dim, v_AllPerm); app=elements[i]; elements[i]=elements[index]; elements[index] = app; } } else { for(j=0; j < dim; j++) { //printf("%d", elements[j]); v_AllPerm.push_back(elements[j]); } //printf("\n"); } }
vector<string> generatePalindromes(string s) { vector<string> res; int size = (int)s.size(); unordered_map<char, int> umap; for (int i=0; i<size; ++i) { ++umap[s[i]]; } char mid = ' '; string half = ""; for (auto i : umap) { if (i.second & 1) { if (mid == ' ') { mid = i.first; } else { return res; } } half.append(i.second/2, i.first); } vector<string> p = permutations(half); for (auto i : p) { string final = ""; final += i; if (mid != ' ') final += mid; final += string(i.rbegin(), i.rend());
void permutations(int index) { if(index==length) { selected[index]='\0'; strcpy(sortme[k],selected); k++; return; } int i; for(i=0;i<length;i++) { if(!taken[i]) { if(i>0 && word[i]==word[i-1] && !taken[i-1]) { continue; }else { selected[index]=word[i]; taken[i]=1; permutations(index+1); taken[i]=0; } } } }
vector<vector<int> > permuteUnique(vector<int> &num) { int len = num.size(); vector<int> curr; vector<bool> avail(len,true); sort(num.begin(),num.end()); //This is important permutations(num,avail,curr); return result; }
int checkRoundPrime(int n) { char cnumber[MAX]; sprintf(cnumber, "%d", n); flag = 0; globalnum = atol(cnumber); permutations(cnumber, 0, strlen(cnumber)); if (flag == 0) return 1; else return 0; }
int permutations(char *string, int k, int m) { int i; if (k == m) { if(!checkPrime(atol(string)) || (atol(string) < globalnum)) flag = 1; } else for (i = k; i < m; i++){ swap(&string[k], &string[i]); permutations(string, k+1, m); swap(&string[k], &string[i]); } }
unsigned char decrypt( unsigned char k1, unsigned char k2, unsigned char ciphertext, unsigned char vector ) { unsigned char buffer1 ; unsigned char buffer2 ; //Initial permutation buffer2 = permutations( ciphertext, 0 ) ; //fk2 buffer1 = f_function( buffer2, k2 ) ; //Switch buffer2 = switch_function( buffer1 ) ; //fk1 buffer1 = f_function( buffer2, k1 ) ; //Final Permutation buffer2 = permutations( buffer1, 1 ) ; //Add to vector return buffer2 ^ vector ; }
unsigned char encrypt( unsigned char k1, unsigned char k2, unsigned char plaintext, unsigned char vector ) { unsigned char buffer1 ; unsigned char buffer2 ; //Add to vector buffer1 = plaintext ^ vector ; //Initial permutation buffer2 = permutations( buffer1, 0 ) ; //fk1 buffer1 = f_function( buffer2, k1 ) ; //Switch buffer2 = switch_function( buffer1 ) ; //fk2 buffer1 = f_function( buffer2, k2 ) ; //Final Permutation return permutations( buffer1, 1 ) ; }
void permutations(char *a, int l, int r) { int i; if (l == r){ printf("%s\n", a); } else { for (i = l; i <= r; i++) { swap((a + l), (a + i)); permutations(a, l + 1, r); swap((a + l), (a + i)); } } }
int main() { int num,i=7; char arr[9]; printf("Enter a number: "); scanf_s("%d", &num); arr[8] = '\0'; while (num != 0){ arr[i] = num % 10+'0'; i--; num = num / 10; } permutations(arr, i+1, 7); _getch(); return 0; }
int main() { int test_cases,i,j; scanf("%d",&test_cases); while(test_cases) { scanf("%s",word); length=strlen(word); permutations(0); sortme_print(); length=0; k=0; test_cases--; } return 0; }
void Grammar::kill_epsilon_rules() { SymbolList epsilon_rules; epsilon_rules.push_back(epsilon); SymbolList prev; do { prev = epsilon_rules; for( auto &nT : non_terminals ) { if( contains_char(epsilon_rules, nT) ) { continue; } for( auto rule : production_rules[get_nt_index(nT)] ) { if( subset_of(rule, epsilon_rules) ) { epsilon_rules.push_back(nT); } } } } while( prev != epsilon_rules ); auto map_copy = production_rules; for( auto &nT : non_terminals ) { //std::cout << "running for " << nT << std::endl; for( auto rule : map_copy[get_nt_index(nT)] ) { //std::cout << "running for " << rule << std::endl; if( !empty_intersection(rule, epsilon_rules) ) { for( auto str : permutations(rule, epsilon_rules) ) { production_rules[get_nt_index(nT)].push_back(str); } } //std::cout << "finished for " << rule << std::endl; } //std::cout << "finished for " << nT << std::endl; } //map_copy = production_rules; SymbolList str_epsilon; str_epsilon.push_back(epsilon); for( auto &nT : non_terminals ) { for( auto it = production_rules[get_nt_index(nT)].begin(); it != production_rules[get_nt_index(nT)].end(); ++it ) { if( str_epsilon == *it ) { production_rules[get_nt_index(nT)].erase(it); break; } } } }
vector<string> generatePalindromes(string s) { vector<string> palindromes; unordered_map<char, int> counts; for (char c : s) counts[c]++; int odd = 0; char mid; string half; for (auto p : counts) { if (p.second & 1) {//? odd++, mid = p.first;//奇数 if (odd > 1) return palindromes; } half += string(p.second / 2, p.first);//string constructor } palindromes = permutations(half); for (string& p : palindromes) {//加奇数char string t(p); reverse(t.begin(), t.end()); if (odd) t = mid + t; p += t; } return palindromes; }
vector<vector<int> > permute(vector<int> &num) { // Add an empty vector as the base case (empty input) vector<vector<int> > permutations(1, vector<int>()); // Algrithm description: // Insert the current number in different spaces of previous permutations for (vector<int>::size_type index = 0; index != num.size(); ++index) { vector<vector<int> > subPermutations(permutations); permutations.clear(); for (vector<vector<int> >::size_type i = 0; i != subPermutations.size(); ++i) { for (int offset = 0; offset != subPermutations[i].size()+1; ++offset) { vector<int> temp(subPermutations[i]); temp.insert(temp.begin() + offset, num[index]); permutations.push_back(temp); } } } return permutations; }
void permutations(vector<int> &num,vector<bool> &avail,vector<int> &curr) { if(num.size()==curr.size()) { result.push_back(curr); return; } int lastIDX = -1; for(int i=0;i<num.size();i++) { if(avail[i]==false) continue; if(lastIDX!=-1 &&num[i]==num[lastIDX]) continue; curr.push_back(num[i]); avail[i] = false; permutations(num,avail,curr); curr.pop_back(); avail[i] = true; lastIDX = i; } }
void Tree::computePermutationImportance(std::vector<double>* forest_importance, std::vector<double>* forest_variance) { size_t num_independent_variables = data->getNumCols() - no_split_variables->size(); // Compute normal prediction accuracy for each tree. Predictions already computed.. double accuracy_normal = computePredictionAccuracyInternal(); prediction_terminal_nodeIDs.clear(); prediction_terminal_nodeIDs.resize(num_samples_oob, 0); // Reserve space for permutations, initialize with oob_sampleIDs std::vector<size_t> permutations(oob_sampleIDs); // Randomly permute for all independent variables for (size_t i = 0; i < num_independent_variables; ++i) { // Skip no split variables size_t varID = i; for (auto& skip : *no_split_variables) { if (varID >= skip) { ++varID; } } // Permute and compute prediction accuracy again for this permutation and save difference permuteAndPredictOobSamples(varID, permutations); double accuracy_permuted = computePredictionAccuracyInternal(); double accuracy_difference = accuracy_normal - accuracy_permuted; (*forest_importance)[i] += accuracy_difference; // Compute variance if (importance_mode == IMP_PERM_BREIMAN) { (*forest_variance)[i] += accuracy_difference * accuracy_difference; } else if (importance_mode == IMP_PERM_LIAW) { (*forest_variance)[i] += accuracy_difference * accuracy_difference * num_samples_oob; } } }
vector< vector<T> > permutationsOfCombinations(vector<T> &v, unsigned int k) { unsigned int next = 0; vector< vector<T> > result, combs; if(k > v.size()) throw k_GreaterThan_n_Exception(); else if(k == v.size()) return permutations(v); else combs = combinations(v, k); for(unsigned int it = 0 ; it < combs.size() ; it++) { sort(combs[it].begin(), combs[it].end()); do { result.resize(result.size() + 1); result[next] = combs[it]; next++; } while(next_permutation(combs[it].begin(), combs[it].end())); } return result; }
int main(int argc, const char *argv[]) { int digits[] = {1, 2, 3, 4, 5, 6}; permutations(digits, 6, callback); return 0; }
PeptideHit AScore::compute(const PeptideHit & hit, PeakSpectrum & real_spectrum, double fragment_mass_tolerance, bool fragment_mass_unit_ppm, Size max_peptide_len, Size max_num_perm) { PeptideHit phospho = hit; //reset phospho phospho.setScore(-1); if (real_spectrum.empty()) { return phospho; } String sequence_str = phospho.getSequence().toString(); Size number_of_phosphorylation_events = numberOfPhosphoEvents_(sequence_str); AASequence seq_without_phospho = removePhosphositesFromSequence_(sequence_str); if (seq_without_phospho.toUnmodifiedString().size() > max_peptide_len) { LOG_DEBUG << "\tcalculation aborted: peptide too long: " << seq_without_phospho.toString() << std::endl; return phospho; } // determine all phospho sites vector<Size> sites(getSites_(seq_without_phospho)); Size number_of_STY = sites.size(); if (number_of_phosphorylation_events == 0 || number_of_STY == 0 || number_of_STY == number_of_phosphorylation_events) { return phospho; } vector<vector<Size> > permutations(computePermutations_(sites, (Int)number_of_phosphorylation_events)); LOG_DEBUG << "\tnumber of permutations: " << permutations.size() << std::endl; // TODO: using a heuristic to calculate the best phospho sites if the number of permutations are exceeding the maximum. // A heuristic could be to calculate the best site for the first phosphorylation and based on this the best site for the second // phosphorylation and so on until every site is determined if (permutations.size() > max_num_perm) { LOG_DEBUG << "\tcalculation aborted: number of permutations exceeded" << std::endl; return phospho; } vector<PeakSpectrum> th_spectra(createTheoreticalSpectra_(permutations, seq_without_phospho)); // prepare real spectrum windows if (!real_spectrum.isSorted()) { real_spectrum.sortByPosition(); } vector<PeakSpectrum> windows_top10(peakPickingPerWindowsInSpectrum_(real_spectrum)); // calculate peptide score for each possible phospho site permutation vector<vector<double> > peptide_site_scores(calculatePermutationPeptideScores_(th_spectra, windows_top10, fragment_mass_tolerance, fragment_mass_unit_ppm)); // rank peptide permutations ascending multimap<double, Size> ranking(rankWeightedPermutationPeptideScores_(peptide_site_scores)); multimap<double, Size>::reverse_iterator rev = ranking.rbegin(); String seq1 = th_spectra[rev->second].getName(); phospho.setSequence(AASequence::fromString(seq1)); phospho.setMetaValue("search_engine_sequence", hit.getSequence().toString()); double peptide1_score = rev->first; phospho.setMetaValue("AScore_pep_score", peptide1_score); // initialize score with highest peptide score (aka highest weighted score) ++rev; String seq2 = th_spectra[rev->second].getName(); double peptide2_score = rev->first; vector<ProbablePhosphoSites> phospho_sites; determineHighestScoringPermutations_(peptide_site_scores, phospho_sites, permutations, ranking); Int rank = 1; double best_Ascore = std::numeric_limits<double>::max(); // the lower the better for (vector<ProbablePhosphoSites>::iterator s_it = phospho_sites.begin(); s_it != phospho_sites.end(); ++s_it) { double Ascore = 0; if (peptide1_score == peptide2_score) // set Ascore = 0 for each phosphorylation site { LOG_DEBUG << "\tscore of best (" << seq1 << ") and second best peptide (" << seq2 << ") are equal (" << peptide1_score << ")" << std::endl; } else { vector<PeakSpectrum> site_determining_ions; computeSiteDeterminingIons_(th_spectra, *s_it, site_determining_ions, fragment_mass_tolerance, fragment_mass_unit_ppm); Size N = site_determining_ions[0].size(); // all possibilities have the same number so take the first one double p = static_cast<double>(s_it->peak_depth) / 100.0; Size n_first = 0; // number of matching peaks for first peptide for (Size window_idx = 0; window_idx != windows_top10.size(); ++window_idx) // for each 100 m/z window { n_first += numberOfMatchedIons_(site_determining_ions[0], windows_top10[window_idx], s_it->peak_depth, fragment_mass_tolerance, fragment_mass_unit_ppm); } double P_first = computeCumulativeScore_(N, n_first, p); Size n_second = 0; // number of matching peaks for second peptide for (Size window_idx = 0; window_idx < windows_top10.size(); ++window_idx) //each 100 m/z window { n_second += numberOfMatchedIons_(site_determining_ions[1], windows_top10[window_idx], s_it->peak_depth, fragment_mass_tolerance, fragment_mass_unit_ppm); } Size N2 = site_determining_ions[1].size(); // all possibilities have the same number so take the first one double P_second = computeCumulativeScore_(N2, n_second, p); //abs is used to avoid -0 score values double score_first = abs(-10 * log10(P_first)); double score_second = abs(-10 * log10(P_second)); LOG_DEBUG << "\tfirst - N: " << N << ",p: " << p << ",n: " << n_first << ", score: " << score_first << std::endl; LOG_DEBUG << "\tsecond - N: " << N2 << ",p: " << p << ",n: " << n_second << ", score: " << score_second << std::endl; Ascore = score_first - score_second; LOG_DEBUG << "\tAscore_" << rank << ": " << Ascore << std::endl; } if (Ascore < best_Ascore) { best_Ascore = Ascore; } phospho.setMetaValue("AScore_" + String(rank), Ascore); ++rank; } phospho.setScore(best_Ascore); return phospho; }
// we have a segment, in NFD. Find all the strings that are canonically equivalent to it. UnicodeString* CanonicalIterator::getEquivalents(const UnicodeString &segment, int32_t &result_len, UErrorCode &status) { Hashtable result(status); Hashtable permutations(status); Hashtable basic(status); if (U_FAILURE(status)) { return 0; } result.setValueDeleter(uprv_deleteUObject); permutations.setValueDeleter(uprv_deleteUObject); basic.setValueDeleter(uprv_deleteUObject); UChar USeg[256]; int32_t segLen = segment.extract(USeg, 256, status); getEquivalents2(&basic, USeg, segLen, status); // now get all the permutations // add only the ones that are canonically equivalent // TODO: optimize by not permuting any class zero. const UHashElement *ne = NULL; int32_t el = UHASH_FIRST; //Iterator it = basic.iterator(); ne = basic.nextElement(el); //while (it.hasNext()) while (ne != NULL) { //String item = (String) it.next(); UnicodeString item = *((UnicodeString *)(ne->value.pointer)); permutations.removeAll(); permute(item, CANITER_SKIP_ZEROES, &permutations, status); const UHashElement *ne2 = NULL; int32_t el2 = UHASH_FIRST; //Iterator it2 = permutations.iterator(); ne2 = permutations.nextElement(el2); //while (it2.hasNext()) while (ne2 != NULL) { //String possible = (String) it2.next(); //UnicodeString *possible = new UnicodeString(*((UnicodeString *)(ne2->value.pointer))); UnicodeString possible(*((UnicodeString *)(ne2->value.pointer))); UnicodeString attempt; nfd.normalize(possible, attempt, status); // TODO: check if operator == is semanticaly the same as attempt.equals(segment) if (attempt==segment) { //if (PROGRESS) printf("Adding Permutation: %s\n", UToS(Tr(*possible))); // TODO: use the hashtable just to catch duplicates - store strings directly (somehow). result.put(possible, new UnicodeString(possible), status); //add(possible); } else { //if (PROGRESS) printf("-Skipping Permutation: %s\n", UToS(Tr(*possible))); } ne2 = permutations.nextElement(el2); } ne = basic.nextElement(el); } /* Test for buffer overflows */ if(U_FAILURE(status)) { return 0; } // convert into a String[] to clean up storage //String[] finalResult = new String[result.size()]; UnicodeString *finalResult = NULL; int32_t resultCount; if((resultCount = result.count())) { finalResult = new UnicodeString[resultCount]; if (finalResult == 0) { status = U_MEMORY_ALLOCATION_ERROR; return NULL; } } else { status = U_ILLEGAL_ARGUMENT_ERROR; return NULL; } //result.toArray(finalResult); result_len = 0; el = UHASH_FIRST; ne = result.nextElement(el); while(ne != NULL) { finalResult[result_len++] = *((UnicodeString *)(ne->value.pointer)); ne = result.nextElement(el); } return finalResult; }
int main() { std::string dataPath = "/home/felipe/data/RawADRC/data.mat"; std::string dataArmaPath = "/home/felipe/data/RawADRC/data.arma"; std::string permutationsPath = "/home/felipe/data/RawADRC/permutations.mat"; std::string permutationsArmaPath = "/home/felipe/data/RawADRC/permutations.arma"; int N_g1 = 25; arma::mat data; arma::mat permutations; arma::mat T; arma::mat MaxT; data.load(dataArmaPath); //data.save(dataArmaPath); permutations.load(permutationsArmaPath); //permutations.save(permutationsArmaPath); /* Get dimensions */ int N = data.n_rows; int N_g2 = N - N_g1; int V = data.n_cols; int nPermutations = permutations.n_rows; std::cout << "Number of subjects (rows in data matrix): " << N << std::endl; std::cout << "Number of voxels per subject (cols in data matrix): " << data.n_cols << std::endl; std::cout << "Number of Permutations (rows in permutations matrix):" << nPermutations << std::endl; //T = arma::zeros(nPermutations, V); MaxT = arma::zeros(nPermutations, 1); /* Do Permutation Testing */ arma::urowvec label_j(1, N); arma::mat group1 = arma::zeros(N_g1, V); arma::mat group2 = arma::zeros(N_g2, V); arma::mat tstat = arma::zeros(1, V); /* Permutation loop */ #pragma omp parallel for for(int i = 0;i < nPermutations ;i++ ) { std::cout << "Permutation " << i << std::endl; for(int j = 0; j < N; j++) { label_j(j) = permutations(i, j) - 1; } group1 = data.rows(label_j(arma::span(0, N_g1-1))); group2 = data.rows(label_j(arma::span(N_g1, N-1))); tstat = ttest2(group1, group2); MaxT(i, arma::span::all) = arma::max(tstat,1); } std::cout << T.n_rows << std::endl; std::cout << T.n_cols << std::endl; MaxT.save("MaxT_Iterative_10000.arma"); MaxT.save("MaxT_Iterative_10000.ascii", arma::raw_ascii); std::cout << T.n_rows << std::endl; std::cout << T.n_cols << std::endl; return 0; }