Java is to JavaScript as Car is to Carpet

36

4

Title stolen inspired by Greg Hewgill's answer to What's the difference between JavaScript and Java?

Introduction

Java and JavaScript are commonly used languages among programmers, and are currently the most popular tags on Stack Overflow. Yet as we all know, aside from similar names, the two have almost nothing in common.

In honor of one of programming's most infamous debates, and inspired by my recent frustrations in tag searching, I propose the following:

Challenge

Write a program which takes in a string as input. Return car if the string begins with "Java" and does not include "JavaScript". Otherwise, return carpet.

Example Input and Output

car:

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

carpet:

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

Notes

  • Input matching should be case insensitive
  • Only possibilities for output should be car or carpet
  • Imaginary bonus points if your answer uses Java, JavaScript, or Regex
  • Alternate Title: Java is to JavaScript as ham is to hamster

Stevoisiak

Posted 2017-07-13T15:40:59.007

Reputation: 501

2The new [tag:pattern-matching] tag needs a wiki. Please contribute if you can – Christopher – 2017-07-13T16:29:52.737

2Depending on the order things are done in, javacarpet might catch bugs that the existing test cases don't. – Ray – 2017-07-13T21:17:27.523

17If you get imaginary bonus points if your answer uses Java, Javascript, or Regex, does that make such solution's bytecount complex? ;) – Steadybox – 2017-07-13T21:34:08.787

Alternate Title: Java is to JavaScript as ham is to hamster Actually, the "ham" in "hamster" is cognate to the food "ham". The food "ham" is pig meat, and the term "hamster" is derived from the related animal, the guinea pig, whose meat replaced pigs meat on long sea voyages as the animals were easier to raise on a ship. – dotancohen – 2017-07-17T08:14:30.307

Answers

100

Java/JavaScript Polyglot, 108 107 106 bytes

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

Run as Java

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

Try it online!

Note: don't trust the highlight as it's incorrect. The real Java, properly interpreted looks like below because \u000A is interpreted in the very first step of the compilation as \n, de facto ending the comment that started with the line comment (//).

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

Run as JavaScript

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

Credits to @CowsQuak for the JS version.

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));

How many imaginary bonus points for this answer?

-1 byte thanks to @Nevay in the Java answer.

Olivier Grégoire

Posted 2017-07-13T15:40:59.007

Reputation: 10 647

1This 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 – 2017-07-14T01:05:43.650

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 – 2017-07-14T10:11:15.807

24@Dennis IMHO "Java/JavaScript polyglot" counts as its own language, in which case this is very competitive. – ETHproductions – 2017-07-14T15:29:28.237

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 – 2017-07-14T16:00:35.320

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 – 2017-07-14T16:23:05.430

1We don't mark answers anymore; for this particular reason, we never did. I'm not saying this answer isn't a serious contender (it isn't in my personal opinion), but if it weren't, it would have to be removed. – Dennis – 2017-07-14T21:20:06.767

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));

user41805

Posted 2017-07-13T15:40:59.007

Reputation: 16 320

I was going to steal your regex but that would have made my answer longer :o nice answer though – HyperNeutrino – 2017-07-13T16:01:03.313

Now we just need a java answer. – James – 2017-07-13T16:02:34.820

We have a Java answer, but... I came to the roughly same regex... – Olivier Grégoire – 2017-07-13T16:25:14.733

alternatively: /^java(?!script)/i – Andrea – 2017-07-13T18:47:29.223

@Andrea Nope: fails on "javajavascript". – Olivier Grégoire – 2017-07-13T20:22:31.353

1@OlivierGrégoire ah, damn, that one seems unfair – Andrea – 2017-07-13T20:48:46.907

If you switch the ternary around, /javascript|^(?!java)/i has been working for me and is 1 byte shorter. – Value Ink – 2017-07-13T23:33:47.000

@ValueInk Thanks for the tip! – user41805 – 2017-07-14T05:47:59.137

15

Java (OpenJDK 8), 92 82 72 58 57 bytes

s->s.matches("(?i)(?!.*javascript)java.*")?"car":"carpet"

Try it online!

1 byte saved thanks to @Nevay!

Olivier Grégoire

Posted 2017-07-13T15:40:59.007

Reputation: 10 647

1You can omit the caret as String#matches attempts to match the entire string. – Nevay – 2017-07-13T23:45:23.867

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

michi7x7

Posted 2017-07-13T15:40:59.007

Reputation: 405

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

HyperNeutrino

Posted 2017-07-13T15:40:59.007

Reputation: 26 575

11 bytes shorter. – notjagan – 2017-07-13T15:55:26.653

Slightly different 81 byte solution – Justin – 2017-07-13T19:23:46.603

@Justin That too. Nice. – HyperNeutrino – 2017-07-13T20:10:07.520

If you switch to Python 2, you can save 2 bytes with a full program. – Dennis – 2017-07-14T06:50:36.497

@Dennis Nice, thanks. – HyperNeutrino – 2017-07-14T16:19:22.877

Possibly a Pythonic meta question, but since ; saves no bytes over \n, should one use \n for readability or it visually better "golfed" if it's on one line? – Luke Sawczak – 2017-07-14T18:28:33.700

@LukeSawczak It makes no difference to golfability so I choose \n for readability. It doesn't matter but sometimes ; is more golfy when indents exist. – HyperNeutrino – 2017-07-14T18:29:23.007

