Java è JavaScript come Car è moquette


36

Titolo rubato ispirato dalla risposta di Greg Hewgill a Qual è la differenza tra JavaScript e Java?

introduzione

Java e JavaScript sono linguaggi comunemente usati tra i programmatori e sono attualmente i tag più popolari su Stack Overflow. Eppure, come tutti sappiamo, a parte nomi simili, i due non hanno quasi nulla in comune.

In onore di uno dei dibattiti più famigerati della programmazione e ispirato alle mie recenti frustrazioni nella ricerca di tag , propongo quanto segue:

Sfida

Scrivi un programma che accetta una stringa come input. Restituisce carse la stringa inizia con "Java" e non include "JavaScript". Altrimenti, ritorna carpet.

Esempio di input e output

auto:

java
javafx
javabeans
java-stream
java-script
java-8
java.util.scanner
java-avascript
JAVA-SCRIPTING
javacarpet

tappeto:

javascript
javascript-events
facebook-javascript-sdk
javajavascript
jquery
python
rx-java
java-api-for-javascript
not-java
JAVASCRIPTING

Gli appunti

  • La corrispondenza dell'input deve essere sensibile al maiuscolo / minuscolo
  • Solo le possibilità di output dovrebbero essere carocarpet
  • Punti bonus immaginari se la tua risposta utilizza Java, JavaScript o Regex
  • Titolo alternativo: Java è JavaScript come ham è come criceto

2
Il nuovo tag di corrispondenza dei modelli ha bisogno di un wiki. Per favore, contribuisci se puoi
Christopher,

2
In base all'ordine in cui vengono eseguite le operazioni, è javacarpetpossibile che vengano rilevati bug che i casi di test esistenti non presentano.
Ray,

17
Se ottieni imaginary bonus points if your answer uses Java, Javascript, or Regex, questo rende complesso il bytecount di tale soluzione? ;)
Steadybox il

Alternate Title: Java is to JavaScript as ham is to hamsterIn realtà, il "prosciutto" in "criceto" è affine al "prosciutto" alimentare. Il "prosciutto" alimentare è carne di maiale e il termine "criceto" deriva dall'animale correlato, la cavia, la cui carne sostituiva la carne di maiale durante i lunghi viaggi in mare poiché gli animali erano più facili da allevare su una nave.
dotancohen,

Risposte:


100

Polyglot Java / JavaScript, 108 107 106 byte

//\u000As->s.matches("(?i)(?!.*javascript)java.*"/*
a=>/(?!.*javascript)^java/i.test(a/**/)?"car":"carpet"

Esegui come Java

//\u000As->s.matches("(?i)(?!.*javascript)java.*"/*
a=>/(?!.*javascript)^java/i.test(a/**/)?"car":"carpet"

Provalo online!

Nota: non fidarti dell'evidenziazione poiché non è corretto. Il vero Java, correttamente interpretato appare come di seguito perché \u000Aviene interpretato nel primo passo della compilation come \n, di fatto termina il commento che è iniziato con la riga comment ( //).

//
s->s.matches("(?i)(?!.*javascript)java.*"/*
a=>/(?!.*javascript)^java/i.test(a/**/)?"car":"carpet"

Esegui come JavaScript

//\u000As->s.matches("(?i)(?!.*javascript)java.*"/*
a=>/(?!.*javascript)^java/i.test(a/**/)?"car":"carpet"

Crediti a @CowsQuak per la versione JS.

let f=

//\u000As->s.matches("(?i)(?!.*javascript)java.*"/*
a=>/(?!.*javascript)^java/i.test(a/**/)?"car":"carpet"

var a=["java","javafx","javabeans","java-stream","java-script","java-8","java.util.scanner","javascript","java-avascript","javascript-events","facebook-javascript-sdk","javajavascript","jquery","python","rx-java","java-api-for-javascript","not-java"];

for(var s of a) console.log(s.padStart(a.reduce((x,y)=>x.length>y.length?x:y).length) + "=>" + f(s));

Quanti punti bonus immaginari per questa risposta?

-1 byte grazie a @Nevay nella risposta Java.


1
This isn't competitive in JavaScript or Java. I'm not even convinced it's a serious contender, which is a requirement for all submissions.
Dennis

