Skip to content
  • Home
  • Contact Us
  • About Us
  • Privacy Policy
  • DMCA
  • Linkedin
  • Pinterest
  • Facebook
thecscience

TheCScience

TheCScience is a blog that publishes daily tutorials and guides on engineering subjects and everything that related to computer science and technology

  • Home
  • Human values
  • Microprocessor
  • Digital communication
  • Linux
  • outsystems guide
  • Toggle search form
HackerRank Jim and the Orders Problem Solution

HackerRank Jim and the Orders Problem Solution

Posted on June 5, 2023June 5, 2023 By Yashwant Parihar No Comments on HackerRank Jim and the Orders Problem Solution

In this post, we will solve HackerRank Jim and the Orders Problem Solution.

Jim’s Burgers has a line of hungry customers. Orders vary in the time it takes to prepare them. Determine the order the customers receive their orders. Start by numbering each of the customers from 1 to n. front of the line to the back. You will then be given an order number and a preparation time for each customer.
The time of delivery is calculated as the sum of the order number and the preparation time. If two orders are delivered at the same time, assume they are delivered in ascending customer number order.
For example, there are n = 5 customers in line. They each receive an order number order[i] and a preparation time prep[i]:

Customer	1	2	3	4	5
Order #		8	5	6	2	4
Prep time	3	6	2	3	3
Calculate:
Serve time	11	11	8	5	7

We see that the orders are delivered to customers in the following order:

Order by:
Serve time	5	7	8	11	11
Customer	4	5	3	1	2

Function Description
Complete the jimOrders function in the editor below. It should return an array of integers
that represent the order that customers’ orders are delivered.
jimOrders has the following parameter(s):
orders: a 2D integer array where each orders[i] is in the form [order[i], prep[i]].
Input Format
The first line contains an integer n, the number of customers.
Each of the next n lines contains two space-separated integers, an order number and prep
time for customer[i].

Output Format
Print a single line of n space-separated customer numbers (recall that customers are numbered from 1 to n) that describes the sequence in which the customers receive their burgers. If two or more customers receive their burgers at the same time, print their numbers in ascending order.

Sample Input 0

3
1 3
2 3
3 3

Sample Output 0

1 2 3

Explanation 0
Jim has the following orders:

  1. order[1] = 1, prep[1] = 3. This order is delivered at time t = 1+3=4.
  2. order[2] = 2, prep[2] = 3. This order is delivered at time t = 2+3 = 5.
  3. order[3] = 3, prep[3] = 3. This order is delivered at time t = 3+3=6
    The orders were delivered in the same order as the customers stood in line. The Index in order[i] is the customer number and is what is printed. In this case, the customer numbers match the order numbers.
HackerRank Jim and the Orders Problem Solution
HackerRank Jim and the Orders Problem Solution

Table of Contents

  • Jim and the Orders C Solution
  • Jim and the Orders C++ Solution
  • Jim and the Orders C Sharp Solution
  • Jim and the Orders Java Solution
  • Jim and the Orders JavaScript Solution
  • Jim and the Orders Python Solution

Jim and the Orders C Solution

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int com(const void *a,const void *b)
{
    const  long int *x=(const long int*)a;
          const long int *y=(const  long int*)b;

     return(*x>*y)-(*x<*y);
}
int main() {

    /* Enter your code here. Read input from STDIN. Print output to STDOUT */
    int n;
    long int t1,d1;
    scanf("%d",&n);
    int i,j;
    long int t[n],d[n],a[n];
    for(i=0;i<n;i++)
    {

    scanf("%ld %ld",&t[i],&d[i]);
    }
    for(i=0;i<n;i++)
    t[i]+=d[i];
    for(i=0;i<n;i++)
    a[i]=t[i];
    qsort(t,n,sizeof(long int),com);
    for(i=0;i<n;i++)
    {
        for(j=0;j<n;j++)
        {
            if(t[i]==a[j] && a[j]!=0){
            printf("%d ",j+1);
            a[j]=0;}
            
            
        }
    }

    return 0;
}


Jim and the Orders C++ Solution

#include <bits/stdc++.h>
using namespace std;
int N;
int T[1003];
int C[1003];
bool was[1003];

int main() {
    ios_base::sync_with_stdio(0);
    cin >> N;
    for(int i = 1; i <= N; i++)
        cin >> T[i] >> C[i];
    
    for(int i = 1; i <= N; i++) {
        int rs = -1;
        for(int j = 1; j <= N; j++) {
            if(was[j]) continue;
            if(rs == -1 || T[j] + C[j] < T[rs] + C[rs]) {
                rs = j;
            }
        }
        
        cout << rs << " ";
        was[rs] = true;
    }
    return 0;
}

Jim and the Orders C Sharp Solution

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.IO;
using System.Numerics;

