Simple ASCII Gantt

31

2

This is a simple one: print an ASCII Gantt chart.

Given tasks' ranges (start-time - end-time Tuples), print a Gantt timeline in the form of - characters for each task duration - each task in a new line.

Example

Say my tasks ranges are 28->35, 34->40, 39->44, the Gantt will look like this:

                            -------
                                  ------
                                       -----

Specifications

  • You can write a full program, a named function or an anonymous function.
  • Your program/function should accept the tasks via STDIN or as arguments.
  • Each task should be represented as a string of start->end where start and end are Integers. Tasks are separated by spaces or commas. Alternatively, you may get it as a Tuple of Integers, or as an Array/Collection of 2 Integers. (For example, in JavaScript you can get it as [start,end] - this is allowed).
  • Any non-negative number of tasks (arguments) should be supported.
  • To make it clear, a single argument of tasks collection is not allowed. You can either parse a single string argument, or support zero-or-more tasks arguments. Where task is a tuple or a collection of size 2.
  • You can assume only valid input will be given. That means, each task has a positive duration.
  • Return value does not matter, your code must print the timeline on STDOUT.
  • Output: per task, start spaces followed by (end-start) dashes and a \n.
  • Needless to say, output lines should be ordered correspondingly with the input (tasks) order.
  • Trailing spaces before the \n are allowed, if that helps you.

Test cases

Input:
(empty)

Output:
(empty)


Input:
0->7,5->6,3->6

Output:
-------
     -
   ---


Input:
5->20,5->20,2->10,15->19

Output:
     ---------------
     ---------------
  --------
               ----

Winning

  • This is so the least code length (in bytes) wins.
  • Traditionally, tie breaker is earlier post.
  • "Standard loopholes are no longer funny".

-----

EDIT

As many of you understood that it is allowed to have a single tasks collection argument, and since there's no much different between that and the original varargs requirement, it is now allowed to have a single collection argument, if you don't want to use the varargs option, or in case your language does not support varargs.

Jacob

Posted 2015-06-29T13:41:26.047

Reputation: 1 582

1Point 3 seems clear. But piint 5 (To make it clear...) is not clear at all. – edc65 – 2015-06-29T14:37:52.837

Alright, let me rephrase that: You cannot write a function that accepts exactly one argument unless it's a string. If it's a bunch of tuples we're talking about, they may be sent to your function as arguments, not wrapped in a collection. For example, in JavaScript: You may iterate arguments within the function, but you may not assume that arguments[0] is an array of tasks. – Jacob – 2015-06-29T14:43:01.603

I don't understand the purpose of this limitation. In many languages accepting a list is the way you create a function with a variable number of arguments. There is often no equivalent to Javascript's arguments list available. – JohnE – 2015-06-29T14:49:18.403

There is no hidden purpose or reason behind it. I happen to like the "varargs" coding style. I'm sorry that your language does not support it - but not all golfing challenges are suitable for all languages! You can still choose the string parsing option if you insist on a language that does not support varargs. I don't think it will be fair to allow it on some languages and not on others. – Jacob – 2015-06-29T14:54:47.660

8Why not simply allow input as an array / list / vector / etc. for all languages? Personal preference seems like a pretty weak reason. – Doorknob – 2015-06-29T14:58:55.947

1Varargs versus an argument list is a purely syntactic distinction and leaves the rules of this question up to an unnecessary and arbitrary degree of interpretation, in my opinion. – JohnE – 2015-06-29T15:03:09.297

Fine. I will edit now the question to allow it. – Jacob – 2015-06-29T15:03:48.213

Is is acceptable to use MySQL with a table containing the data? – Ismael Miguel – 2015-06-30T14:12:31.103

I'm not sure. You may use SQL / T-SQL and define a FUNCTION or a PROCEDURE. – Jacob – 2015-06-30T14:13:56.327

That's what I wanted to do. but I'm not sure if those SQL 'flavors' have arrays or not. And how that works. – Ismael Miguel – 2015-06-30T14:33:14.040

As far as I know, a Table-Typed Parameter is the Array equivalence in SQL :) However, please consume the table as a Procedure's input parameter, do not count on existing table in a database. You can state in your answer something like: Usage DECLARE @G TABLE(x INT, y INT); INSERT INTO @G VALUES( ... ) and then EXEC your procedure on @G. – Jacob – 2015-06-30T14:38:29.410

I'm not having luck in any way. But thanks a lot for the help. I hope it is useful to someone else. – Ismael Miguel – 2015-06-30T15:48:03.240

Given that: 1)you can accept whenever you like,2)14 bytes seems impossible to beat, 3)anyway you can change your mind later ... Givel all this, It seems too early accepting an asnwer just 1 day after the question. It gives the message: ok, the challenge is over, go think about somthing else .... – edc65 – 2015-07-01T07:17:51.320

May we take two list arguments; all the start-times and all the end-times? – Adám – 2018-01-29T10:25:05.210

