Algorithm


Problem Name: Mathematics - Sherlock and Moving Tiles

Problem Link: https://www.hackerrank.com/challenges/sherlock-and-moving-tiles/problem?isFullScreen=true

In this HackerRank in Mathematics - Sherlock and Moving Tiles solutions,

Sherlock is given 2 square tiles, initially both of whose sides have length l placed in an x - y plane. Initially, the bottom left corners of each square are at the origin and their sides are parallel to the axes.

At t = 0, both squares start moving along line y = x (along the positive x and y) with velocities s1 and s2.

For each querydetermine the time at which the overlapping area of tiles is equal to the query value, queries[i].

img

Note: Assume all distances are in meters, time in seconds and velocities in meters per second.

Function Description

Complete the movingTiles function in the editor below.

movingTiles has the following parameter(s):

  • int l: side length for the two squares
  • int s1: velocity of square 1
  • int s2: velocity of square 2
  • int queries[q]: the array of queries

Returns

  • int[n]: an array of answers to the queries, in order. Each answer will be considered correct if it is at most 0.0001 away from the true answer.

Input Format
First line contains integers l,s1,s2.
The next line contains q, the number of queries.
Each of the next q lines consists of one integer queries[i] in one line.

Constraints

 

1 <= l,s1,s2 <= 109

1 <= q <= 105

1 <= queries[i] <= L2

s1 not= s2

Sample Input

10 1 2
2
50
100

Sample Output

4.1421
0.0000

Explanation

For the first case, note that the answer is around 4.1421356237..., so any of the following will be accepted:

4.1421356237
4.14214
4.14215000
4.1421
4.1422

 

 

Code Examples

#1 Code Example with C Programming

Code - C Programming


#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

int main() {
    double l, s1, s2;
    int q;
    int i;
    scanf("%lf %lf %lf", &l, &s1, &s2);
    scanf("%d", &q);
    for (i = 0; i  <  q; i++) {
        double qi;
        scanf("%lf", &qi);
        printf("%.20f\n", sqrt(2) * (l - sqrt(qi)) / abs(s2 - s1));
    }
    return 0;
}
Copy The Code & Try With Live Editor

#2 Code Example with C++ Programming

Code - C++ Programming


#include <bits/stdc++.h>

using namespace std;

string ltrim(const string &);
string rtrim(const string &);
vector < string> split(const string &);

/*
 * Complete the 'movingTiles' function below.
 *
 * The function is expected to return a DOUBLE_ARRAY.
 * The function accepts following parameters:
 *  1. INTEGER l
 *  2. INTEGER s1
 *  3. INTEGER s2
 *  4. INTEGER_ARRAY queries
 */

vector<long double> movingTiles(int l, int s1, int s2, vector<long long> queries) {
    int v = abs(s2 -s1);
    vector < long double> ans;
    for (long long q : queries) {
        long double d = sqrt(2)* (long double)l - sqrt(2)*sqrt(q);
        ans.push_back(d/v);
    }
    return ans;
}

int main() {
    
    int l, s1, s2;
    cin >> l >> s1 >> s2;
    
    int q;
    cin >> q;
    
    vector < long long> queries;
    long long query;
    for (int i = 0; i  <  q; i++){
        cin >> query;
        queries.push_back(query);
    }
    
    vector < long double> responses = movingTiles(l, s1, s2, queries);
    
    for (auto time : responses){
        cout<< fixed << setprecision(20) << time << endl ;
    }

    return 0;
}

vector < string> split(const string &str) {
    vector<string> tokens;

    string::size_type start = 0;
    string::size_type end = 0;

    while ((end = str.find(" ", start)) != string::npos) {
        tokens.push_back(str.substr(start, end - start));

        start = end + 1;
    }

    tokens.push_back(str.substr(start));

    return tokens;
}
Copy The Code & Try With Live Editor

#3 Code Example with C# Programming

Code - C# Programming


using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Text.RegularExpressions;
using System.Text;
using System;

class Result
{

    /*
     * Complete the 'movingTiles' function below.
     *
     * The function is expected to return a DOUBLE_ARRAY.
     * The function accepts following parameters:
     *  1. INTEGER l
     *  2. INTEGER s1
     *  3. INTEGER s2
     *  4. INTEGER_ARRAY queries
     */

    public static List < double> movingTiles(int l, int s1, int s2, List<int> queries)
    {

    }

}

class Solution
{
    public static void Main(string[] args)
    {
        TextWriter textWriter = new StreamWriter(@System.Environment.GetEnvironmentVariable("OUTPUT_PATH"), true);

        string[] firstMultipleInput = Console.ReadLine().TrimEnd().Split(' ');

        int l = Convert.ToInt32(firstMultipleInput[0]);

        int s1 = Convert.ToInt32(firstMultipleInput[1]);

        int s2 = Convert.ToInt32(firstMultipleInput[2]);

        int queriesCount = Convert.ToInt32(Console.ReadLine().Trim());

        List < int> queries = new List<int>();

        for (int i = 0; i  <  queriesCount; i++)
        {
            int queriesItem = Convert.ToInt32(Console.ReadLine().Trim());
            queries.Add(queriesItem);
        }

        List < double> result = Result.movingTiles(l, s1, s2, queries);

        textWriter.WriteLine(String.Join("\n", result));

        textWriter.Flush();
        textWriter.Close();
    }
}
Copy The Code & Try With Live Editor

