Etant donné le chemin d' artiste et le temps qu'il m'a fallu pour le traverser, dites-moi si je conduisais trop vite.
Unités
La distance est dans l'unité arbitraire de d
. Le temps est dans l'unité arbitraire de t
.
La route
Voici une route simple:
10=====
Le 10
moyen 10 d
per t
. C'est la limite de vitesse pour la route. La route a 5 =
s, donc elle d
est 5. Par conséquent, si je traverse cette route dans 0.5t
, je suis allé 10 d
par t
, parce que 5 / 0,5 = 10. La limite de vitesse de cette route est de 10, donc je suis resté dans la limite de vitesse.
Mais si je traverse cette route en 0,25 t
, je suis passé à 20 d
% t
, car 5 / 0,25 = 20. La limite de vitesse de cette route est de 10, donc j’ai dépassé la limite de vitesse.
Exemples et calculs
Notez que l'entrée 1 correspond au temps que j'ai pris pour parcourir la route et l'entrée 2 à la route elle-même.
Voici une route complexe:
Input 1: 1.5
Input 2: 5=====10=====
Le plus rapide que j'aurais pu (légalement) aller sur la première route (les 5 premières =
secondes) est de 5 d
% t
. Étant donné que 5 (distance) divisé par 5 (limite de vitesse) est égal à 1, le plus rapide que j'aurais pu parcourir sur cette route est 1 t
.
Sur la prochaine route, la limite de vitesse est de 10 et la distance est également de 5, le plus rapide que je puisse traverser est de 0,5 (5/10). Le total des temps minimaux donne 1,5, ce qui signifie que je suis allé exactement à la limite de vitesse.
Note: Je sais, j'aurais peut-être été très rapide sur une route et très lent sur une autre et je croisais toujours en 1,5, mais supposons le meilleur ici.
Un dernier exemple:
Input 1: 3.2
Input 2: 3.0==========20===
La première route a une longueur de 10 km et une limite de vitesse de 3, donc le temps minimum est de 3,333333 ... (10/3).
La deuxième route est longue de 3 et a une limite de vitesse de 20, donc le temps minimum est de 0,15 (3/20).
Totaliser les temps en 3.483333333 ... Je l'ai croisé en 3.2, donc je devais être rapide quelque part.
Remarques:
- Vous devez indiquer une valeur distincte si je suis en train d’accélérer, et une autre valeur différente si ce n’est peut-être pas le cas.
- Votre programme ou fonction peut nécessiter une entrée ou une sortie pour avoir une fin de ligne, mais veuillez l'indiquer dans votre soumission.
- Votre première entrée sera ma vitesse. Ce sera un float positif, un entier ou une chaîne.
- Votre deuxième entrée sera la route. Cela correspondra toujours à la regex
^(([1-9]+[0-9]*|[0-9]+\.[0-9]+)=+)+\n?$
. Vous pouvez tester les entrées potentielles ici si vous êtes intéressé. - Vous pouvez entrer une entrée dans 2 paramètres d’une fonction ou d’un programme, dans 2 fichiers séparés, à partir de STDIN deux fois, ou à partir d’une chaîne séparée par des espaces passée à STDIN, une fonction, un fichier ou un paramètre de ligne de commande.
- Si vous le souhaitez, vous pouvez modifier l'ordre des entrées.
- Des questions? Demandez ci-dessous en commentaires et code-golf ing heureux !
^(([1-9]+[0-9]*|(?!0\.0+\b)[0-9]+\.[0-9]+)=+)+\n?$
. (It would have been cleaner with a lookbehind, but then it would need .Net engine)Réponses:
05AB1E,
2422 bytesReturns 1 when undoubtedly speeding and 0 otherwise.
Saved 2 bytes thanks to carusocomputing.
Try it online!
-§'-å
shouldn't have to be more than a simple comparison, but for some reason neither›
nor‹
seem to work between the calculated value and the second input.Explanation
Using
3.0==========20===, 3.2
as examplela source
'=¡õK¹S'=QJ0¡õK€g/O-0.S
for 23 bytes.S
works, OK. That doesn't return 2 unique values though as it will return 0 when you've done exactly the speed limit.a > b
operator is casting to integer before the comparison between a float and an int. It's very odd indeed... I did get it down to 22 bytes though:'=¡€Þ¹S'=Q.¡O0K/O-§'-å
.g>s/
}O-§'-å at 23 with 2 return values. Maybe there is some improvement to be made there still? I Don't see what though. That last comparison really screws us up.Python 2, 71 bytes
Try it online!
Python's dynamic type system can take quite some abuse.
Splitting the input string
s.split('=')
turnsk
equal signs intok-1
empty-string list elements (except at the end, where one must be cut off). For example,The code iterates over these elements, updating the current speed
s
each time it sees a number. The update is done ass=float(c or s)
, where ifc
is a nonempty string, we getfloat(c)
, and otherwisec or s
evaluates tos
, wherefloat(s)
just keepss
. Note thatc
is a string ands
is a number, but Python doesn't require doesn't require consistent input types, andfloat
accepts either.Note also that the variable
s
storing the speed is the same one as taking the input string. The string is evaluated when the loop begins, and changing it within the loop doesn't change what is iterated over. So, the same variable can be reused to save on an initialization. The first loop always hasc
as a number, sos=float(c or s)
doesn't care abouts
's initial role as a string.Each iteration subtracts the current speed from the allowance, which starts as the speed limit. At the end, the speed limit has been violated if this falls below
0
.la source
Python 3, 79 bytes
Try it online!
For example, the input
3.0==========20===
is converted to the stringand evaluated, and the result is compared to the input speed. Each
-~
increments by1
. I'm new to regexes, so perhaps there's a better way, like making both substitutions at once. Thanks to Jonathan Allan for pointing out how to match on all but the=
character.la source
"0.5=20==="
, the output will beNone
regardless of the time input.([\d|.]+)
may fix it.Javascript (ES6), 63 bytes
Usage
Assign this function to a variable and call it using the currying syntax. The first argument is the time, the second is the road.
Explanation
Matches all consecutive runs of characters that are not equal signs followed by a run of equal signs. Each match is replaced by the result of the inner function, which uses two arguments: the run of equal signs (in variable
d
) and the number (variablec
). The function returns the length of the road devided by the number, prepended by a +.The resulting string is then evaluated, and compared against the first input.
Stack Snippet
la source
GNU C, 128 bytes
Handles non-integer speed limits also.
#import<stdlib.h>
is needed for the compiler not to assume thatatof()
returns anint
.t<s-.001
is needed to make the exact speed limit test case to work, otherwise rounding errors cause it to think you were speeding. Of course, now if the time is1.4999
instead of1.5
, it doesn't consider that speeding. I hope that's okay.Try it online!
la source
Perl 5, 43 bytes
42 bytes of code +
-p
flag.Try it online!
For each group of digit followed by some equal signs (
[^=]+(=+)
), we calculate how much time is needed to cross it (number of equals divided by the speed:(length$1)/$&
) and sum those times inside$t
. At the end, we just need to check that$t
is less than the time you took to cross it ($_=$t < <>
). The result will be1
(true) or nothing (false).la source
Mathematica, 98 bytes
Pure function taking two arguments, a number (which can be an integer, fraction, decimal, even
π
or a number in scientific notation) and a newline-terminated string, and returningTrue
orFalse
. Explanation by way of example, using the inputs3.2
and"3==========20===\n"
:#2~StringSplit~"="
produces{"3","","","","","","","","","","20","","","\n"}
. Notice that the number of consecutive""
s is one fewer than the number of consecutive=
s in each run.//.{z___,a_,b:Longest@""..,c__}:>{z,(Length@{b}+1)/ToExpression@a,c}
is a repeating replacement rule. First it setsz
to the empty sequence,a
to"3"
,b
to"","","","","","","","",""
(the longest run of""
s it could find), andc
to"20","","","\n"
; the command(Length@{b}+1)/ToExpression@a
evaluates to(9+1)/3
, and so the result of the replacement is the list{10/3, "20","","","\n"}
.Next the replacement rule sets
z
to10/3
,a
to"20"
,b
to"",""
, andc
to"\n"
. Now(Length@{b}+1)/ToExpression@a
evaluates to(2+1)/20
, and so the result of the replacement is{10/3, 3/20, "\n"}
. The replacement rule can't find another match, so it halts.Finally,
Tr[...]-"\n"
(it saves a byte to use an actual newline between the quotes instead of"\n"
) adds the elements of the list, obtaining10/3 + 3/20 + "\n"
, and then subtracts off the"\n"
, which Mathematica is perfectly happy to do. Finally,<=#
compares the result to the first input (3.2
in this case), which yieldsFalse
.la source
"1+2====3.456====π=====\n"
even.Jelly, 27 bytes
Try it online!
Note: assumes that the regex given in the question should be such that a speed limit cannot be
0.0
,0.00
, etc. - just like it cannot be0
(confirmed as an unintentional property).How?
la source
0.0
since I filter out values that evaluate as0
in the code to pull out the speed limits.Python 3, 90 bytes
Outputs
True
if you're speeding,False
if you might not be. Does not require (but will work with) trailing newline.Despite it not looking like it would, it correctly handles floats in both input time and speed limits, because the regex is just used to seperate the road segments.
la source
MATL,
3130 bytesInputs are: a string (speed limits and roads), then a number (used speed). Output is
1
if undoubtedly speeding,0
if not.Try it online!
Explanation with example
Consider inputs
'3.0==========20==='
and3.2
.la source
APL, 41 bytes
This takes the road as a string as its right argument, and the time taken as its left argument, and returns
1
if you were speeding and0
if not, like so:Explanation:
X←⍵='='
: store inX
a bit vector of all positions in⍵
that are part of the road.X≠¯1⌽X
: mark each position ofX
that is not equal to its right neighbour (wrapping around), giving the positions where numbers and roads startY←⍵⊂⍨
: split⍵
at these positions (giving an array of alternating number and road strings), and store it inY
.Y⊂⍨2|⍳⍴Y
: split upY
in consecutive pairs.{(≢⍵)÷⍎⍺}/¨
: for each pair, divide the length of the road part (≢⍵
) by the result of evaluating the number part (⍎⍺
). This gives the minimum time for each segment.+/
: Sum the times for all segments to get the total minimum time.⍺<
: Check whether the given time is less than the minimum or not.la source
TI-Basic,
168165 bytesInput is the road as
Str0
and the time asT
. Make sure to precede the road with a quote, egStr0=?"14========3===
.Output is 0 if speeding, 1 if possibly not speeding.
la source
Bash, 151 bytes
Running as (for example)
$ bash golf.sh .5 10=====
:Explanation
Enable bash's extended pattern-matching operators and assign the road to a variable
r
.Loop until
r
is empty. Setf
tor
with all equal signs removed from the end, using the%%
parameter expansion and the+()
extended globbing operator.Assign to
s
a running sum of the minimum times for each road segment. This can be re-written (perhaps slightly) more readably as:Basically what's going on here is we're using a here-string to get the
dc
command to do math for us, since bash can't do floating-point arithmetic by itself.9k
sets the precision so our division is floating-point, andp
prints the result when we're done. It's a reverse-polish calculator, so what we're really calculating is${f##*=}
divided by$[${#r}-${#f}]
, plus our current sum (or, when we first run through ands
hasn't been set yet, nothing, which gets us a warning message on stderr aboutdc
's stack being empty, but it still prints the right number because we'd be adding to zero anyway).As for the actual values we're dividing:
${f##*=}
isf
with the largest pattern matching*=
removed from the front. Sincef
is our current road with all the equal signs removed from the end, this means${f##*=}
is the speed limit for this particular stretch of road. For example, if our roadr
were '10=====5===', thenf
would be '10=====5', and so${f##*=}
would be '5'.$[${#r}-${#f}]
is the number of equal signs at the end of our stretch of road.${#r}
is the length ofr
; sincef
is justr
with all the equal signs at the end removed, we can just subtract its length from that ofr
to get the length of this road section.Remove this section of road's speed limit from the end of
f
, leaving all the other sections of road, and setr
to that, continuing the loop to process the next bit of road.Test to see if the time we took to travel the road (provided as
$1
) is less than the minimum allowed by the speed limit. This minimum,s
, can be a float, so we turn todc
again to do the comparison.dc
does have a comparison operator, but actually using it ended up being 9 more bytes than this, so instead I subtract our travel time from the minimum and check to see if it's negative by checking if it starts with a dash. Perhaps inelegant, but all's fair in love and codegolf.Since this check is the last command in the script, its return value will be returned by the script as well: 0 if possibly speeding, 1 if definitely speeding:
la source
Python 3.6, 111 bytes
My first code golf!
Try it online!
re.split('(=+)',b)[:-1]
Splits the road by chunks of=
.It then iterates over the result, using
try:s=float(c)
to set the current speed limit if the current item is a number orexcept:t+=len(c)/s
to add the time to traverse this section of road to the cumulative total.Finally it returns the time taken to the fastest possible time.
la source
PHP5
207202 bytesFirst effort at a code golf answer, please go easy on me. I'm sure one of you geniuses will be able to shorten this significantly, any golfing tips are welcome.
Invoke with
Returns true if you have been under the speed limit, false otherwise
la source
Dyalog APL, 27 bytes
<∘(+/(⍎'='⎕r' ')÷⍨'=+'⎕s 1)
'=+'⎕s 1
is a function that identifies stretches of'='
with a regex and returns a vector of their lengths (⎕s
's right operand 0 would mean offsets; 1 - lengths; 2 - indices of regexes that matched)'='⎕r' '
replaces'='
s with spaces⍎'='⎕r' '
executes it - returns a vector of speeds÷⍨
in the middle divides the two vectors (⍨
swaps the arguments, so it's distance divided by speed)+/
is sumeverything so far is a 4-train - a function without an explicit argument
<∘
composes "less than" in front of that function; so, the function will act only on the right argument and its result will be compared against the left argumentla source
F# (165 bytes)
I'm still new to F#, so if I did anything weird or stupid, let me know.
la source
C# method (
137122 bytes)Requires
using System.Linq
adding 19 bytes, included in the 122:Expanded version:
The
road
string is split on the=
character. Depending on whether a string is the resulting array is empty, the aggregate function sets thepace
variable for the segment (denoting the time it takes to travel a single=
) and subtracts it from the time supplied. This will do one too many substractions (for the final road segment), so instead of comparing to0
, we compare to-pace
la source
R, 100 bytes
Try it online!
Returns
TRUE
for unambiguously speeding values,FALSE
for possibly unspeedy ones.la source
PowerShell, 71 bytes
Try it online!
Test script:
Output:
Explanation:
5=====10=====
, swaps elements, adds brackets and operators+(=====)/5+(=====)/10
=
with+1
:+(+1+1+1+1+1)/5+(+1+1+1+1+1)/10
la source