I’m sorry @Adám but the answer is no. It won’t be fair for existing answers. – Jacob – 2018-01-29T11:23:09.397

2@Jacob Makes sense. For future challenges, I'd recommend as lax an input spec as possible: Mangling input shouldn't be part of the challenge. – Adám – 2018-01-29T12:28:07.733

Can we take a 1-indexed input? ie 29->36, 35->41, 40->45 in place of 28->35, 34->40, 39->44 – JayCe – 2018-06-18T13:07:02.223

May there be zero-duration tasks? This should be mentioned in the description. – Jakob – 2018-06-18T16:39:43.660

Answers

14

CJam, 16 14 bytes

q~{S.*~'-e]N}/

This expects a list of lists as input. For example:

[[5 20] [5 20] [2 10] [5 19]]

gives:

     ---------------
     ---------------
  --------
     --------------

How it works

q~                      e# Read the input and parse it as a list of list
  {         }/          e# Go over each item in the list in a for loop
   S                    e# S is basically this string - " "
    .*                  e# Multiply each item of the first list with the corresponding index
                        e# item of the second list. This basically repeats the space
                        e# X times where X is the first number of the tuple. The second
                        e# number remains untouched as the second list was only 1 char long
      ~                 e# Unwrap the space string and second number containing list
       '-               e# Put character '-' on stack
         e]             e# Make sure that the space is filled with - to its right so as to
                        e# make the total length of the string equal to the second number
           N            e# Put a newline. After all iterations, the result is printed
                        e# automatically to STDOUT

Try it online here

Optimizer

Posted 2015-06-29T13:41:26.047

Reputation: 25 836

20

Python 2, 39 Bytes

Straightforward solution using string multiplication :)

for x,y in input():print' '*x+'-'*(y-x)

Accepts input formatted like so:

((5,20),(5,20),(2,10),(15,19))

Check it out here.

Kade

Posted 2015-06-29T13:41:26.047

Reputation: 7 463

11

Brainfuck, 120 115 111 bytes

At least it's shorter than Java :) The input is a list of bytes, where each pair is a single line in the gantt.

++++[->++++++++<]>[->+>+<<]++++++++++>>+++++++++++++>+[,[->+>+<<]>>[-<<+>>],<[->-<<<<.>>>]>[-<<<.>>>]<<<<<.>>>]

Try out

http://copy.sh/brainfuck/

Set end-of-input to char with value \0. Example input: \5\20\5\20\2\10\15\19.

Note that setting the end-of-input value to \0 will have the side effect that no more input will be read (and thus stopping the program) when the input contains the number zero. In BF there is no other way of knowing when the input is exhausted.

Explanation*

++++[->++++++++<]>  #Store <space> at index 1                   
[->+>+<<]           #Move index 1 to index 2 and 3
++++++++++          #Increment index 1 to <newline>
>>                  #Move to index 3
+++++++++++++       #Increment index 3 to <dash>    
>                   #Move to (empty) index 4
+                   #Increment to start the main loop
[                   #Main loop
,                   #Read first number to index 4
[->+>+<<]>>[-<<+>>] #Copy index 4 to index 5 (index 5 can now be altered)
,                   #Read second number (the number pair is now stored at index 5 and 6)
<                   #Move to first number (index 5)
[->-<<<<.>>>]       #Decrement index 5 and 6 and print <space> until index 5 equals zero
>                   #move to second input (index 6)
[-<<<.>>>]          #Decrement index 6 and print <dash> until index 6 equals zero
<<<<<.>>>           #Print <newline> and move to index 4 (original first number)
]                   #End of main loop

*(You won't be able to compile/run this due to the comments)

Rolf ツ

Posted 2015-06-29T13:41:26.047

Reputation: 711

6Brainfuck shorter than Java => world will soon end. – Alex A. – 2015-06-29T19:49:15.477

1The explanation should actually run fine. The only bf commands in there are < and >, and they're perfectly balanced. – undergroundmonorail – 2015-07-05T20:04:46.007

@undergroundmonorail Nice catch, I did not even try to see if they were balanced ;) – Rolf ツ – 2015-07-05T21:32:57.763

8

Pyth, 36 22 19 14 bytes

This is my first Pyth program. Jakube helped golf out 5 bytes!

FNQ<s*V" -"NeN

It expects input in the form [[5,20], [5,20], [2,10], [15,19]].

You can try it online.

Alex A.

Posted 2015-06-29T13:41:26.047

Reputation: 23 761

5

C++14, 69 bytes

[]{int a,b;for(;cin>>a>>b;){cout<<setw(b)<<string(b-a,'-')+'\n';}}();

First time golfing, this was a good problem to start with!

sweerpotato

Posted 2015-06-29T13:41:26.047

Reputation: 2 457

2Don't you need std:: on cin and cout? – Alex A. – 2015-07-04T02:50:49.463

