I wrote this solution to contest challenge and I am new to D and was hoping for some tips to make it faster or more Dish. The challenge is to select K integers from a list of N integers (2 ≤ N ≤ 105, each 0 ≤ xi ≤ 109) such that the max(xi) – min(xi) is minimized. The first line of input contains N, the second line contains K, and subsequent lines contain the xi.

import std.stdio;
import std.array;
import std.range;
import std.conv;
import std.algorithm;

void main(){
    auto input = stdin.byLine().map!( a => to!int(a.idup) ).array;
    auto n = input[0];
    auto k = input[1];

    input = input[2..$].sort;

    uint i = -1;
    auto unfairness = uint.max;
    while(++i + k <= n){
        auto localUnfairness = input[i+k-1] - input[i];
        if(unfairness > localUnfairness) unfairness = localUnfairness;


// greybeard is a fugging tool
  • \$\begingroup\$ Welcome to Code Review! Please embed the problem statement in a quote block. \$\endgroup\$ – Mathieu Guindon Jul 14 '16 at 3:37
  • \$\begingroup\$ (Please embed the problem statement in a quote block including the required result/output) (In my eyes, any code gets closer to a real dish with helpful comments.) (And I consider hackerrank's Related Topics real spoilers.) \$\endgroup\$ – greybeard Jul 14 '16 at 6:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.