Generating all possible permutations in the fox, goose and beans problem

I have learned graph theory, and am using it to solve the classic Fox, goose and bag of beans puzzle. If we consider that there are three locations for each of the fox (X), goose (G), farmer (F) and beans (B) (near side of river, in the boat, far side of the river), and there are four characters, there are hence 4^3 = 81 combinations. Two of these combinations would be

(Near)    (Boat)    (Far) F,G,B,X     -         -  (Near)    (Boat)    (Far)  B,X        F,G        - 

…for the starting state and the state when the farmer and the goose have entered the boat respectively.

I want to generate all of these states programatically (in C++, but that is beyond the point), but simply cannot get my head around how to do it. (I know that some of these 81 possible states will be invalid (e.g. that with all characters in the boat at once) but I can search for those and remove them afterwards.)

I am well aware of binary and how I get 81 combinations, and am aware using C++ I could generate all combinations of the characters F,G,X,B, but still cannot figure how to add the three “locations” into this.

Can someone please advise?

EDIT:

OK, can the downvoter explain how “this question does not show any research effort; it is unclear or not useful”. Do you want me to list everything I’ve tried and every single search I’ve done??

(And yes, I have extensively searched for solutions before posting here.)

Is all permutations of a string a good way to index full text search?

I am writing an application to be used as a local disc documents store similar functionality to Firebase or MongoDB. The gist of how it works is a column hash table. For example:

Say I have a user document

{   "first": "stack",   "last": "overflow",    "age": 2147 } 

I basically iterate each field as a column and save a hashed value as a filename for a file, that contains the unique row key(if multiple objects have the same value for a column there will be multiple row keys written to the file). Then save record in a directory with the key as the filename. So for a simple name = “stack” I have an O(1) lookup, hash the value, see if a file exists with the hashed value as a name, if exists, read all row keys from file. iterate each key and load data from file. I guess if the number of rows is large this will be a slower query.

What I am trying to do I want to ad a partial text search capability. My initial idea is to write all permutations of the value into the index and then do the same O(1) – file exists – check that I mentioned above. So if the query is name name contains st I will just look a filename for that value and read all rows keys.

Is this a good way to offer a partial text search? What are some common industry techniques?

Project

All permutations with known letter on one place

Following code is doing what I want but I am looking for a way how to make it nicer and more effective

for i in c:   for j in c:     for k in c:         for l in c:             for m in c:                               if (i != j and i != k and i != l and j != k and k != l and i != m and j != m and k != m and l !=m):                 print i + j + 'u' + k + l + m 
odusdi odusdt odusit odusti oduids oduidt oduist oduits odutds odutdi odutsi ... 

I tried filters, lambdas and generators but that makes everything just worse.

I am new to python so I also have problems with copying and sending python code any hint with comment would be nice.

How to create a dictionary from a list of words and their permutations [on hold]

So I’ve forgot a luks device passphrase, nothing critical but I’d like to have the content back. I kinda remember what it was about and the words included, but not the exact order of words, so instead of trying manually I’d like to create a dictionary.

I’ve already read about crunch, but it has a problem: the passphrase could be from 10 to 30 characters long, and that would create a dictionary of serveral thousands of petabytes (even restricting the charset) and I couldn’t find an option to use a wordset instead of a charset.

So, I have a list of words that I’m quite sure are included in the passphrase (10 at maximum) and create a dictionary with permutation of them in different order, and also some variation (uppercase for first letter, 1337 characters, numbers and symbols at the end, etc..)

For example, this could be a set of words

  • password
  • luks
  • disk
  • 1987 (I’m pretty sure there was a date)

And this is how I think the dictionary should be

luks password password1987 Password1987 LuksPassword1987 Lukspassword1987 PasswordLuks! password1987diskLuks ... 

Is there another dictionary generating tool that could make this possible?

Stationary Distribution of a Markov Process defined on the space of permutations

Let $ S$ be the set of $ n!$ permutations of the first $ n$ integers. Let $ p\in(0,1)$ . Consider the Markov Process defined on the elements of $ S$ .

  1. Let $ x\in S$ . Choose two distinct integers $ 1\le i <j \le n$ uniformly at random among the $ n(n+1)/2$ possible combinations.
  2. If $ x_i < x_j$ , swap $ x_i$ and $ x_j$ with probability $ p$ , otherwise do nothing. If $ x_i > x_j$ , swap $ x_i$ and $ x_j$ with probability $ 1-p$ , otherwise do nothing.