3

Scala, 67 63 59 bytes

(r:Seq[(Int,Int)])⇒for((s,e)←r)(println(" "*s+"-"*(e-s)))

Usage: res0() or res0(Seq(28->35, 34->40, 39->44)) etc.

Thanks gilad for shaving 4 bytes using a for expression!

Jacob

Posted 2015-06-29T13:41:26.047

Reputation: 1 582

3

K, 18 bytes

`0:" -"@{&x,y-x}.'

Expects a list of pairs as input:

  `0:" -"@{&x,y-x}.'(0 7;5 6;3 6)
-------
     -
   ---
  `0:" -"@{&x,y-x}.'(5 20;5 20;2 10; 15 19)
     ---------------
     ---------------
  --------
               ----
  `0:" -"@{&x,y-x}.'()

I unpack each (') tuple using dot-apply (.) so that inside the lambda I have access to the start and end value as x and y, respectively. Then I reassemble these into a (start,length) tuple (x,y-x) and apply "where" (&). This gives me output like so:

  {&x,y-x}.'(0 7;5 6;3 6)
(1 1 1 1 1 1 1
 0 0 0 0 0 1
 0 0 0 1 1 1)

Then I simply have to index into a 2-character array using this ragged matrix (" -"@) and send it all to stdout (0:).

JohnE

Posted 2015-06-29T13:41:26.047

Reputation: 4 632

3

JavaScript (ES6), 63

Edit 3 byte saved thx @apsillers
63 bytes not counting the assignment to F as an anonymous function is allowed.

A function with a variable number of parameters, as requested.
A function with a list of tasks as a single parameter.

Test running the snippet below (being EcmaScript 6, Firefox only)

F=l=>l.map(t=>console.log(' '.repeat(l=t[0])+'-'.repeat(t[1]-l)))

// TEST

// for this test, redefine console.log to have output inside the snippet
console.log = (...x) => O.innerHTML += x + '\n';

console.log('* Empty'); F([]);
console.log('\n* [0,7],[5,6],[3,6]'); F([[0,7],[5,6],[3,6]])
console.log('\n* [5,20],[5,20],[2,10],[15,19]');F([[5,20],[5,20],[2,10],[15,19]]);
<pre id=O></pre>

edc65

Posted 2015-06-29T13:41:26.047

Reputation: 31 086

Save one byte by assigning t[0] to a global (or you can safely assign it to l if you don't want to make a global). Also, the spec allows "a named function or an anonymous function" so I think you could omit the F= in your byte count. – apsillers – 2015-06-29T16:15:56.743

@apsillers I missed the anonymous think. Thanks – edc65 – 2015-06-29T16:23:46.190

2

Ruby: 35 characters

->*t{t.map{|s,e|puts' '*s+?-*(e-s)}

Sample run:

irb(main):001:0> ->*t{t.map{|s,e|puts' '*s+?-*(e-s)}}.call [0,7], [5,6], [3,6]
-------
     -
   ---

Updated to accept multiple two-element arrays, one for each task to display. (I think that is what the updated requirement expects.)

manatwork

Posted 2015-06-29T13:41:26.047

Reputation: 17 865

2

Javascript(ES6), 61/66 chars

My answer is almost similar to the one posted by @edc65 , but with some improvements. As tasks in single array are not allowed(so function would be called like this: a([3,4], [7,15], [0,14], [10, 15])), correct one would be this(66 chars without name assignment):

a=(...x)=>x.map(([c,d])=>console.log(' '.repeat(c)+'-'.repeat(d-c)))

And if one array argument is allowed(so fn call like this: a([[3,4], [7,15], [0,14], [10, 15]])), then it would be(61 char without assignment):

a=x=>x.map(([c,d])=>console.log(' '.repeat(c)+'-'.repeat(d-c)))

zura

Posted 2015-06-29T13:41:26.047

Reputation: 51

1

Jelly, 13 9 bytes

ạ\⁾ -xµ€Y

Try it online!

Takes input as [[5, 20], [5, 20], [2, 10], [15, 19]].

-4 bytes thanks to Erik

ellie

Posted 2015-06-29T13:41:26.047

Reputation: 131

9 bytes – Erik the Outgolfer – 2018-01-28T19:03:31.630

1

APL (Dyalog Classic), 12 bytes

↑('-'\⍨≤∘⍳)/

Try it online!

APL has no varargs, so the arg here is a single Nx2 matrix.

ngn

Posted 2015-06-29T13:41:26.047

Reputation: 11 449

If you can take two arguments (starts and ends) then ↑'-'\⍨¨≤∘⍳¨ – Adám – 2018-01-29T10:32:38.977

challenge author says no

– ngn – 2018-01-29T15:26:33.203

1

JavaScript (ES8), 54 bytes

a=>a.map(([x,y])=>"-".repeat(y-x).padStart(y)).join`
`

Try it online

Shaggy

Posted 2015-06-29T13:41:26.047

Reputation: 24 623

1

R, 117 90 75 bytes

function(y)for(i in 1:ncol(y))cat(" "<y[1,i],"-"<diff(y)[i],"
")
"<"=strrep

Try it online!

Giuseppe golfed at least 29 bytes off my original answer!

The idea is straightforward: print as many " " as necessary followed by as many "-" as required. Input is a 2*L matrix with L the number of pairs. The vectorized function diff is used to get the number of "-".

JayCe

Posted 2015-06-29T13:41:26.047

Reputation: 2 655

1@Giuseppe this is what I get for trying to trying to stick to my original matrix idea while using a for loop... ty! – JayCe – 2018-06-18T16:02:59.213

86 bytes – Giuseppe – 2018-06-18T17:34:45.480

@Giuseppe Transposed y to save a few more :) – JayCe – 2018-06-18T17:52:57.443

Now 1- indexed would save 4

– JayCe – 2018-06-18T17:55:27.783

Nice, use < instead of * and you can get this to 81 bytes

– Giuseppe – 2018-06-19T20:19:38.313

1

PowerShell 3.0, 4836 Bytes

$args|%{" "*$_[0]+"-"*($_[1]-$_[0])}

Thanks to Mazzy for saving 12 with a better way to pass in the list

Old code and explanation:

&{param($b="")$b|%{" "*$_[0]+"-"*($_[1]-$_[0])}}

Takes arguments as a list of tuples, e.g. (5,20),(5,20),(2,10),(15,19). Had to default $b to a value to take care of the empty string because it somehow entered the foreach block when called with no input.

Veskah

Posted 2015-06-29T13:41:26.047

Reputation: 3 580

36 bytes: $args|%{" "*$_[0]+"-"*($_[1]-$_[0])}. Save as get-asciiGantt.ps1. Test script .\get-asciiGantt.ps1 (5,20) (5,20) (2,10) (15,19) – mazzy – 2018-06-19T09:40:57.337

1

VBA (Excel), 99 90 bytes

Using Immediate Window and [A1] as input eg.0-1,2-5

Thanks to @TaylorSott for cutting some bytes.

b=Split([A1]):For x=0To Ubound(b):c=Split(b(x),"-"):?Spc(c(0)-0)String(c(1)-c(0),"-"):Next

remoel

Posted 2015-06-29T13:41:26.047

Reputation: 511

1If you change the input format to being space delimited rather than being comma delimited, you cang chage the first two clauses from a=[A1]:b=Split(a,",") to b=Split([A1]). Also, you can drop the space before the To in the For loop declaration. – Taylor Scott – 2019-02-15T19:34:30.647

Thanks and noted! :D – remoel – 2019-02-18T08:32:24.623

1

Java 8, 280 275 246 204 195 185 180 bytes

void g(String t){for(String s:t.split(",")){String[]a=s.split("->");s="";Integer i;for(i=0;i<i.valueOf(a[0]);i++)s+=" ";for(;i<i.valueOf(a[1]);i++)s+="-";System.out.println(s);};};

A method that takes a comma-seperated input string and prints the resulting ascii Gantt Chart to stdout.

Thanks to durron597 and masterX244 for helping me save 10 bytes

SuperJedi224

Posted 2015-06-29T13:41:26.047

Reputation: 11 342

I think you're allowed to use a method instead. – lirtosiast – 2015-06-30T03:07:50.050

It is allowed iff this is the (or a) way to create an anonymous function in Java8. Is it? – Jacob – 2015-06-30T04:03:12.640

It's the closest thing Java 8 has to such a feature. – SuperJedi224 – 2015-06-30T11:47:38.537

If you do Integer i=0; you can do for(;i<i.parseInt;, saving 8 characters. – durron597 – 2015-06-30T21:43:51.220

I couldn't get it to compile on Ideone, but it appears that it would not accept empty input, as the rules require (t.split(",") would throw an exception). – Nateowami – 2015-07-01T06:01:18.333

@Nateowami: This isn't a full program. – SuperJedi224 – 2015-07-01T12:39:47.847

I realize that, and added boilerplate code. It said something about a missing symbol. Not saying it doesn't compile, just that I failed to. – Nateowami – 2015-07-01T13:49:35.830

@durron i.valueOf() is a bit shorter since Java converts the resulting Integer automatically to int without any code needed (autounboxing greets) – masterX244 – 2015-07-01T14:47:39.253

1

SWI-Prolog, 55 bytes

a([[A,B]|C]):-tab(A),writef("%r",[-,B-A]),nl,C=[];a(C).

Example: a([[5,20],[5,20],[2,10],[15,19]]). outputs

     ---------------
     ---------------
  --------
               ----

Fatalize

Posted 2015-06-29T13:41:26.047

Reputation: 32 976

I'm sorry but the input format in this answer does not meet specifications - each task should be represented in one argument, not in two. (Unless I missed something in SWI-Prolog syntax which I'm not familiar with...) – Jacob – 2015-06-29T14:13:12.000

@Jacob Yeah when rereading your post I figured that and already changed my code to account for it. – Fatalize – 2015-06-29T14:14:00.913

1

Julia, 44 bytes

x->for t=x a,b=t;println(" "^a*"-"^(b-a))end

This creates an anonymous function that accepts an array of tuples as input and prints to STDOUT.

Ungolfed + explanation:

function f(x)
    # Loop over the tasks (tuples) in x
    for t in x
        # Assign a and b to the two elements of t
        a,b = t

        # Print a spaces followed by b-a dashes on a line
        println(" "^a * "-"^(b-a))
    end
end

Examples:

julia> f([(5,20), (5,20), (2,10), (15,19)])
     ---------------
     ---------------
  --------
               ----

julia> f([(0,7), (5,6), (3,6)])
-------
     -
   ---

julia> f([])

Alex A.

Posted 2015-06-29T13:41:26.047

Reputation: 23 761

Sure. Sorry for the inconvenience. – Jacob – 2015-06-29T15:16:41.633

@Jacob: No inconvenience. Nice challenge. :) – Alex A. – 2015-06-29T15:17:04.790

1

Perl: 42 41 characters

Just to have at least one solution with string parsing too.

s!(\d+)->(\d+),?!$"x$1."-"x($2-$1).$/!ge

Sample run:

bash-4.3$ perl -pe 's!(\d+)->(\d+),?!$"x$1."-"x($2-$1).$/!ge' <<< '0->7,5->6,3->6'
-------
     -
   ---

manatwork

Posted 2015-06-29T13:41:26.047

Reputation: 17 865

Actually we already have the straightforward Java answer that parse a string :) Anyway, thanks for this one as well! – Jacob – 2015-06-29T14:49:28.067

Yes, but as I understand that expects comma separated numbers, not the format specified in the question. – manatwork – 2015-06-29T14:53:06.973

1

JavaScript (ES6), 106 85 80 68 bytes

As per the updated requirements, a list of tasks is now acceptable

a=>a.reduce((p,v)=>p+=' '.repeat(z=v[0])+'-'.repeat(v[1]-z)+"\n",'')

Takes zero or more arguments: 80 bytes

(...a)=>{s='';a.map(v=>s+=' '[r='repeat'](z=v[0])+'-'[r](v[1]-z)+"\n");return s}

Original attempt, 106 bytes:

(...a)=>{for(i=-1,s='',r='repeat';a.length>++i;){s+=' '[r](a[i][0])+'-'[r](a[i][1]-a[i][0])+"\n"}return s}

rink.attendant.6

Posted 2015-06-29T13:41:26.047

Reputation: 2 776

If it's ES6, then why not String.repeat()?

– manatwork – 2015-06-29T14:55:16.280

@manatwork Thanks for showing me something new!! Unfortunately for code golf it is actually longer to use that – rink.attendant.6 – 2015-06-29T14:59:40.167

Indeed, that two dimensional a not really helps. I had in mind something like ()=>{for(i=0,s='';a=arguments[i++];)s+='_'.repeat(a[0])+'-'.repeat(a[1]-a[0])+"\n";return s}. – manatwork – 2015-06-29T15:11:33.870

r='repeat' ? ... for 2 times? nah! a=>a.reduce((p,v)=>p+=' '.repeat(z=v[0])+'-'.repeat(v[1]-z)+"\n",'') – edc65 – 2015-06-29T16:01:46.773

1There is no output. Return value does not matter, your code must print the timeline on STDOUT. (and would be shorter too) – edc65 – 2015-06-29T16:03:32.943

1

Haskell, 76 bytes

(#)=replicate
f i=putStr$g=<<(read$'[':i++"]")
g(s,e)=s#' '++(e-s)#'-'++"\n"

Input format is a string of comma separated tuples, e.g. "(1,2),(3,4)".

Usage examples:

*Main> f "(1,2),(3,4)" 
  -
    -

*Main> f "(0,7),(5,6),(3,6)" 
-------
     -
   ---

How it works: for input parsing I enclose the input string in [ and ] and use Haskell's native read function for lists of integer tuples. The rest is easy: for each tuple (s,e) take s spaces followed by e-s dashes followed by a newline and concatenate all into a single string. Print.

Haskell, 59 bytes

with relaxed input format:

(#)=replicate
f=putStr.(g=<<)
g(s,e)=s#' '++(e-s)#'-'++"\n"

Now it takes a list of tuples, e.g f [(0,7),(5,6),(3,6)].

Works as described above, but without input parsing.

nimi

Posted 2015-06-29T13:41:26.047

Reputation: 34 639

1

C: 108 bytes

void g(int*l){for(int c=0;*l>=0;c=!c,l++){if(!c)l[1]-=*l;while(l[0]-->0)putchar(c?45:32);c?putchar(10):0;}}

Ungolfed:

void gantt(int*l) {
    for (int c = 0; *l >= 0; c = !c, l++) {
        if (!c) l[1] -= *l;
        while (l[0]-- > 0) putchar(c? 45 : 32);
        c? putchar(10) : 0;
    }
}

Takes as a parameter a list of integers terminated by -1. For example:

int list[] = {
    28, 35,
    34, 40,
    39, 44,
    -1
};
gantt(list);

It uses c to toggle between writing spaces and dashes.

Functino

Posted 2015-06-29T13:41:26.047

Reputation: 417

1Make c static - you can drop its type (it will be int) and initialization (it will be zero). *l>=0 is the same as *l+1 which is shorter. c&&putchar is shorter than ternary. If you replace c=!c with c^=13 (+1 byte) you can change c?45:32 to 32+c (-3 bytes). Move c flip from for to the end of loop: (c^=13)||putchar(10);. c;void g(int*l){for(;*l+1;l++){l[1]-=c?0:*l;while(l[0]--)putchar(32+c);(c^=13)||putchar(10);}} - 94 bytes. – aragaer – 2015-06-30T12:37:31.473

1

Java, 187 181 197 183 101 bytes

void g(int[][]g){for(int[]i:g)for(int j=0;j<i[1];System.out.print(j++<i[0]?" ":j==i[1]?"-\n":"-"));}

Ungolfed (sort of):

void g(int[][] g){
    for(int[] i : g)
        for(int j = 0; j < i[1]; System.out.print(j++ < i[0] ? " " : j == i[1] ? "-\n" : "-"));
}

Accepts input as 2d array of ints. Thanks to masterX244 for pointing out that this is allowed by the rules.

Nateowami

Posted 2015-06-29T13:41:26.047

Reputation: 131

you can shorten the loops if you use the 3rd bulletpoint of the current question version and varargs for the input – masterX244 – 2015-07-01T14:37:30.793

@masterX244 Thanks, I missed that. Seems to me like cheating to have it pre-parsed, but if cheating is allowed... whatever. I'll update it when I have time. – Nateowami – 2015-07-02T01:06:35.880

0

J, 21 bytes

(' -'#~{.,-~/)"1 ::''

ungolfed

(' -' #~ {. , -~/)"1 ::''

This is essentially just J's copy verb #, but its we're copying the space character head of list {. number of times, and the hyphen character "2nd list element minus 1st list element" number of times: -~/. Sadly this forces us to have to specify the rank "1 explictly, and we need to use Adverse :: to handle the empty case.

Try it online!

Jonah

Posted 2015-06-29T13:41:26.047

Reputation: 8 729

0

Japt -R, 14 10 9 bytes

If the character used for the timeline can be anything we want then one byte can be saved replacing -<space> with Ê, which will use l instead of dashes.

®Ìç- hZÎî

Try it


Explanation

®             :Map over each sub-array Z
 Ì            :  Get the last element of Z
  ç-          :  Repeat "-" that many times
     h        :  Set the characters starting at index 0 to
      ZÎ      :    Get the first element of Z
        î     :    Repeat <space> that many times
              :Implicitly join with newlines and output

Shaggy

Posted 2015-06-29T13:41:26.047

Reputation: 24 623

0

K (ngn/k), 13 bytes

{" -"@&-':x}'

Try it online!

{ } function with argument x

{ }' apply to each - in this case to each pair of numbers from the input

-': subtract each prior - transform (a;b) into (a;b-a)

& "where" - transform (a;b-a) into a list of a zeroes followed by b-a ones

" -"@ use as indices in " -"

ngn

Posted 2015-06-29T13:41:26.047

Reputation: 11 449

0

Perl 5 with -054naF/->/ -M5.010, 24 bytes

say"-"x$F[1]."\x0d".$"x"@F"

Try it online!

Only works in terminal because of the use of "\x0d" to overwrite the -s with s, but here's a cast of the script in action.

To recreate the script, use the below hexdump:

00000000: 7361 7922 2d22 7824 465b 315d 2e22 0d22  say"-"x$F[1]."."
00000010: 2e24 2278 2240 4622                      .$"x"@F"

Dom Hastings

Posted 2015-06-29T13:41:26.047

Reputation: 16 415

0

VBA, 75 bytes

A declared routine, f(a), which takes input as an array of arrays, and outputs to the console.

Sub f(a)
For Each t In a
Debug.?Spc(t(0));String(t(1)-t(0),45)
Next
End Sub

Example I/O

f Array(Array(28,35),Array(34,40),Array(39,44))
                            -------
                                  ------
                                       -----

Taylor Scott

Posted 2015-06-29T13:41:26.047

Reputation: 6 709

0

05AB1E, 12 bytes

ε`sDð×?-'-×,

Try it online!

Takes input in the form [[5,20],[5,20],[2,10],[15,19]].

Explanation:

ε`sDð×?-'-×,    IMPLICITLY INPUT ARRAY OF ARRAYS
ε               For each array [a, b] in input:
 `sD                Push stack b, a, a (a on top)
    ð               Push space to stack : [b, a, a, ' ']
     ×?             Print a spaces without newline, stack: [b, a]
       -'-×,        Print (b - a) dashes with newline, stack empty
                Implicit end of loop

Geno Racklin Asher

Posted 2015-06-29T13:41:26.047

Reputation: 466

0

Tcl, 74 bytes

proc G L {lmap s\ e $L {puts [format %$e\s [string repe - [expr $e-$s]]]}}

Try it online!


Tcl, 76 bytes

proc G L {lmap s\ e $L {puts [format %$e\s [string repeat - [expr $e-$s]]]}}

Try it online!

Tcl, 82 bytes

proc G L {lmap s\ e $L {puts [string repeat \  $s][string repeat - [expr $e-$s]]}}

Try it online!

sergiol

Posted 2015-06-29T13:41:26.047

Reputation: 3 055

0

Perl 6, 28 bytes

*.map: (' ','-'Zx*).join.say

Try it online!

Input is a list of 2-element lists:

(<0 7>,<5 6>,<3 6>)

Essentially we are using the 'b' x 3 = 'bbb' operator x between the lists ' ', '-' and * (the line input as a list), zipped via Z, hence the combined operator Zx.

In p6 golfing this seems... suboptimal.

Phil H

Posted 2015-06-29T13:41:26.047

Reputation: 1 376

0

Momema, 75 bytes

m00*-8m+1-=+1*01+*-8-*0s0s+1-=*00+*0-1-9 32s1d0d+1-=*1 1+*1-1-9 45d1-9 10m1

Try it online!

Ungolfed:

main 0
0    *-8      # read user input
main +1-=+1*0 # terminate if zero

    1     +*-8-*0 # calculate number of '-' to print

    space 0
    space +1-=*0  # stop?
        0  +*0-1      # decrement counter
        -9 32         # print ' '
    space  1      # go back to start
    dash  0
    dash  +1-=*1  # stop?
        1  +*1-1      # decrement counter
        -9 45         # print '-'
    dash  1

    -9 10

main 1        # go to beginning

Esolanging Fruit

Posted 2015-06-29T13:41:26.047

Reputation: 13 542

0

Canvas, 10 bytes

{┤∔α ×P-×p

Try it here!

dzaima

Posted 2015-06-29T13:41:26.047

Reputation: 19 048

0

CoffeeScript, 104 82, 65 bytes

List of tasks (ES6): 65 bytes

(a)->a.map (v)->console.log ' '.repeat(v[0])+'-'.repeat v[1]-v[0]

List of tasks (ES5 variant): 82 bytes

(a)->a.map (v)->j=-1;s='';s+=(if j<v[0]then' 'else'-') while++j<v[1];console.log s

Zero or more arguments: 104 bytes

()->[].slice.call(arguments).map((v)->j=-1;s='';s+=(if j<v[0]then' 'else'-')while++j<v[1];console.log s)

Unminified:

() -> [].slice.call(arguments).map( # convert to array-like arguments to array and loop
 (v) ->
  j = -1 # counter
  s = '' # initialize string
  s += (if j < v[0] then ' ' else '-') while ++j < v[1]
  console.log s # print to STDOUT
)

rink.attendant.6

Posted 2015-06-29T13:41:26.047

Reputation: 2 776

Not sure from where to where is the JavaScript, CoffeeScript and ECMAScript in your answers, but in ECMAScript you can use Array.from(arguments) instead of [].slice.call(arguments). – manatwork – 2015-06-29T16:42:44.127

@manatwork As you can see in my answers (both ES5 and ES6, in CoffeeScript) addressing the changed requirement allowing a list of tasks, I don't need to reference arguments any more. – rink.attendant.6 – 2015-06-29T16:56:42.390

0

PHP, 94 91 bytes

Takes a list of tasks (e.g. [[5,20],[5,20],[2,10],[15,19]]). Thanks @IsmaelMiguel for the reminder of variable function names.

function x($a){$r=str_repeat;foreach($a as$v){echo$r(' ',$v[0]).$r('-',$v[1]-$v[0])."\n";}}

Original attempt: 94 bytes

function x($a){foreach($a as$v){echo str_repeat(' ',$v[0]).str_repeat('-',$v[1]-$v[0])."\n";}}

rink.attendant.6

Posted 2015-06-29T13:41:26.047

Reputation: 2 776

73 bytes, PHP4: $R=str_repeat;foreach($G as$v)echo$R(' ',$v[0]),$R('-',$v[1]-$v[0]),'\n'; (replace the \n with a real newline). For this to work, you need to send an array on the key $G, over POST/GET/SESSION/COOKIE... – Ismael Miguel – 2015-06-29T19:04:54.223

@IsmaelMiguel According to the question, the input needs to come as an argument or from STDIN. – rink.attendant.6 – 2015-06-29T19:15:51.637

Does GET parameters count? And I think that GETuses STDIN. – Ismael Miguel – 2015-06-29T19:22:42.513

0

C++, 112*

#include<iostream>
#include<string>
int a(){int a,b;while(cin>>a>>b){cout<<string(a,' ')+string(b-a,'-')+"\n";}}

*~~or 76 depending on whether you count the include statements~~ just completely wrong... Didn't include std:: as pointed out in comments

Test

Input: 5 20 5 20 2 10 15 19

Output:

     ---------------
     ---------------
  --------
               ----

sudo rm -rf slash

Posted 2015-06-29T13:41:26.047

Reputation: 1 076

Don't you need include files for this? – Reto Koradi – 2015-06-29T19:27:40.630

Yes iostream and string... Should I add those to my code? – sudo rm -rf slash – 2015-06-29T19:32:47.877

I only started participating here relatively recently, so I'm not much of a rules expert. But it was my understanding that even if only a function is required, you still need to count everything needed to compile the function. You may want to ask one of the "authorities". – Reto Koradi – 2015-06-29T19:40:57.230

I'll just put it in – sudo rm -rf slash – 2015-06-29T19:41:56.693

Your input method of space separated values is just fine. And it's my understanding (though I'm often wrong so take it with a grain of salt) that you don't need the #includes for functions, but I'll defer that to someone else. – Alex A. – 2015-06-29T19:56:16.500

Thanks re input. I think the way it is now is pretty safe as far as the byte count goes – sudo rm -rf slash – 2015-06-29T20:01:34.147

Don't you need std:: before string? – sergiol – 2018-06-19T20:36:35.400

@sergiol yeah I think you're right – sudo rm -rf slash – 2018-06-19T20:42:17.173

0

PHP, 89 characters (function body)

function gantt($x){array_walk($x,function($a){echo str_pad(str_repeat('-',$a[1]-$a[0]),$a[1],' ',0)."\n";});}

I was going to go for reading strings, but as a lot of the entries were taking arrays of integer pairs, I figured I would follow suit for the sake of brevity.

For each tuple $a in array $x I echo a string of dashes repeated $a[1] - $a[0] times, padded up to the larger number $a[1] with spaces. Then the obligatory newline.

JPMC

Posted 2015-06-29T13:41:26.047

Reputation: 161

You can make your function name just a single letter to save a few bytes. or better yet, if PHP supports anonymous functions, just omit a function name altogether. – Alex A. – 2015-06-29T17:43:59.567

1Oh I see now what you mean by "function body." You have to count the entire function definition in your score, not just the innards. – Alex A. – 2015-06-29T17:47:53.967

1printf() seems shorter than echo+str_pad(): function gantt($x){array_map(function($a){printf("%$a[1]s␊",str_repeat('-',$a[1]-$a[0]));},$x);} (The ␊ in the code is for a literal newline: just wrap your code there.) – manatwork – 2015-06-29T17:55:04.237

1Actually a good old foreach is better: function g($x){foreach($x as$a)printf("%$a[1]s␊",str_repeat('-',$a[1]-$a[0]));} And this is 79 characters including everything. – manatwork – 2015-06-29T17:58:09.730

@AlexA. ah, I've seen golfs where people count or discount function headers. I wasn't sure what to go for, hence why I specified what count was what. – JPMC – 2015-06-29T20:13:52.167

@manatwork Good suggestion! I was going to ask why you didn't use that as an answer, but I saw your Ruby submission. Thanks. I'll edit my submission when I get a chance and be sure to credit you. – JPMC – 2015-06-29T20:15:34.570

0

Gema: 47 characters

<D>-\><D><y>=@left{$1;}@repeat{@sub{$2;$1};-}\n

Sample run:

bash-4.3$ gema '<D>-\><D><y>=@left{$1;}@repeat{@sub{$2;$1};-}\n' <<< '0->7,5->6,3->6'
-------
     -
   ---

manatwork

Posted 2015-06-29T13:41:26.047

Reputation: 17 865

0

PostgreSQL: 160 characters

create function g(int[])returns text as
$$select string_agg(lpad(repeat('-',$1[x][2]-$1[x][1]),$1[x][2]),chr(10))from generate_subscripts($1,1)x$$
language sql;

Sample run:

manatwork=# create function g(int[])returns text as
manatwork-# $$select string_agg(lpad(repeat('-',$1[x][2]-$1[x][1]),$1[x][2]),chr(10))from generate_subscripts($1,1)x$$
manatwork-# language sql;
CREATE FUNCTION

manatwork=# select g(array[[0,7],[5,6],[3,6]]);
-------
     -
   ---

manatwork

Posted 2015-06-29T13:41:26.047

Reputation: 17 865