class Program
{
    static void Main(string[] args)
    {
        int n = Convert.ToInt32(Console.ReadLine());
        int[] index = new int[n];
        int[] t = new int[n];
        int[] d = new int[n];

        for (int i = 0; i < n; i++)
        {
            index[i] = i + 1;
            string[] parts = Console.ReadLine().Split(' ');
            t[i] = Convert.ToInt32(parts[0]);
            d[i] = Convert.ToInt32(parts[1]);
        }

        bool sorted = false;
        while (!sorted)
        {
            sorted = true;
            for (int i = 0; i < n - 1; i++)
            {
                int vPrevious = t[i] + d[i];
                int vNext = t[i + 1] + d[i + 1];
                if (vPrevious > vNext ||
                    (vPrevious == vNext && index[i] > index[i + 1]))
                {
                    int temp = 0;

                    temp = index[i];
                    index[i] = index[i + 1];
                    index[i + 1] = temp;

                    temp = t[i];
                    t[i] = t[i + 1];
                    t[i + 1] = temp;

                    temp = d[i];
                    d[i] = d[i + 1];
                    d[i + 1] = temp;

                    sorted = false;
                }
            }
        }

        for (int i = 0; i < n; i++)
        {
            Console.Write("{0} ", index[i]);
        }
    }
}

Jim and the Orders Java Solution

import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;

class Result {

    /*
     * Complete the 'jimOrders' function below.
     *
     * The function is expected to return an INTEGER_ARRAY.
     * The function accepts 2D_INTEGER_ARRAY orders as parameter.
     */

    public static List<Integer> jimOrders(List<List<Integer>> orders) {
        List<Integer> returnList = new ArrayList<>();
        TreeMap<Integer,List<Integer>> map = new TreeMap<>(); 
        for(int i=0;i<orders.size();i++){            
            int key = orders.get(i).get(0)+orders.get(i).get(1); 
            int value = i+1; 
            if(Objects.isNull(map.get(key))){
                List<Integer> list = new ArrayList<>();
                list.add(value);
                map.put(key,list);    
            }else{
                map.get(key).add(value);    
            }            
        }
        
        map.forEach((k,v)->{
            IntStream.range(0,v.size()).forEach(e->returnList.add(map.get(k).get(e)) );
        });
        return returnList;
    }

}

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

        int n = Integer.parseInt(bufferedReader.readLine().trim());

        List<List<Integer>> orders = new ArrayList<>();

        IntStream.range(0, n).forEach(i -> {
            try {
                orders.add(
                    Stream.of(bufferedReader.readLine().replaceAll("\\s+$", "").split(" "))
                        .map(Integer::parseInt)
                        .collect(toList())
                );
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        });

        List<Integer> result = Result.jimOrders(orders);

        bufferedWriter.write(
            result.stream()
                .map(Object::toString)
                .collect(joining(" "))
            + "\n"
        );

        bufferedReader.close();
        bufferedWriter.close();
    }
}

Jim and the Orders JavaScript Solution

function processData(input) {
    var lines = input.split("\n");
    var times = {}; //map time to index of person
    for (var i = 1; i < lines.length; i++) {
        var order = lines[i].split(" ").map(Number);
        var time = order[0];
        var duration = order[1];
        var total = time + duration;
        if (!times[total]) {
            times[total] = [];
        }
        times[total].push(i);
    }
    var keys = Object.keys(times).sort(function(a,b) {return a -b;});
  // console.log("Times are " + JSON.stringify(times));
   // console.log("Keys are " + JSON.stringify(keys));
    var output = "";
    for (var k = 0; k < keys.length; k++) {
        var people = times[keys[k]].sort();
     //   console.log("for k = " + k +", keys[k]=" + keys[k] + " and times[keysk]=" + times[keys[k]] + " peole:" + JSON.stringify(people));
        for (var p = 0; p < people.length; p++) {
            output += (people[p] + " ");
        }
    }
    console.log(output.trim());
} 

process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
    _input += input;
});

process.stdin.on("end", function () {
   processData(_input);
});

Jim and the Orders Python Solution

numTrials = int(input())

L = []

for i in range(1,numTrials+1):
    t,d = map(int,input().split())
    L.append((i,t+d))

L.sort(key = lambda x:x[1])

s= ''

for i in L:
    s += str(i[0])+' '
    
print(s)
c, C#, C++, HackerRank Solutions, java, javascript, python Tags:C, cpp, CSharp, Hackerrank Solutions, java, javascript, python

Post navigation

Previous Post: HackerRank Max Min Problem Solution
Next Post: HackerRank Permuting Two Arrays Solution

Related Posts

HackerRank Caesar Cipher Problem Solution HackerRank Caesar Cipher Problem Solution c
HackerRank A Very Big Sum Problem Solution HackerRank A Very Big Sum Problem Solution c
HackerRank Find the Median Problem Solution HackerRank Find the Median Problem Solution c
HackerRank String Construction Problem Solution HackerRank String Construction Problem Solution c
HackerRank Absolute Element Sums Problem Solution HackerRank Absolute Element Sums Solution c
HackerRank Far Vertices Problem Solution HackerRank Far Vertices Problem Solution c

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Pick Your Subject
Human Values

Copyright © 2023 TheCScience.

Powered by PressBook Grid Blogs theme