Sequence Equation
Sequence Equation
+ 0 comments Here is my O(N) c++ solution, you can watch the explanation here : https://youtu.be/D9nfVOmmv7Q
vector<int> permutationEquation(vector<int> p) { vector<int> indexes(p.size() + 1), result; for(int i = 1; i <= p.size(); i++) indexes[p[i-1]] = i; for(int i = 1; i <= p.size(); i++) result.push_back(indexes[indexes[i]]); return result; }
+ 0 comments The
permutationEquation
function you provided seems to implement the permutation equation method in Python. This method takes a listp
as input and returns a list of values based on the permutation equation.Let's break down the code to understand how it works:
def permutationEquation(p): result = [] for i in range(len(p)): p1 = p.index(i+1) + 1 result.append(p.index(p1) + 1) return result
- The function
permutationEquation
takes a listp
as an argument. - It initializes an empty list called
result
to store the computed values. - It iterates over the range of indices of the input list
p
using therange
function. - Inside the loop, it calculates
p1
by finding the index ofi+1
inp
and adding 1 to it. Theindex
function returns the index of the first occurrence of the specified value in the list. - Then, it finds the index of
p1
in the listp
using theindex
function again, and adds 1 to it. - The computed value is then appended to the
result
list. - After the loop completes, the function returns the
result
list.
This function essentially calculates the permutation equation
p(p(y)) = x
for each valuex
in the input listp
and returns the resulting list.Please note that the code assumes that the input list
p
is 1-based indexed (i.e., the values start from 1). If the input list is 0-based indexed, the code would need to be modified accordingly.- The function
+ 0 comments It's nearly impossible to write a readable solution to such a nonsensical problem. It's bascially asking you to think in terms of POSITION instead of 0 based index. The solution to that problem is a 1 based index, hence the + 1's you see.
Java 8 Solution:
public static List<Integer> permutationEquation(List<Integer> intArray) { // Write your code here List<Integer> returnList = new ArrayList<Integer>(); for(int i = 1; i <= intArray.size(); i++){ int outterPos = intArray.indexOf(i) + 1; returnList.add(intArray.indexOf(outterPos) + 1); } return returnList; }
+ 0 comments My Javascript (nodejs) solution:
let y = []; p.forEach((item, i) => y[i] = p.indexOf(p.indexOf(i+1) + 1) + 1); return y;
+ 0 comments python3
def permutationEquation(p): result = [] for i in range(len(p)): p1 = p.index(i+1) + 1 result.append(p.index(p1) + 1) return result
Sort 1381 Discussions, By:
Please Login in order to post a comment