#4 Code Example with Java Programming

Code - Java Programming


import java.io.*;
import java.math.*;
import java.text.*;
import java.util.*;
import java.util.regex.*;

public class Solution {

    /*
     * Complete the movingTiles function below.
     */
    static double[] movingTiles(int l, int s1, int s2, long[] queries) {
        /*
         * Write your code here.
         */
        int len=queries.length;
        double[] time = new double[len];
        double root2 = Math.sqrt(2.0);
        double diff =Math.abs(1.0*s1-1.0*s2);
        for(int i= 0; i  <  len; i++)
        {   time[i]=(l*1.0-Math.sqrt(queries[i]*1.0))*root2/diff;
        }
        return time;
    }

    private static final Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) throws IOException {
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));

        String[] lS1S2 = scanner.nextLine().split(" ");
        scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])*");

        int l = Integer.parseInt(lS1S2[0]);

        int s1 = Integer.parseInt(lS1S2[1]);

        int s2 = Integer.parseInt(lS1S2[2]);

        int queriesCount = scanner.nextInt();
        scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])*");

        long[] queries = new long[queriesCount];

        for (int queriesItr = 0; queriesItr  <  queriesCount; queriesItr++) {
            long queriesItem = scanner.nextLong();
            scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])*");
            queries[queriesItr] = queriesItem;
        }

        double[] result = movingTiles(l, s1, s2, queries);

        for (int resultItr = 0; resultItr  <  result.length; resultItr++) {
            bufferedWriter.write(String.valueOf(result[resultItr]));

            if (resultItr != result.length - 1) {
                bufferedWriter.write("\n");
            }
        }

        bufferedWriter.newLine();

        bufferedWriter.close();

        scanner.close();
    }
}
Copy The Code & Try With Live Editor

#5 Code Example with Javascript Programming

Code - Javascript Programming


'use strict';

const fs = require('fs');

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', function(inputStdin) {
    inputString += inputStdin;
});

process.stdin.on('end', function() {
    inputString = inputString.split('\n');

    main();
});

function readLine() {
    return inputString[currentLine++];
}

/*
 * Complete the 'movingTiles' function below.
 *
 * The function is expected to return a DOUBLE_ARRAY.
 * The function accepts following parameters:
 *  1. INTEGER l
 *  2. INTEGER s1
 *  3. INTEGER s2
 *  4. INTEGER_ARRAY queries
 */

function movingTiles(l, s1, s2, queries) {
  return queries.map(q => 
    Math.abs(Math.sqrt(2) * (Math.sqrt(q) - l) / (s1 - s2)).toFixed(4)
  );
}

function main() {
    const ws = fs.createWriteStream(process.env.OUTPUT_PATH);

    const firstMultipleInput = readLine().replace(/\s+$/g, '').split(' ');

    const l = parseInt(firstMultipleInput[0], 10);

    const s1 = parseInt(firstMultipleInput[1], 10);

    const s2 = parseInt(firstMultipleInput[2], 10);

    const queriesCount = parseInt(readLine().trim(), 10);

    let queries = [];

    for (let i = 0; i  <  queriesCount; i++) {
        const queriesItem = parseInt(readLine().trim(), 10);
        queries.push(queriesItem);
    }

    const result = movingTiles(l, s1, s2, queries);

    ws.write(result.join('\n') + '\n');

    ws.end();
}
Copy The Code & Try With Live Editor

#6 Code Example with Python Programming

Code - Python Programming


#!/bin/python3

import math
import os
import random
import re
import sys

#
# Complete the 'movingTiles' function below.
#
# The function is expected to return a DOUBLE_ARRAY.
# The function accepts following parameters:
#  1. INTEGER l
#  2. INTEGER s1
#  3. INTEGER s2
#  4. INTEGER_ARRAY queries
#

def movingTiles(l, s1, s2, queries):
    # Write your code here
    arr = []
    for i in queries:
        arr.append(round(math.sqrt(2)*(l-math.sqrt(i))/(abs(s1-s2)),4))
    return arr

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    first_multiple_input = input().rstrip().split()

    l = int(first_multiple_input[0])

    s1 = int(first_multiple_input[1])

    s2 = int(first_multiple_input[2])

    queries_count = int(input().strip())

    queries = []

    for _ in range(queries_count):
        queries_item = int(input().strip())
        queries.append(queries_item)

    result = movingTiles(l, s1, s2, queries)

    fptr.write('\n'.join(map(str, result)))
    fptr.write('\n')

    fptr.close()
Copy The Code & Try With Live Editor
Advertisements

Demonstration


Previous
[Solved] Cutting Paper Squares solution in Hackerrank - Hacerrank solution C, C++, C#, java, js, Python
Next
[Solved] Best Divisor solution in Hackerrank - Hacerrank solution C++, java, Python