Hackerrank – Problem Statement
A description of the problem can be found on Hackerrank.
Solution
I have given count of numbers n.
I will iterate over all numbers from 1
to n
I will find index of each iterated number in all elements and then index of index within all elements
I created solution in:
All solutions are also available on my GitHub profile.
Scala
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import scala.io.Source object Solution extends App { val inputLines = Source.stdin.getLines().toList val n = inputLines.head.toInt val elements = inputLines.tail.head.split(" ").map(_.toInt) val y = (1 to n).map(i => { val index = elements.indexOf(i) val value1 = index + 1 val index2 = elements.indexOf(value1) index2 }) println(y.mkString("\n")) } |
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Scanner; import java.util.stream.Collectors; public class SequenceEquation { public static void main(String[] args) { Scanner stdin = new Scanner(System.in); int tests = Integer.parseInt(stdin.nextLine()); List<Integer> elements = Arrays.stream(stdin.nextLine().split(" ")).map(Integer::parseInt).collect(Collectors.toList()); List<Integer> result = new ArrayList<>(); for(int i = 1; i <= tests; i++) { int index = elements.indexOf(i); int value1 = index + 1; int index2 = elements.indexOf(value1); result.add(index2 + 1); } for (int elem : result) { System.out.println(elem); } stdin.close(); } } |
Javascript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
'use strict'; const processData = input => { const lines = input.split('\n'); const n = parseInt(lines[0]); const elements = lines[1].split(' ').map(i => parseInt(i)); const result = []; for(let i = 1; i <= n; i++) { const index = elements.indexOf(i); const value1 = index + 1; const index2 = elements.indexOf(value1); result[i - 1] = index2 + 1; } console.log(result.join('\n')); }; process.stdin.resume(); process.stdin.setEncoding("ascii"); let _input = ""; process.stdin.on("data", input => _input += input); process.stdin.on("end", () => processData(_input)); |
Here is a solution for Python:
def permutationEquation(p):
return [(p.index(p.index(i)+1)+1) for i in range(1, max(p)+1)]