This process is ergodic, because there is path between any two states with non-zero probability. It has a stationary distribution. I conjecture that the stationary distribution of $ p(x)$ depends only on $ p$ and on the number of mis-rankings of $ x$ , defined as $ \sum_{i\le j} 1\{x_i < x_j\}$ . But am not able to prove it. I also wonder whether this simple model has been studied somewhere, maybe in Statistical Mechanics. Any literature reference is appreciated.

How to return all array permutations iteratively into a two-dimensional array?

I am trying to write a program that will iterate through all possible permutations of a String array, and return a two dimensional array with all the permutations. Specifically, I am trying to use a String array of length 4 to return a 2D array with 24 rows and 4 columns.

I have only found ways to print the Strings iteratively but not use them in an array. I have also found recursive ways of doing it, but they do not work, as I am using this code with others, and the recursive function is much more difficult.

For what I want the code to do, I know the header should be:

public class Permutation {      public String[][] arrayPermutation(String[] str)      {           //code to return 2D array      } } 

//I tried using a recursive method with heap’s algorithm, but it is very //complex with its parameters.

I am very new to programming and any help would be greatly appreciated.

Generate all permutations of 1 to n with i stacks

Assume we have i stacks. the possible actions are:

  1. push to first stack form input
  2. pop from stack i and push it to stack i+1
  3. pop from last stack to output

If we have numbers of 1 to n starting from 1 in the input, what is the minimum value of i which can generate all permutations of 1 to n at the output?

The options are:

  1. 1
  2. 2
  3. n-1
  4. n

Option 1 obviously is not the answer, and also it’s totally possible with n and n-1 stacks witch removes the option 4.

The real question is “is it possible doing it with 2 stacks or we need n-1” ?

Permutations covered by subgroups?

Given integer $ m\in[1,n]$ fix a set $ \mathcal T$ of permutations in $ S_n$ . There are subgroups $ G_1,\dots,G_m$ of $ S_n$ so that $ \mathcal T$ is covered by cosets of $ G_1,\dots,G_m$ .

  1. My problem then is given $ \mathcal T$ is there always an $ m=O(poly(n))$ such that there are elements $ g_1,\dots,g_m\in S_n$ and some subgroups of $ G_1,\dots,G_m$ of $ S_n$ such that

$ $ \mathcal T\subseteq\cup_{i=1}^mg_iG_i$ $ $ $ (\sum_{i=1}^m|G_i|-|\mathcal T|)^2<m’$ $ where both $ m$ and $ m’$ are $ O(poly(n))$ .

  1. If not what is the trade off between $ m$ and $ m’$ ?

  2. Is it possible to get at least $ O(subexp(n))$ for both?

