Wakat czy brak wakatu?


17

Wszyscy widzieliśmy znaki na motelach informujące nas, czy jest wolne miejsce, czy nie:

Zazwyczaj będą one na stałe zapalone litery VACANCY i zaświecą się litery NO , jeśli w motelu nie będzie miejsca.

Wyzwanie

Przeciętny motel w USA ma 200 pokoi.

Napisz program / funkcję, która przyjmuje jako liczbę całkowitą T (dla zajętych pomieszczeń).
Twój program wyświetli słowa NO VACANCY. Litery VACANCYzostaną wydrukowane na czerwono.
Jeśli T ≥ 200, litery NOzostaną również wydrukowane na czerwono.

Na przykład, zakładając, że a.outjest to twój program i argument „input” = argument wiersza poleceń: (wpisałem literę, a mój system ignoruje wielkość liter).
enter image description here

Zasady

  • Twój program / funkcja musi wyświetlać (lub, jeśli lambda, zwraca ) dokładny ciąg NO VACANCY, w tym wielkość liter.
  • Twój program / funkcja może ustawić tylko kolor pierwszego planu tekstu na czerwony, a nie tło.
  • Jeśli chcesz, możesz użyć kodów ucieczki ANSI, aby wydrukować czerwony kolor - \x1b[31mbędzie działać.
  • Twój program / funkcja może nie zmienić koloru tekstu powłoki po jej zakończeniu.
  • Twój program / funkcja musi zakończyć się normalnie.
  • Twój program / funkcja musi drukować tylko na standardowe wyjście.
  • Twój program / funkcja musi używać domyślnego koloru tła powłoki / terminala / IDE. (Jeśli zdecydujesz się na wyjście graficzne, możesz wybrać dowolny kolor, z wyjątkiem czerwonego).
  • Jeżeli T ≤ 200, litery zNO muszą być wydrukowane w domyślnym kolorze pierwszego planu powłoki / terminala / IDE. (Jeśli zdecydujesz się na wyjście graficzne, ponownie możesz wybrać dowolny kolor)
  • Jeśli z jakiegoś powodu domyślny kolor pierwszego planu / tła powłoki / terminala / IDE jest czerwony, musisz wydrukować na czarnym tle i domyślnym białym planie.
  • Jeśli zdecydujesz się użyć wyjścia graficznego, czerwonego można używać tylko wtedy, gdy jest określony w programie (np. Kolor tła lub domyślny kolor tekstu może nie być czerwony).

Zwycięzca

Jak zwykle w przypadku , wygrywa najkrótszy program! Punkty Brownie za wynik graficzny.
Przyjmę najkrótszą odpowiedź za tydzień. Miłej gry w golfa!

Tabela liderów

var QUESTION_ID=123146,OVERRIDE_USER=61563;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>


2
Występuje sprzeczna zasada: na zrzucie ekranu i powyżej napisano, że NIE należy drukować na czerwono „If T ≥ 200”. Później mówisz, aby drukować w domyślnym kolorze „If T ≤ 200”
Arc676

2
@ Arc676 Ups. Cóż, logicznie rzecz biorąc, jeśli hotel ma 200 pokoi, to musi być to pierwszy poprawny opis.
Ørjan Johansen

3
Aby uzyskać dodatkowy kredyt, zrób to dla hotelu Hilbert, który ma nieskończoną liczbę pokoi.
David Conrad

Czy te dane wyjściowe są prawidłowe: i.imgur.com/221Qxgj.png ?
sergiol,

@sergiol Tak, w porządku.
MD XF

Odpowiedzi:


8

Galaretka , 29 26 bajtów

<200o-“NO“ɓ31m”m“=ȤŻ»Œu“ɓm

Używa <CSI>( 0x9b ), który jest krótszy niż <ESC>[( 0x1b 0x5b ).

Resetuje kolor pierwszego planu za pomocą <CSI>mzamiast <CSI>0m, jako 0 jest niejawne.

Weryfikacja

Należy pamiętać, że emulator terminala (np. Konsole) musi być ustawiony na ISO 8859-1 lub podobny.

screenshot

Jak to działa

<200o-“NO“ɓ31m”m“=ȤŻ»Œu“ɓm  Main link. Argument: n (integer)

<200                        Compare with 200, yielding 1 if true, 0 if not.
    o-                      Logical OR -1; map 0 to -1 (and 1 to 1).
      “NO“ɓ31m”             Yield ["NO", "\x9b31m"].
               m            Take the list "modulo" 1 or -1, keeping it as is for 1,
                            reversing it for -1.
                “=ȤŻ»       Implicitly print the previous result and yield the
                            string " vacancy". This is achieved by indexing into
                            Jelly's in-built dictionary.
                     Œu     Convert to uppercase.
                       “ɓm  Implicitly print the previous result and yield the
                            string "\x9bm", which is printed on exit.

11

JavaScript (ES6), 60 bajtów

(Otwórz konsolę przeglądarki podczas uruchamiania fragmentu, aby zobaczyć kolorowy wynik).

screenshot

f=
n=>console.log((n>199?'%cNO':'NO%c')+' VACANCY','color:red')
<input oninput=f(this.value)>


1
NO%c VACANCY color:red?
MD XF

1
@MDXF sprawdź swoją konsolę przeglądarki. emulator konsoli urywków go nie obsługuje.
nderscore

2
Och, dobry chwyt. +1
MD XF

2
Standardowe reguły JS pozwalają znacznie to skrócić. Usuń, console.log()ponieważ reguły określają, że zwroty są w porządku, nie musisz również definiować funkcji.
MayorMonty

4
@MayorMonty to rozwiązanie korzysta z funkcji console.log do tworzenia kolorowego tekstu, więc dziwnie byłoby go nie uwzględniać.
nderscore

8

Ruby (terminal w stylu * nix), 54 48 45 44 43 bajty

1 bajt zapisany dzięki Value Ink

oznacza dosłowny bajt esc (ASCII 27)

->x{"#{x>199?"␛[31m":p}NO␛[31m VACANCY␛[m"}

Port mojej odpowiedzi na python, to bajt krótszy o kilka bajtów. Jestem początkującym w ruby ​​golfie, ale chętnie się uczę, więc doceniam opinie.


1
->x{"#{x>199?"␛[31m":p}NO␛[31m VACANCY␛[m"}zapisuje bajt. Sztuczka polega na tym, że w interpolacji ciągów "#{nil}"zostanie oceniony na pusty ciąg i pmożna go użyć jako zamiennika nil.
Wartość tuszu

6

Python 3 (terminal w stylu * nix), 55 54 bajtów

lambda x:"\033[31m"*(x-199)+"NO\033[31m VACANCY\033[m"

This uses ANSI escape codes. \033[31m Makes the terminal red, if x is less than 200 we will start with one making NO red, otherwise we will have one after NO making it red anyway. When we are done \033[m clears the color from the terminal.


The multiplication of the color string instead of a condition is brilliant!
Hubert Grzeskowiak

6

HTML, 72 71 bytes

<input min=200 type=number><x>NO <y>VACANCY<style>:valid+x,y{color:red}


10
You can save 1 byte by using the correct wording...
Neil

6
Oh my... I need a vacation.
GOTO 0

3
One of the other answers defines CSS separately. If you do that too, you could save 7 chars with "<style>" (pun intended)
Hubert Grzeskowiak


3

bash, 41 bytes

echo ␛[$[($1>199)*31]mNO ␛[31mVACANCY␛[0m

where ␛ represents a literal ESC character (ASCII \033).


1
brilliant multiplication!
Ipor Sircer

3

Go, 82 81 bytes

This only works on *nix terminals. I wonder how easy it would be to port this to Java... Done.

func f(x int)string{v:="NO\033[31m VACANCY\033[m";if(x>199){v=v[2:7]+v};return v}

2
I see a Java port coming.
MD XF

Ninja'd by 11 seconds. XD
totallyhuman

3

BASH / MKSH, 48 47 46 bytes

(($1>199))&&a=^[[31m;echo $a^MNO ^[[31mVACANCY^[[m

Note: ^[ means 1 byte wide ESC character: 0x1b or decimal 27.

^M means 1 byte wide CR character: 0x0d, decimal 13.


3

Excel VBA, 76 73 72 Bytes

Anonymous VBE immediate window function that takes input of expected type Integer from cell [A1] and outputs a (NO) VACANCY sign across cells A2:B2

[A2]="NO":[B2]="VACANCY":Range([If(A1>199,"A2:B2","B2")]).Font.Color=255

-3 Bytes for changing rgbRed to 255


1
Sorry if this is incorrect, I'm not fluent with Excel. But did you mean to write iif, and does this return the correct value if the input is equal to 200? [A1]>200 makes me think otherwise.
MD XF

1
@MDXF Yes, I did mean to write iif (abbreviated from inline if) however, you are right that should be >199rather than >200 good catch!
Taylor Scott

2

HTML + CSS + JavaScript (ES6), 74 59 bytes

Takes input as function argument of f, like f(100).

HTML

<x id=n>NO <j id=r>VACANCY

CSS

#r{color:red

JavaScript (ES6)

f=a=>a>199?n.id="r":0

Test Snippet

f=a=>a>199?n.id="r":0

f(prompt("Enter a number"))
#r{color:red
<x id=n>NO <j id=r>VACANCY


3
Gah that unclosed curly bracket is awful...
Beta Decay

@BetaDecay HAHA! LOL! :D
Arjun

@BetaDecay I feel with you.... It hurts deep down in your <s>heart</s> assembly level code...
Roman Gräf

1
-1: f=a=>n.id=a>199&&"r"
nderscore

Get rid of second element's id and set the CSS rule selector to j,#r to save 3 bytes.
Hubert Grzeskowiak

2

Haskell, 54 53 bytes

EDIT:

  • -1 byte: From @Dennis's Jelly answer, the 0 argument in the final escape sequence can be dropped.

f takes an integer and returns a string. Use as putStrLn$f 200.

f t|t>199="\27[31m"++f 0|0<1="NO \27[31mVACANCY\27[m"

Try it online! Alas, the colors don't show up in TIO, but you can see that the ANSI codes are correctly placed.

Golfing seemed to peter out pretty quickly with this one - not even naming the escape strings seems to save anything. The cleverest bit is recursing with f 0 to use the other branch as a substring. Three different attempts at using list comprehensions all turned up one byte longer. Perhaps the nicest I found:

f t=foldr drop"\27[31mNO \27[31mVACANCY\27[m"[5|t<200]

54 byte alternative: f t=concat["\27[31m"|t>199]++"NO \27[31mVACANCY\27[0m".
Laikoni

@Laikoni Oh! I was so close to that but somehow never noticed concat was shorter than id=<< because of the parentheses.
Ørjan Johansen

@Laikoni With Dennis's tip that's also 53 bytes.
Ørjan Johansen

2

Bash script, 60 bytes

c="\e[1;31m";((199<$1))&&printf $c;printf "NO$c VACANCY\e[m"

4
Just so you know, the downvote was cast automatically by the Community user when your answer was edited. I consider this a bug.
Dennis

@MDXF Input is via command-line arguments.
Dennis

@Dennis Ah, my bad. You may want to change the header to Bash script, 64 bytes.
MD XF

Unless you literally make hundred of edits, you can edit your answer every time you get an idea. Edits within the same 5-minute window get grouped into a single revision anyway.
Dennis

1
This doesn't reset the terminal color at the end, which is required.
Post Rock Garf Hunter

1

Mathematica, 67 bytes

Print[s=Style[#,FontColor->Red]&;If[#>200,s,#&]@"NO",s@" VACANCY"]&

or (60 bytes, but may be considered cheating)
This is actually Times["NO","VACANCY"], but appear to be correct.

(s=Style[#,FontColor->Red]&;If[#>200,s,#&]@"NO")s@"VACANCY"&

1

BASH, 100 bytes

if(($1<200));then
echo -n NO
else
echo -ne '\033[31mNO\033[0m'
fi
echo -e '\033[31m VACANCY\033[0m'

This can be probably be golfed, but I'm low on time. I'll come back to this later.

-5 bytes thanks to @R. Kap


Replacing if [ $1 -le 200 ] with if(($1<200)) saves 5 bytes and fixes the bug of the output not appearing in all red with an input of 200.
R. Kap

@R.Kap Thanks. OP requested default color for less than or equal to 200 though.
Arc676

No, OP asked for all red ouput for inputs more than or equal to 200.
R. Kap


1

C (*nix style terminal), 50 55 52 51 bytes

-1 thanks to Wheat Wizard

f(t){printf("␛[%dmNO ␛[31mVACANCY␛[m",t>199?31:0);}

␛ stands for the literal ESC byte, ASCII 27.

Call with f(200), 200 being the number. Prints NO VACANCY colored to the spec.


In my terminal, that breaks your rule that it shouldn't change the text color of the shell.
Ørjan Johansen

@ØrjanJohansen Fixed. I forgot that I run a custom shell which automatically sets the color.
MD XF

You can change ␛[0m to ␛[m
Post Rock Garf Hunter

1

PHP, 41 bytes

␛[<?=$argn<200?31:''?>mNO␛[31m VACANCY␛[m

␛ represents the Escape character.


0

shortC, 48 bytes

f(t){R"␛[%dmNO ␛[31mVACANCY␛[m",t>199?31:0

Where ␛ stands for ASCII 27, the ESCAPE byte.


0

GW-BASIC, 78 74 65 bytes

-12 thanks to Orjan Johansen

1INPUT X:IF X>199THEN COLOR 4
2?"NO ";:COLOR 4:?"VACANCY":COLOR 7

Prompts user for an integer. Output:

output


Hm can't find an online interpreter, but can't line 1 and 2 be joined with :?
Ørjan Johansen

@ØrjanJohansen Wow... can't believe I completely missed that. Thanks, and yeah, there are no online interpreters. However, you can use the first emulator on pcjs.org and type BASICA to get something close enough, although it may not have color.
MD XF

Assuming that emulator is good enough: You need a new line before the first PRINT. However, you don't need spaces after the line numbers, and PRINT can be abbreviated to ?.
Ørjan Johansen

@ØrjanJohansen NO WAY. I've used Microsoft BASIC for eight years and I never new about ?=PRINT. Updating...
MD XF

You missed the line number spaces, and seem to have a stray lower case x.
Ørjan Johansen

0

Tcl/Tk, 96 bytes

grid [label .n -text NO -fg [expr \$argv>199?"red":"tan"]]
grid [label .v -text VACANCY -fg red]

enter image description here

Korzystając z naszej strony potwierdzasz, że przeczytałeś(-aś) i rozumiesz nasze zasady używania plików cookie i zasady ochrony prywatności.
Licensed under cc by-sa 3.0 with attribution required.