10
@Dennis Thank you for your information. However I consider this as a polyglot entry. Is there any rule against polyglot entries when they aren't explicitly requested? I tried to golf this as much as possible. For instance, I tried to put both regexes together, but I couldn't get anything shorter than this (because of the two different albeit similar regexes, and their delimiter). It's also impossible to have the same variable definition because JavaScript doesn't allow a new line between a and =>. I tried to stay in the spirit of golfing. If I did something wrong, please tell me?
Olivier Grégoire

24
@Dennis IMHO "Java/JavaScript polyglot" counts as its own language, in which case this is very competitive.
ETHproductions

1
@OlivierGrégoire I'm not saying this isn't a well-golfed polyglot submission, but it's debatable if there should be polyglot submissions to non-polyglot challenges in the first place. They came up as part of the Can serious contenders do more than the challenge asks for? discussion, but I don't think there's a clear consensus on this particular topic. Personally, I'm not in favor.
Dennis

3
@Dennis Thank you for your insights, I now understand what you meant. Should this answer be tagged as "non-competitive", according to you? On the other hand, while I'm not speaking for all polyglot answers (this is my first ever), this one has the special meaning that the challenge speaks about both Java and JavaScript, and that the "imaginary bonus points" were explicitly awarded for Java, JavaScript and regex answers before I wrote this answer. Java and regex can be combined, JavaScript and regex can be combined, why not all together? Anyways, I don't mind marking this as non-competitive.
Olivier Grégoire

17

JavaScript, 50 49 bytes

Saved 1 byte thanks to @ValueInk by rearranging the regex

a=>/javascript|^(?!java)/i.test(a)?"car":"carpet"

Test snippet

let f=

a=>/javascript|^(?!java)/i.test(a)?"carpet":"car"

var a=["java","javafx","javabeans","java-stream","java-script","java-8","java.util.scanner","java-avascript","javascript","javascript-events","facebook-javascript-sdk","javajavascript","jquery","python","rx-java","java-api-for-javascript","not-java"];

for(var s of a) console.log(s.padStart(a.reduce((x,y)=>x.length>y.length?x:y).length) + "=>" + f(s));


I was going to steal your regex but that would have made my answer longer :o nice answer though
HyperNeutrino

Now we just need a java answer.
DJMcMayhem

We have a Java answer, but... I came to the roughly same regex...
Olivier Grégoire

alternatively: /^java(?!script)/i
Andrea

1
@OlivierGrégoire ah, damn, that one seems unfair
Andrea


11

C (only calling puts), 131 bytes

f(int*s){char r[]="carpet";~*s&'AVAJ'||(r[3]=0);for(;*s&255;*(int*)&s+=1)~*s&'AVAJ'||~s[1]&'IRCS'||~s[2]&'TP'||(r[3]='p');puts(r);}

It does have its problems, but it passes all of the testcases provided :)

g(int* s)
{
  char r[] = "carpet";
  ~*s&'AVAJ' || (r[3]=0);
  for(;*s & 255; *(int*)&s +=1)
    ~*s&'AVAJ' || ~s[1]&'IRCS' || ~s[2]&'TP' || (r[3]='p');
  puts(r);
}

Imaginary bonus points if your answer uses Java, Javascript, or Regex

well... no thanks



8

Python 2, 68 bytes

k=input().lower();print'car'+'pet'*(k[:4]!='java'or'javascript'in k)

Try it online!

-11 bytes thanks to notjagan
-2 bytes thanks to Dennis




@Justin That too. Nice.
HyperNeutrino

If you switch to Python 2, you can save 2 bytes with a full program.
Dennis

1
@LukeSawczak Oh I didn't even realize that :P I was using Java right before that and in Java ; is required so I since I have to use it anyway the newline is unnecessary :P That's why I used it.
HyperNeutrino

4

C#, 80 78 bytes

s=>(s=s.ToLower()).StartsWith("java")&!s.Contains("javascript")?"car":"carpet"

1
I think the most readable language here is C#
sepehr

2
@sepehr You mean you see sharp with C#. (Do I get a bonus for dumb comments)
Ray

4

EXCEL Google Sheets, 89 86 Bytes

Saved 3 bytes thanks to Taylor Scott

