w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Recursive Permutation C++
You need to send all numbers of possibilities for permutation. If you change your main function you will get the solution. Add a loop in main funciton and send to nextPermutation(a, i) with variable i int main() { for(int i = 1; i < 5; i++) { int a[]= {1,2,3,4}; nextPermutation(a,i); } return 0; } You should debug your program and also i figure out that your s value is decrasing here: else if(i==0 && test(a,s)) { int p=a[0]; for(int i=0; i<=s-2; i++) { a[i]=a[i+1]; } fl=1; nextPermutation(a,s-1); //*** careful you are decreasing s here and your output gives 3 numbers. !!*** a[s]=p; fl=0; nextPermutation(a,s); }

Categories : C++

How to calculate the permutation of a bit vector?
Yes in order to permute the bit vector, then take each bit and apply the permutation function on it.

Categories : Algorithm

Java: Permutation of array
Stick them in a list and then get an array out of it. You could go directly with an int[][] but you do not know the first dimension value without an extra repetition. public static int[][] permuteToArray(int[] array, int k){ ArrayList<int[]> arrL=new ArrayList<>(); for(int i=k; i<array.length; i++) { int temp; temp = array[i]; array[i] = array[k]; array[k] = temp; permute(array, k+1, arrL); int temp2; temp2 = array[i]; array[i] = array[k]; array[k] = temp2; } if (k == array.length-1) { arrL.add(array); } return arrL.toArray(new int[][]); } Change permute( to be: public static void permute(int[] array, int k, ArrayList arrL) //raw type, I know { for(int i=k;

Categories : Java

R - help on basic one-way permutation test
I don't think you need to bother with factors, or pretty much any of your source data. Say, e.g., you have 1000 runners of which 10 are 'abroad' . Then all you need to do is calculate(simulate) the probability of the first 10 values of runif(1000) being in the top X% of all random values generated. The order of generation is irrelevant since you're assuming noncorrelation.

Categories : R

Python - permutation and percentage
I'm a little unclear about what the output should be exactly, but if you want to compare the 1-c1 values of a and b, then the 1-c1 values for b and c, etc. for each of the columns in your list you could do: # NOTE: I'm using foo as input because it should have more interesting # results than for your given list foo = [[x for x in range(1, 11)], [x for x in range(10, 0, -1)], [x for x in range(1, 11)]] ans = [] for comp, to in zip(foo[:-1], foo[1:]): ans.append([]) for n in range(len(comp)): ans[-1].append((100 * to[n]/float(comp[n])) - 100) The values stored in ans are: [[900.0, 350.0, 166.66666666666669, 75.0, 20.0, -16.66666666666667, -42.857142857142854, -62.5, -77.77777777777777, -90.0], [-90.0, -77.77777777777777, -62.5, -42.857142857142854, -16.6

Categories : Python

List permutation existance
var query = PossibleSolution.Any(x=>HashSet<int>.CreateSetComparer() .Equals(new HashSet<int>(){A,B,C} ,new HashSet<int>(){x.CapacitorALocation,x.CapacitorBLocation,x.CapacitorCLocation})); To save some time, you can create the HashSet<int>(){A,B,C} and the comparer beforehand, and call it in your code, with something like: var fixedSet = new HashSet<int>(){A,B,C}; IEqualityComparer<HashSet<int>> comparer = HashSet<int>.CreateSetComparer(); var query = PossibleSolution.Any( x=>comparer.Equals(fixedSet,new HashSet<int>(){x.CapacitorALocation,x.CapacitorBLocation,x.CapacitorCLocation})); And finally, for a version that uses SetEquals instead of the comparer, check Thomas Levesque s

Categories : C#

2 arrays, find every permutation
This works on http://writecodeonline.com/php/ : $option_array[] = array( "name" => "delivery", "options" => array( "sat", "sun") ); $option_array[] = array( "name" => "colour", "options" => array( "red", "blue", "green") ); $option_array[] = array( "name" => "size", "options" => array( "small", "medium", "large") ); $N = 1; foreach ($option_array as $options) $N *= count($options['options']); $all_combinations = array(); for( $i = 0 ; $i < $N ; ++$i ) { $all_combinations[$i] = array(); $q = $i; for( $j = count($option_array)-1 ; 0 <= $j ; --$j ) { $opt = $option_array[$j]; $nopts = count($opt['options']); $all_combinations[$i][$opt['name']] = $opt['options'][$q % $nopts]; $q = floor($q / $no

Categories : PHP

Prolog - Nth Permutation of 3 elements
One way to do this (note that the permutations are in lexicographical order) is to explicitly state that two consecutive elements cannot be the same: perm(1, Input, [Last]) :- member(Last, Input). perm(N, Input, [First,Second|Perm]) :- N > 1, N0 is N-1, member(First, Input), dif(First, Second), perm(N0, Input, [Second|Perm]). ?- perm(3,[a,b,c],R). R = [a, b, a] ; R = [a, b, c] ; R = [a, c, a] ; R = [a, c, b] ; R = [b, a, b] ; R = [b, a, c] ; R = [b, c, a] ; R = [b, c, b] ; R = [c, a, b] ; R = [c, a, c] ; R = [c, b, a] ; R = [c, b, c] ; false. You have tagged the question with swi-prolog. It has a predicate dif/2, like other major Prolog implementations. You can also find quite a few interesting discussions on StackOverflow about dif/2, with pros and cons. To summ

Categories : Prolog

permutation of an array of strings in c++
You could have accomplished it easier using standard library: #include <algorithm> using namespace std; int main() { int a[] = {1, 2, 5, 6, 7}; int n = 5; do { // print array a } while (next_permutation(a, a + n)); } Unless the task was to implement it on your own. And of course make sure your array is sorted before you try to permutate it in this way, otherwise you will miss some permutations.

Categories : C++

need help on permutation & combination ..would like to know the formula for this?
I will denote by W, W, W, B, B and G the rabbits of each color. Note first that, at most, you will have binomial(6, 3)×binomial(3, 2)×binomial(1, 1) = 60 such alignments. As this is not a so large number, and as the constraint of "not two rabbits of the same color side-by-side" is pretty strong (as half of your rabbits already share the exact same color!), let's try to enumerate all such correct lines. First you have the lines where you have White rabbit at one and only one edge of the line. This means the line must look like (assuming the White rabbit starts the line) W _ W _ W _, and that's it. Now you can fill as you wish the empty spots _ with the remaining rabbits, and the constraint will be satisfied for all of the colors. You have 3 different ways of filling the empty spots, hen

Categories : Misc

How to add characters to the output of a permutation in Haskell?
You can map a function that adds the prefix: combinations pre suf letters = prefixed ++ suffixed where perms = permutations letters prefixed = map (x -> pre ++ x) $ perms suffixed = ... The way to solve this is to break the problem down, as you have started doing: create a function to give every permutation (permutation) create functions to add the prefix & suffix (x -> pre ++ x etc) apply these functions to every permutation (map) to create two lists of words combine the two lists of words (++)

Categories : Haskell

permutation with two sets in itertools using python
Is this what you are looking for? def change_freq(freq_set, freq_set_val, freq, i1, i2): change = "echo "+ str(freq_set[freq_set_val][freq][i1]) +"> /sys/devices/system/cpu/cpu"+ str(sets[freq_set_val][i2]) + "/cpufreq/scaling_setspeed" # os.system(change) for freq_set_val in range(0, len(freq_set)): for freq in range(0, len(freq_set[freq_set_val])): for i in range(0, (freq_set_val+1)*2): change_freq(freq_set, freq_set_val, freq, i/2, i) if freq_set_val == 0: print "dosomething" if freq_set_val == 1: print "dosomething" if freq_set_val == 2: print "dosomething" if freq_set_val == 3: print "dosomething"

Categories : Python

How to obtain the index permutation after the sorting
Why not put some satellite data? Instead of sorting the numbers, just sort pairs of numbers and their indices. Since the sorting is first done on the first element of the pair, this shouldn't disrupt a stable sorting algorithm. For unstable algorithms, this will change it to a stable one. But note that if you try sorting this way it generates the index while sorting, not after. Also, since knowing the permutation index would lead to a O(n) sorting algorithm, so you cannot do it faster than O(nlogn).

Categories : C++

Python - get all permutation of a list w/o repetitions
You need itertools.combinations(). And to get a regular list, just use list() factory function. >>> from itertools import combinations >>> list(combinations([1, 2, 3, 4], 3)) [(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)]

Categories : Python

Permutation with redundant overlaps? Python
You want itertools.product instead: >>> import itertools >>> mylist = ['a', 'b', 'c', 'd', 'e', 'f'] >>> list(itertools.product(mylist, repeat=2)) [('a', 'a'), ('a', 'b'), ('a', 'c'), ...]

Categories : Python

Algorithm of Permutation with Limited Repetition
I have come into this problem before with generating all the possible partitions of a set. This is essentially the same concept as what you are trying to do. (All combinations of a given size is the same as the set of partitions of that size) I found this paper that gave a very fast non recursive algorithm to generate these combinations without any repetition along with a c++ implementation.

Categories : Java

Boost spirit permutation of rules
Edit Moved my early response to the bottom BIG UPDATE That took a while. Mostly it was because the code shown has strange problems: several rules contain syntax errors (function_call and factor_ there is a reference to GetContainerId and GetSubstring was never Phoenix-adapted The type CTranslationFunctions didn't exist, and member functions were being declared however the ADAPT_FUNCTION macros still referenced the member function names as if they were supposed to be in the enclosing namespace (?!) So what I basically ended up doing was a re-write. Yeah I know. I'm crazy. Nevertheless, let me walk you through it, explaining some of the things I changed and why. #define BOOST_SPIRIT_USE_PHOENIX_V3 // #define BOOST_SPIRIT_DEBUG #include <boost/spirit/include/qi.hpp> #include <

Categories : C++

Prolog sort list using permutation
permutation sort doesn't remove duplicates: testing your code ?- sort_([1,4,2,5,4,4,2], X). X = [1, 2, 2, 4, 4, 4, 5] . (I renamed to sort_ to avoid the builtin name clash). But sort/2 does remove duplicates. You can use msort/2 ?- msort([1,4,2,5,4,4,2], X). X = [1, 2, 2, 4, 4, 4, 5].

Categories : Sorting

Haskell -- mapping function to permutation
try map listToNumber (permutations [1 .. 3]) in ghci you can check the type of a function or an expression with :t > :t map > map :: (a -> b) -> [a] -> [b] im means map requires a function and a list and returns a list, but in map listToNumber permutations [1 .. 3] you try to pass two functions and a list to map (since function application associates to the left).

Categories : Haskell

minimum switch to sorted permutation
This looks suspiciously similar to bubble sort, in which you need up to n^2 movements. And the interesting fact is that, simple bubble sort actually achieves your goal to find the minimum number of switches! (proof below) In that case, we don't need to further improve algorithms using double loops, and it's actually possible using double loops (in C++): int switch = 0; for(int repeat=0; repeat<n; repeat++){ for(int j=0; j<n-repeat; j++){ if(arr[j]>arr[j+1]){ int tmp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = tmp; switch = switch + 1 } } } The switch is the result. arr is the array containing the numbers. n is the length of the array. Prove that this produces minimum number of switch: First, we note that th

Categories : Algorithm

Generate all one step variations of a permutation
>>> from itertools import product >>> for p in product(range(5), repeat=5): print(p[::-1]) (0, 0, 0, 0, 0) (1, 0, 0, 0, 0) (2, 0, 0, 0, 0) (3, 0, 0, 0, 0) (4, 0, 0, 0, 0) (0, 1, 0, 0, 0) (1, 1, 0, 0, 0) .... >>> import itertools >>> for p in itertools.permutations(range(5)): print(p[::-1]) (4, 3, 2, 1, 0) (3, 4, 2, 1, 0) (4, 2, 3, 1, 0) (2, 4, 3, 1, 0) (3, 2, 4, 1, 0) .... >>> for p in itertools.combinations_with_replacement(range(5), 5): print(p) (0, 0, 0, 0, 0) (0, 0, 0, 0, 1) (0, 0, 0, 0, 2) (0, 0, 0, 0, 3) (0, 0, 0, 0, 4) (0, 0, 0, 1, 1) .... Like that? Something along those lines?? :P

Categories : Python

Parsec permutation parser with separators
Something like that: parsePlus = many1 (char ' ') >> char '+' >> many1 (char ' ') parseRegisterModified = parsePlus >> parseOffsetLabel parseOffsetModified = parsePlus >> parseLabel parseRegister' = do Address r _ _ <- parseRegister optionMaybe parseRegisterModified >>= return $ maybe (Address r Nothing Nothing) (Address _ o l -> Address r o l) parseOffset' = do Address _ o _ <- parseOffset optionMaybe parseOffsetModified >>= return $ maybe (Address Nothing o Nothing) (Address _ _ l -> Address Nothing o l) parseOffsetLabel = try parseOffset' <|> parseLabel parseAddress = try parseRegister' <|> parseOffset' <|> parseLabel

Categories : Haskell

Empty string consideration for substring and permutation
You can test the first two yourself with contains: /* 1 */ System.out.println("".contains("")); /* 2 */ System.out.println("abc".contains("")); true true As for your last question, it seems analogous to asking how many permutations of the empty set are there?, and the answer to that is 0! = 1 - i.e. yes, the empty set is a permutation of itself, therefore the empty string can be considered a permutation of itself, in the mathematical sense.

Categories : Java

Looking for better-than-O(n^2) algorithm for “factorial base” representation of permutation
Your loop for j <- i + 1 to n - 2: if p[i] > p[j]: d[i] <- d[i] + 1 is simply a rank query; you want to know how many elements of p after the ith are less than p[i]. You can modify a balanced binary search tree to report the rank of an element in logarithmic time in addition to its usual operations. You can initialise such a tree to contain all of p. Then you are setting d[i] to rank(p[i]) and deleting p[i]. (You could also run your loop backward and do insertions instead of deletions.)

Categories : Algorithm

Haskell permutation library function - please clarify?
First, I'll move rewrite the code in a form that's probably easier for you to understand, with the internal function definitions moved outside the main function. Note that I had to add some parameters to interleave and interleave' so that they could "see" all the same variables they had access to when they were defined within other functions. I also added type signatures for clarity. permutations :: [a] -> [[a]] permutations xs0 = xs0 : perms xs0 [] The function perms takes two lists, and creates every possible permutation of the elements in both lists -- but not including the original order. For example: λ> perms "ab" "XY" ["aXYb","XaYb","aYXb","YaXb","baXY","abXY","aXbY","bXaY","XbaY","XabY","bYXa","YbXa","YXba","bXYa","XbYa","XYba","bYaX","YbaX","YabX","baYX","abYX","aYbX"

Categories : Haskell

gprolog - Simple way to determine whether one list is a permutation of another
perm(L, M) :- sort(L, X), sort(M, X). This gets you pretty close and is fully declarative ("two lists are permutations of each other if they have the same sorted representation", but sorting in Prolog removes duplicates). However, it will succeed for cases like perm([1,2], [2,2,2,1]) which I'm not sure if you want. It will handle [2,2,4] and [4,4,2] though, since they both sort to [2,4]. Another solution would be something like this: perm([], []). perm([L|Ls], M) :- select(L, M, Ms), !, perm(Ls, Ms). This version won't succeed for [2,2,4] and [4,4,2], but it will properly fail for [1,2] and [2,2,2,1]. I'm not sure which one you want, but I think one or the other of these is probably correct.

Categories : Prolog

Python: create permutation of variables and operators
You can use python "itertools" http://docs.python.org/2/library/itertools.html to genrate all combinations of ['+','-','*','a','b','c',10] So that you can get all possible combinations and then just filter out the valid expressions. but it won't generate paranthesis. You can include ['(',')'] but it will take more time.

Categories : Python

Create a table of permutation data python
Here's an approach in which the data gets packed into a 2D list in the format you requested above to prepare it for printing, then use a nice little pretty-printing script that thg435 wrote in another answer to print the 2D list out with even spacing. cat1 = ['red', 'green', 'blue', 'yellow'] cat2 = ['round', 'square', 'hard', 'soft'] permutations = [c1 + " " + c2 for c1 in cat1 for c2 in cat2] # making the actual permutation list values = range(len(permutations)) # creating some values for us to use # This part puts the permutation values into a list of lists to prepare it for printing: matrix = [[" "] + cat1] for c2 in cat2: row = [c2] for c1 in cat1: permutation = c1 + " " + c2 row.append(values[permutations.index(permutation)]) matrix.append(row) #

Categories : Python

Permutation Parser to vector, via matches
I'm assuming that you don't really need a fusion::vector<bool,bool,bool> and you just want it to work. If this assumption is wrong simply say something in the comments. As you can see in the documentation the attribute of the permutation parser is tuple<optional<A>,optional<B>>. In your case this translates to fusion::vector<optional<bool>,optional<bool>,optional<bool>>. Thanks to the way Spirit works with attributes this vector is compatible with a simple fusion::vector<bool,bool,bool>. In this case this means that every non-empty component of the optional vector (the ones that are actually matched by the permutation parser) is assigned to its corresponding one of the plain bool vector, and the rest of the components in this latter ve

Categories : C++

String permutation on linking trailing character
What you want to do is a Eulerian Path.. I had solved the same problem on Codechef. This is my Code if you wanna use.. Plz tell me if you need a explanation,it is very easy to understand though. #include <iostream> #include <string.h> #include <string> using namespace std; int visit[26]; int adj[26][26]; int count=0; void scc(int i) //Strongly COnnected Component { visit[i]=-1;//visiting for(int t=0;t<26;t++) { if(adj[i][t]>0 && visit[t]==0)//not visited yet scc(t); } visit[i]=1; count++; } int main() { string in; int t,n,k,nv,counta,countb,flag; int a[26],b[26]; cin >> t; while(t--) { cin >> n; memset(a,0,26*sizeof(int)); memset(b,0,26*sizeof(int));

Categories : String

Generating permutation in Python with specific rule
Use itertools.product function to generate permutation. from itertools import * w = [1,2,3,4] max_weight = 4 for selection in product([1,0], repeat=len(w)): accum = sum(compress(w, selection)) if accum > 4: print '{} --> {} > {}, exceeded, stop, move to next'.format(selection, accum, max_weight) else: print '{} --> {} , finished, move to next'.format(selection, accum) Use itertools.compress to filter weights by selection. >>> from itertools import * >>> compress([1,2,3,4], [1,0,1,1]) <itertools.compress object at 0x00000000027A07F0> >>> list(compress([1,2,3,4], [1,0,1,1])) [1, 3, 4]

Categories : Python

How to find the mapping after permutation of a 2-d matrix in Matlab
low hanging fruits first. Suppose there are no duplicate rows: % compute the permutation matrix P = all( bsxfun( @eq, permute( A, [1 3 2]),permute(B,[3 1 2]) ), 3 ); [~, p] = max(P, [], 2 ); % gives you what you want If there are duplicates, we need to "break ties" in the rows/columns of P: n = size(A,1); bt = abs( bsxfun(@minus, 1:n, (1:n)' ) )/n; %//' [~, p] = max( P+bt, [], 2 );

Categories : Matlab

Neo4j 2.0 cypher enforce unique username (create unique node or fail)
Not thread safe yet, but MERGE is the proper way to do this. You could do something like this, that sort of checks for a property matching something before returning. This kind of depends on the fact that timestamp() returns the same value for an entire query, which is documented: http://docs.neo4j.org/chunked/milestone/query-functions-scalar.html#functions-timestamp. MERGE (u:User { username:"test" }) ON CREATE u SET u.created = timestamp() WITH u WHERE u.created = timestamp() RETURN u The second time you run this, you don't get any results.

Categories : Neo4j

Laravel 4 - how to use a unique validation rule / unique columns with soft deletes?
Your Eloquent model should have the $softDeletes property set. If so, then when you perform a WHERE check, like User::where('username', 'jimbob'), Eloquent will automatically add in the query WHERE deleted_at IS NULL... which excludes soft deleted items.

Categories : Laravel

assigning unique id and unique name to dynamically created element using global variable
Change: cell1.innerHTML="<td> <input type='text' name='nametext+count' id='nametext+count' required >"; To: cell1.innerHTML="<td> <input type='text' name='" + nametext+count + "' id='" + nametext+count + "' required >"; String literals are not interpreted in JavaScript.

Categories : Javascript

Unique Clustered Index - can I make non-unique without drop/create
Is the clustered index also the primary key? If the clustered index is the primary key, then a unique clustered is also created. This mean you have to drop and create. If the clustered index is not the primary key, you can use with drop existing to drop/create the index. e.g. create clustered index MyIndex on MyTable(MyColumn[s]) with(drop_existing=on);

Categories : Sql Server

Why do all Simplex Noise algorithms have a Permutation & Gradient table?
Essentially yes, the P table is used to select a random gradient from the G table. However, the important thing is that it needs to be repeatable. That is, in the 3D case, for a given (i,j,k) triple you need to be able to always produce the same "random" gradient. This is what makes the noise function coherent. So the whole point of the formula where it does a few lookups in the P table is that the result comes out looking random, but it's deterministic for a given input. If you weren't concerned about performance, you could just as easily use (i,j,k) to seed a pseudorandom number generator, and then use that to pick a gradient from the G table.

Categories : Algorithm

How does this algorithm for generating the next lexicographically ordered permutation work?
The main idea in this algorithm is how to find the next permutation for a given permutation. According to the link that you wrote, it can be done by finding the right most character in the last printed permutation that is smaller than its right character. Proof: Denote P = P[1]p[2]p[3]..p[n] as the last printed permutation. Suppose k is the index of the rightmost character such P[k] > P[k+1]. According to the definition of Next, So Next(P) = P[1]p[2]p[3]..p[k+1]p[k]p[k+2]p[k+3]..p[n]. Let's assume that there is P' such value(P) < value(P') < value(Next(P)). Denote k' as the minimal index such P[k'] != P'[k']. There are 3 options: k' < k: In that case, because value(P') > value(P) , we get that P'[k'] > P[k']. But until the k' index, Next(P) and P are the same, so P'[k'] >

Categories : Algorithm

Create fixed length non-repeating permutation within certain ranges in PHP
Based on some comment clarification, I can suggest one way to go about it. Specifically, this is my "try the simplest thing that could possibly work" approach to a problem that is potentially quite tricky. First, the tricky part is that the sum of all meals has to be in a certain range, but SQL does not have a built-in feature that I'm aware of that does specifically what you want in one pass; that's ok, though, as we can just implement this functionality in PHP instead. So lets say you request 5 meals that will total 2000 calories - we leave the other variables aside for simplicity, but they will work the same way. We then calculate that the 'average' meal is 2000/5=400 calories, but obviously any one meal could be over or under that amount. I'm no dietician, but I assume you'll want no

Categories : PHP

Detecting GWT permutation on server based on user agent
You can take advantage of the HTML5Manifest solution provided with mgwt. They have a linker which produces a file which can be read by the servlet they provide, and return the appropriate list of files to cache by the browser based on the user-agent header. If you want to do it by yourself, you can figure out the most suitable permutation per browser, based on the http user-agent header, and on the compilation-mappings.txt file which is generated by the gwt compiler if you are using xsiframe linker.

Categories : Javascript



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.