  3. If $ m’=0$ is there always a minimum $ m$ for all $ \mathcal T$ ?

Python program to print all permutations of a string in lexicographic order using recursion

An assignment at school required me to print all permutations of a string in lexicographic or dictionary order.

Here is my solution to the task –

from math import factorial  def print_permutations_lexicographic_order(s):      seq = list(s)     for _ in range(factorial(len(seq))):         print(''.join(seq))         nxt = get_next_permutation(seq)         # if seq is the highest permutation         if nxt is None:             # then reverse it             seq.reverse()         else:             seq = nxt  def get_next_permutation(seq):     """     Return next greater lexicographic permutation. Return None if cannot.      This will return the next greater permutation of seq in lexicographic order. If seq is the highest permutation then this will return None.      seq is a list.     """     if len(seq) == 0:         return None      nxt = get_next_permutation(seq[1:])      # if seq[1:] is the highest permutation     if nxt is None:         # reverse seq[1:], so that seq[1:] now is in ascending order         seq[1:] = reversed(seq[1:])          # find q such that seq[q] is the smallest element in seq[1:] such that         # seq[q] > seq[0]         q = 1         while q < len(seq) and seq[0] > seq[q]:             q += 1          # if cannot find q, then seq is the highest permutation         if q == len(seq):             return None          # swap seq[0] and seq[q]         seq[0], seq[q] = seq[q], seq[0]          return seq     else:         return [seq[0]] + nxt   s = input('Enter the string: ') print_permutations_lexicographic_order(s)) 

Here are some example inputs/outputs:

Enter the string: cow >>> cow     cwo     ocw     owc     wco     woc  Enter the string: dogs >>> dogs     dosg     dsgo     dsog     gdos     gdso     gods     gosd     gsdo     gsod     odgs     odsg     ogds     ogsd     osdg     osgd     sdgo     sdog     sgdo     sgod     sodg     sogd     ogds     ogsd 

So, I would like to know whether I could make my program shorter and more efficient.

Any help would be highly appreciated.

Finding the sublist with best utility function among all list’s permutations

I try to find the the better solution in terms of time complexity. Among the list of elements I need to find the sublist with maximum value of given utility function.

Each element has it’s own type. The type of the adjusted element in the sublist should be different

My code works, I find it not optimal. I guess there is a room for improvement in terms time complexity.

import sys #python 3.5  class Object:     def __init__(self, initial_position, object_type):         self.initial_position = initial_position         self.object_type = object_type      @property     def object_relevance(self):         '''         object utility function         '''         return 2 ** (-self.initial_position)   class ObjectList:     def __init__(self, list):         self.object_list = list         self.rel = 0         self.best_list = []       def _list_relevance(self, object_sub_list):         '''         list utility function         '''         relevance = 0         for j in range(len(object_sub_list)):             relevance += (2 ** (-j)) * object_sub_list[j].object_relevance         return relevance       def _check_sub_list_permissibility(self, object_sub_list):         for i in range(len(object_sub_list) - 1):             if object_sub_list[i].object_type == object_sub_list[i + 1].object_type:                 return False             else:                 pass         return True       def _element_not_exist_in_the_list(self, object_sub_list, elem):         for object in object_sub_list:             if elem.initial_position == object.initial_position:                 return False         return True       def _traverse(self, object_list, init_list):         for elem in object_list:             try_list = init_list.copy()             if self._element_not_exist_in_the_list(try_list, elem):                 try_list.append(elem)                 if self._check_sub_list_permissibility(try_list):                     init_list = try_list                     if self._list_relevance(init_list) > self.rel:                         self.best_list = init_list                         self.rel = self._list_relevance(init_list)                     next = [object for object in object_list if object.initial_position != elem.initial_position]                     self._traverse(next, init_list)       def find_relevant_subset(self):         self._traverse(self.object_list, [])         return self.best_list  if __name__ == '__main__':     input = sys.stdin.read()     data = list(map(int, input.split()))     n, m = data[:2]     a_list = [Object(i,object_type) for i, object_type in enumerate(data[2:])]     object_list = ObjectList(a_list)     best_list = object_list.find_relevant_subset()     return_format = ' '.join([str(object.initial_position) for object in best_list])     sys.stdout.write(return_format) 

The input format: The first line contains numbers separated by a space n and m. m – is the number of unique types and n is the number of elements. In the next n lines of the input the type of every element is specified.

10 2 1 1 1 0 0 1 0 1 1 1 

So in the example above we have 10 elements with two different types (0 and 1). The input specifies the type of each element. Each object has it’s own type (in this example – 0 or 1) object_type and the order index initial_position.

The output format: 0 3 1 4 2 6 5

The goal is to find the sublist with maximum value of given utility function (_list_relevance).

This output shows the list of element’s initial_position. Also the object_type of the adjusted elements in this list are different.

  • The element with initial_position == 0 has object_type == 1
  • The element with initial_position == 3 has object_type == 0
  • The element with initial_position == 1 has object_type == 1
  • The element with initial_position == 4 has object_type == 0
  • The element with initial_position == 2 has object_type == 1
  • The element with initial_position == 6 has object_type == 0
  • The element with initial_position == 5 has object_type == 1

My algorithm: I tried to represent all possible combinations of the initial list as a tree and perform the DFS consider the given constrains. My code works, I find it not optimal. I guess there is a room for improvement in terms time complexity.