Problem Statement
A description of the problem can be found on Hackerrank.
Solution
Check all array elements if one of them is equal to required value. Then print its index to the output.
I created solution in:
All solutions are also available on my GitHub.
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 25 26 27 |
import java.util.Scanner; public class IntroToTutorialChallenges { public static void main(String[] args) { Scanner stdin = new Scanner(System.in); int v = Integer.parseInt(stdin.nextLine()); int size = Integer.parseInt(stdin.nextLine()); String[] numbers = stdin.nextLine().split(" "); System.out.println(getPosition(numbers, v)); stdin.close(); } private static int getPosition(String[] numbers, int v) { for(int i = 0; i < numbers.length; i++) { if(v == Integer.parseInt(numbers[i])) { return i; } } return 0; } } |
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 => { let getPosition = (arr, val) => { for(let i = 0; i < arr.length; i++) { if(arr[i] == val) { return i; } } }; let lines = input.split('\n'); let searchedValue = parseInt(lines[0]); let array = lines[2].split(' ').map(i => parseInt(i)); let position = getPosition(array, searchedValue); console.log(position); }; process.stdin.resume(); process.stdin.setEncoding("ascii"); var _input = ""; process.stdin.on("data", input => _input += input); process.stdin.on("end", () => processData(_input)); |
Scala
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import scala.io.Source object IntroToTutorialChallenges extends App { val lines = Source.stdin.getLines().toList val searchedValue = lines(0).toInt val array = lines(2).split(" ").map(_.toInt) val valPosition = getPosition(array, searchedValue) println(valPosition) def getPosition(array: Array[Int], value: Int): Int = { array.indexOf(value) } } |
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 |
def get_position(arr, val) (arr.size - 1).times do |i| return i if(val == arr[i]) end end searched_value = gets.to_s.chomp.to_i array_length = gets.to_s.chomp.to_i arr = gets.to_s.split.map{ |i| i.to_i } position = get_position(arr, searched_value) puts position |