=LEFT("carpet",6-3*ISERR(SEARCH("javascript",A1))+3*ISERR(IF(SEARCH("java",A1)=1,1,1/0

Takes an input on A1

Explanation

=LEFT("carpet",6-3*ISERR(SEARCH("javascript",A1))+3*ISERR(IF(SEARCH("java",A1)=1,1,1/0)))

 SEARCH("javascript",A1)        #Case-Insensitive Find, returns error if not found  
 ISERR(                         #Returns string true if error, False if not
 3*ISERR(                       #Forces TRUE/False as integer, multiplies by 3
 IF(SEARCH("java",A1)=1,1,1/0)  #If java found, returns integer. if 1, java begins string
                                #so returns 1, which will be turned into 0 by iserr.
                                #Else returns 1/0, which will be turned into 1 by iserr.
 LEFT(                          #Returns digits from the left, based upon count.

I believe that you can replace the Searches with Finds for -2 bytes and that that could be further translated to a google sheets formula for -3 bytes by not closing the last three parens
Taylor Scott

1
Find is case sensitive, search is case insensitive. But those last 3 bytes are a good idea!
Mark

Why the swap from Excel to Google Sheets?
Stevoisiak

2
Removing the last 3 parens saves 3 bytes. Excel would just throw an error and put them in for you anyways.
Mark

3

vim, 58 bytes

gUU:s/.*JAVASCRIPT.*/Q/g
:s/^JAVA.*/car
:s/[A-Z].*/carpet

Try it online!


I think using the g command might be a little shorter, something like :g/\cjavascript/d :g!/^\cjava/d icarpet␛:s/pet..*.
Neil




3

Common Lisp, 131 125 bytes

(lambda(s)(format()"car~@[pet~]"(or(<(length s)4)(not(#1=string-equal"java"(subseq s 0 4)))(search"javascript"s :test'#1#))))

Try it online!

Size reduced thanks to the #n= “trick” of Common Lisp.

Explanation

(lambda (s)                 ; anonymous function
  (format                   ; use of format string to produce the result
    ()                      ; the result is a string
    "car~@[pet~]"           ; print "car", then print "pet" when:
    (or (< (length s) 4)    ; the string is less then 4 characters or
        (not (string-equal "java" (subseq s 0 4)))     ; does not start with java or
        (search "javascript" s :test 'string-equal)))) ; contains javascript

2

C (tcc), 144 136 bytes

a;f(s){char*t=s;for(;*t;a=!strncmp(s,"java",4))*t=tolower(*t++);for(t=s;*t;)s=strncmp(t++,"javascript",10)&&s;puts(a*s?"car":"carpet");}

Try it online!

Unrolled:

a;
f(s)
{
    char *t = s;
    for (; *t; a = !strncmp(s, "java", 4))
        *t = tolower(*t++);
    for (t=s; *t;)
        s = strncmp(t++, "javascript", 10) && s;
    puts(a*s ? "car"  :"carpet");
}

1

Excel, 84 bytes

="car"&IF(AND(ISERR(SEARCH("javascript",A1)),IFERROR(SEARCH("java",A1),2)=1),,"pet")

1

Excel VBA, 76 Bytes

Anonymous VBE immediate window function that takes input from range [A1] and outputs is car/carpet status to the VBE immediate window

Does not use RegExp

?"car"IIf(InStr(1,[A1],"Java",1)*(InStr(1,[A1],"JavaScript",1)=0),"","pet")

1
Nice use of vba! I thought a macro would have been shorter. Now I have proof.
Mark

1

Python 3, 95 bytes

g=lambda s:(lambda r:'car' if r[:4]=='java' and 'javascript' not in r else 'carpet')(s.lower())

Try it online!

Yeah, it could be shorter but I wanted to try using a nested lambda!


Always good to experiment :) Note that you can save bytes around operators like and, or, if, else
Luke Sawczak

1

Perl, 42 bytes

I believe the answer by stevieb has an incorrect output (tried that one myself - it returns car for 'javajavascript'). This should work:

say/^java/i&&!/javascript/i?'car':'carpet'

0

Mathematica, 82 bytes

regex

If[#~StringMatchQ~RegularExpression@"(?i)(?!.*javascript)^java.*","Car","Carpet"]&

0

JAISBaL, 36 bytes

℠℘(?!.*javascript)^java.*}͵Ucar½Upet

Verbose/explanation:

# \# enable verbose parsing #\
tolower                           \# [0] convert the top value of the stack to lowercase #\
split (?!.*javascript)^java.*}    \# [1] split the top value of the stack by (?!.*javascript)^java.*} #\
arraylength                       \# [2] push the length of the array onto the stack #\
print3 car                        \# [3] print car #\
!if                               \# [4] if the top value on the stack is falsy, skip the next statement #\
print3 pet                        \# [5] print pet #\

JAISBaL was my first attempt at designing a golfing language, so it's rather quirky... there's no matches or contains, regex or otherwise, so instead we have to split and check the resulting array length... because JAISBaL has a split-by-regex... but no other regex support.... because reasons.

Regex stolen borrowed from @Cows Quack's answer.


0

Python 2, 69 bytes

f=input().lower().find
print'car'+'pet'*(f('java')!=~f('javascript'))

Currently 1 byte longer than the shortest Python 2 solution.

Try it online!


0

Perl, 36 bytes

say/^java(?!script)/i?"car":"carpet"

Run it as such:

perl -nE 'say/^java(?!script)/i?"car":"carpet"' java.txt

0

Batch, 91 bytes

@set/ps=
@set t=%s:~0,4%
@if "%t:java=%%s:javascript=%"=="%s%" (echo car)else echo carpet

Takes input on STDIN. Batch doesn't have a case insensitive comparison operator but it does have case insensitive string replacement so I can assign a temporary to the first four characters and then case insensitively replace java, which should then result in the empty string. Meanwhile I case insensitively replace javascript in the original string, which should leave it unchanged.



0

Perl, 98 84 62 Bytes

sub a{"car".($_[0]=~/javascript/i||$_[0]!~/^java/i?'pet':'');}

Try it online!

Thanks to bytepusher


Welcome to the site! I don't know any perl, but it looks like there is a lot of whitespace you could remove. Also, if you're looking for more ways to shorten it, there's a bunch of tips here.
DJMcMayhem

@DJMcMayhem Thank you, I think the entire logic can be changed to make it even shorter, but I haven't figured it out
Burgan

1
Just some hints (without changing your solution too much): You can replace the return $b; with just $b;. Perl always returns the last evaluated statement. Since we don't care about warnings, you can even drop the ';' to $b}. You don't need the brackets around the if. If you use || instead of or, you can save a whitespace after the regex.
bytepusher

1
You can also remove the () around the first lc, but need a space after if then. If you use !~ instead of ! =~ the second condition can be lc$_[0]!~. ` -> sub a{$b="car";$b.="pet"if lc$_[0]=~/javascript/||lc$_[0]!~/^java/;$b}. Using the ternary ops brings it down one more sub a{$b="car";$b.="pet"if lc$_[0]=~/javascript/||lc$_[0]!~/^java/;$b}
bytepusher

1
Not to forget - no need for lc when you have the regex ignore case switch, down another 2 :) $_[0] =~//i||$_[0]!~//i. And finally, why a variable? sub a{"car".($_[0]=~/javascript/i||$_[0]!~/^java/i?'pet':'');} should do fine :). And now: perl will be nice and let you use $_[0] w/o specifying it (though not with !~): sub a{"car".(/javascript/i||!/^java/i?'pet':'')} -> 48 :)
bytepusher

0

Dart VM, 104 bytes 102 bytes

main(p){p=p[0].toLowerCase();print("car${p.indexOf('java')==0&&p.indexOf('javascript')<0?'':'pet'}");}

Explanation:

Degolfed:

main(p)
{
    p = p[0].toLowerCase();
    print("car${p.indexOf('java') == 0 && p.indexOf('javascript') < 0 ? '' : 'pet'}");
}

We have our usual main function

We replace p with p[0].toLowerCase(); so that we don't have to declare a new variable (var plus a space would be 4 extra bytes)

We then proceed to do the actual printing

We print car unconditionally and we use inline statements for checking whether to print pet after it or not. If it has the string 'java' at index 0 and does not have 'javascript' in it, we do nothing (we actually append an empty string but it does not have any effect) and otherwise we append pet.


0

Rust, 97 bytes

let s=if Regex::new(r"^javascript|^!java$").unwrap().is_match("javascript"){"carpet"}else{"car"};

I'm pretty sure that there is a shorter solution but it's my first try :)


Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.