@HyperNeutrino That's true. Just noticing that you used ; here. – Luke Sawczak – 2017-07-14T18:30:21.350

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 – 2017-07-14T18:31:30.547

8

05AB1E, 21 bytes

lD'¦‚å≠sη'îáå*„¾„ƒ´#è

Try it online!

Erik the Outgolfer

Posted 2017-07-13T15:40:59.007

Reputation: 38 134

2lD“¦‚“åi“¾„“ë“îá“åi…carë 3 bytes more and 1 hour late :(. Nice job. – Magic Octopus Urn – 2017-07-13T17:14:22.353

4

C#, 80 78 bytes

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

TheLethalCoder

Posted 2017-07-13T15:40:59.007

Reputation: 6 930

1I think the most readable language here is C# – sepehr – 2017-07-14T16:52:05.760

2@sepehr You mean you see sharp with C#. (Do I get a bonus for dumb comments) – Ray – 2017-07-15T09:43:37.560

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.

Mark

Posted 2017-07-13T15:40:59.007

Reputation: 221

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 – 2017-07-13T21:19:49.817

1Find is case sensitive, search is case insensitive. But those last 3 bytes are a good idea! – Mark – 2017-07-13T21:29:40.353

Why the swap from Excel to Google Sheets? – Stevoisiak – 2017-07-13T23:09:40.893

2Removing the last 3 parens saves 3 bytes. Excel would just throw an error and put them in for you anyways. – Mark – 2017-07-13T23:39:23.267

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

Renzo

Posted 2017-07-13T15:40:59.007

Reputation: 2 260

3

Retina,  44  37 bytes

Ai`^(?!.*javascript)java
.+
pet
^
car

Thanks to @MartinEnder for golfing off 7 bytes!

Try it online!

Dennis

Posted 2017-07-13T15:40:59.007

Reputation: 196 637

3

vim, 58 bytes

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

Try it online!

Ray

Posted 2017-07-13T15:40:59.007

Reputation: 1 488

I think using the g command might be a little shorter, something like :g/\cjavascript/d :g!/^\cjava/d icarpet␛:s/pet..*. – Neil – 2017-07-15T23:48:33.033

3

Jelly, 27 bytes

,“Ẋṣ“®Ẓȷ»ŒlwЀ/Ḅn2‘×3“¢Ẹị»ḣ

Try it online!

Dennis

Posted 2017-07-13T15:40:59.007

Reputation: 196 637

3

Ruby, 42+1 = 43 bytes

Uses the -p flag.

$_="car#{"pet"if~/javascript|^(?!java)/i}"

Try it online!

Value Ink

Posted 2017-07-13T15:40:59.007

Reputation: 10 608

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");
}

Steadybox

Posted 2017-07-13T15:40:59.007

Reputation: 15 798

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")

Taylor Scott

Posted 2017-07-13T15:40:59.007

Reputation: 6 709

1Nice use of vba! I thought a macro would have been shorter. Now I have proof. – Mark – 2017-07-14T06:24:57.457

1

Excel, 84 bytes

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

Wernisch

Posted 2017-07-13T15:40:59.007

Reputation: 2 534

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!

Kavi

Posted 2017-07-13T15:40:59.007

Reputation: 31

Always good to experiment :) Note that you can save bytes around operators like and, or, if, else – Luke Sawczak – 2017-07-14T18:31:33.793

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'

bytepusher

Posted 2017-07-13T15:40:59.007

Reputation: 149

0

Mathematica, 82 bytes

regex

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

J42161217

Posted 2017-07-13T15:40:59.007

Reputation: 15 931

0

Perl, 98 84 62 Bytes

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

Try it online!

Thanks to bytepusher

Burgan

Posted 2017-07-13T15:40:59.007

Reputation: 101

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.

– James – 2017-07-13T18:04:32.783

@DJMcMayhem Thank you, I think the entire logic can be changed to make it even shorter, but I haven't figured it out – Burgan – 2017-07-13T18:28:29.003

1Just 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 – 2017-07-16T15:45:26.133

1You 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 moresub a{$b="car";$b.="pet"if lc$[0]=~/javascript/||lc$[0]!~/^java/;$b}` – bytepusher – 2017-07-16T15:53:40.003

1Not 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 – 2017-07-16T15:58:40.507

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.

Socratic Phoenix

Posted 2017-07-13T15:40:59.007

Reputation: 1 629

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!

Dennis

Posted 2017-07-13T15:40:59.007

Reputation: 196 637

0

Perl, 36 bytes

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

Run it as such:

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

stevieb

Posted 2017-07-13T15:40:59.007

Reputation: 101

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.

Neil

Posted 2017-07-13T15:40:59.007

Reputation: 95 035

0

Lua, 96 bytes

function(x)return x:lower():match"^java"and not x:lower():match"javascript"and"car"or"carpet"end

IllidanS4 wants Monica back

Posted 2017-07-13T15:40:59.007

Reputation: 109

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.

Ice Flake

Posted 2017-07-13T15:40:59.007

Reputation: 1

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 :)

f4bi4n

Posted 2017-07-13T15:40:59.007

Reputation: 1

0

Bracmat, 66 bytes

(f=.pet:?b&@(low$!arg:(? javascript ?|java ?&:?b|?))&str$(car !b))

Try it online!

Bart Jongejan

Posted 2017-07-13T15:40:59.007

Reputation: 71