text:
IP address or not?
Your network scanning tool is annoyingly picky about input, and immediately crashes if you feed it an IPv4 address that contains improper characters or isn't properly formatted.

An IPv4 address is a 32-bit numeric address written as four numbers separated by periods. Each number can be zero to 255.

We need to write a tool to pre-validate the input to avoid those crashes, and our specific tool is picky: A valid format will look like a.b.c.d where a, b, c and d:

Can be a 0 or a natural number with no leading zeros.
Should be between 0 - 255 (inclusive).
Should not contain special symbols like +, -, ,, and others.
Should be decimal (base 10)

Input: A string
Output: Truthy or Falsey value (arbitrary values also accepted)
Test Cases:
Input            |  Output  |  Reason
                 |          |
- 1.160.10.240   |  true    |
- 192.001.32.47  |  false   |  (leading zeros present)
- 1.2.3.         |  false   |  (only three digits)
- 1.2.3          |  false   |  (only three digits)
- 0.00.10.255    |  false   |  (leading zeros present)
- 1.2.$.4        |  false   |  (only three digits and a special symbol present)
- 255.160.0.34   |  true    |
- .1.1.1         |  false   |  (only three digits)
- 1..1.1.1       |  false   |  (more than three periods)
- 1.1.1.-0       |  false   |  (special symbol present)
- .1.1.+1        |  false   |  (special symbol present)
- 1 1 1 1        |  false   |  (no periods)
- 1              |  false   |  (only one digit)
- 10.300.4.0     |  false   |  (value over 255)
- 10.4F.10.99    |  false   |  (invalid characters)
- fruit loops    |  false   |  (umm...)
- 1.2.3.4.5      |  false   |  (too many periods/numbers)
- 0.0.0.0        |  true    |
- 0.0 0.0.       |  false   |  (periods misplaced)
- 1.23..4        |  false   |  (a typo of 1.2.3.4)
- 1:1:1:1:1:1:1:1|  false   |  (an IPv6 address, not IPv4)

This is code-golf, so fewest bytes will win!

Note for the users - if anyone wants to add some test-cases, they're welcomed (by suggesting an edit).

Suggest testcases: 1.1.1.1.1, 1.1.1.1., .1.1.1, 1..1.1, 1..1.1.1, 1.1.1.0, 1.1.1.-0, 1.1.1.+1, 1.1.1.1E1, 1.1.1.256, 1.1.1.0x1, 255.255.255.255, 0.0.0.0, 'or 1=1--, <empty string>, 1 1 1 1, 1,1,1,1.

I'd suggest test cases like Hello, World!, 1.1.1.1.1, 1.-1.1.1

Suggest adding test cases "1.2.3.4.5" (to rule out too long IPs) and "999.0.0.0" (to rule out too large IPs).

Possibly slightly picky, but you should probably refer to "IPv4 addresses" rather than "IP addresses" - or at least, mention somewhere that you just mean IPv4 addresses - otherwise 1234:5678::1 ought to be a valid IP address (whereas from the description it's clear that that's not intended :)

Why are leading 0's disallowed in octets especially if one of your restrictions is base 10?

0 is a valid IPv4 address too, which expands to 127.0.0.1

1.2.3 is accepted by ping too - it expands to 1.2.0.3 and 1.2 expands to 1.0.0.2

@Criggie The premise isn't to actually check all real IP4 rules (like the ones you mentioned), it's to ensure that the input string doesn't crash some other (presumably badly written) app that only allows input in a very specific form. Also, we're not going to change the rules of a challenge that already has 30+ answers.

@BradC Fair enough - I'm just  pointing out that this is not 100% reflective of the real world.   Its a bit specalised.

@Criggie Worth noting that the RFC declares that "Addresses are fixed length of four octets". I think the fringe cases you're referencing are more specialized than this challenge.

A test case similar to one presented by @tsh would be 1.23..4 (e.g. a typo of 1.2.3.4); there are four digits and three periods, and there are no leading or trailing periods, but it's still not valid (other than via Criggie's expansion, which would still be a different IP from what was likely intended: 1.23.0.4 vs 1.2.3.4)

Ipv4 addresses can also be written as a longint... such as http://16843009, should that be allowed here?

@nl-x It very heavily seems like the intent of this challenge is to parse ip addresses in dot-decimal notation.

To IP or not to IP?

“fruit loops” (umm...)

@Criggie Actually, RFCs specify that a valid IPv4 address is either of the form n8.n8.n8.n8, n8.n8.n16, n8.n24 or n32, each n being written either in decimal, octal or hexadecimal (thus 0x7f.001 is a valid IPv4). BTW, 0 is not 127.0.0.1, it's 0.0.0.0, meaning "any address", which on your machine resolves to any or all of your interfaces IPv4 addresses. This challenge focuses on only one of of those multiple notations and, obviously, the resulting codes should NOT be used in real life programs (use dedicated functions like POSIX's inet_addr()). True IPv4 validation may be another golf though.

X86_64 machine code: 18 16 bytes
Edit: This answer doesn't quite work, as

I am using inet_pton from the standard C libraries, which means I need the extern. I didn't include the extern in my byte count though.
I used the red zone as a result for the actual address, but called a function which also could've used the red zone. It fortunately doesn't on my machine, but some odd standard library build might use it which could cause undefined behavior.

And yeah, the whole thing is pretty much being done by an already written function
Anyway, this is what I got: 48 89 fe 6a 02 5f 48 8d 54 24 80 e9 00 00 00 00
Assembly:
section .text
    extern inet_pton
    global ipIsValid

ipIsValid:
    mov rsi, rdi
    ;mov rdi, 2 ; change to 10 for ipv6
    push 2
    pop rdi ; thank you peter
    lea rdx, [rsp - 128]
    jmp inet_pton

Explanation:
Take a look at inet_pton(3). It takes a string IP address and puts it in a buffer you can use with struct sockaddr. It takes 3 arguments: the address family (AF_INET (ipv4), 2, or AF_INET6 (ipv6), 10), the ip address's string, and a pointer to the output. It returns 1 on success, 0 for an invalid address, or -1 for when the address family is neither AF_INET or AF_INET6 (which will never occur because I'm passing a constant to it).
So I simply move the string to the register for the second argument, set the first register to 2, and set the third register to the red zone (128 bytes below the stack pointer) since I don't care about the result. Then I can simply jmp to inet_pton and let that return straight to the caller!
I spun up this quick test program to test your cases:
#include <stdio.h>
#include <arpa/inet.h>
#include <netinet/ip.h>

extern int ipIsValid(char *);

int main(){
    char *addresses[] = {
        "1.160.10.240",
        "192.001.32.47",
        "1.2.3.",
        "1.2.3",
        "0.00.10.255",
        "1.2.$.4",
        "255.160.0.34",
        ".1.1.1",
        "1..1.1.1",
        "1.1.1.-0",
        ".1.1.+1",
        "1 1 1 1",
        "1",
        "10.300.4.0",
        "10.4F.10.99",
        "fruit loops",
        "1.2.3.4.5",
        NULL
    };

    for(size_t i = 0; addresses[i] != NULL; ++i){
        printf("Address %s:\t%s\n", addresses[i],
            ipIsValid(addresses[i]) ? "true" : "false");
    }
    return 0;
}

Assemble with nasm -felf64 assembly.asm, compile with gcc -no-pie test.c assembly.o, and you'll get:
Address 1.160.10.240:   true
Address 192.001.32.47:  false
Address 1.2.3.: false
Address 1.2.3:  false
Address 0.00.10.255:    false
Address 1.2.$.4:    false
Address 255.160.0.34:   true
Address .1.1.1: false
Address 1..1.1.1:   false
Address 1.1.1.-0:   false
Address .1.1.+1:    false
Address 1 1 1 1:    false
Address 1:  false
Address 10.300.4.0: false
Address 10.4F.10.99:    false
Address fruit loops:    false
Address 1.2.3.4.5:  false

I could make this much smaller if the caller was supposed to pass AF_INET or AF_INET6 to the function

I love that you did this in asm. And the fact you explained it to those who might not understand it (as well as test code) is even better. Which is not to say that I could have done it in asm; far too many years have passed but I remember enough to see exactly what your explanation (and therefore process) is saying (does). Good work.

e9 00 00 00 00 is a jmp near $+5, not a jmp inet_pton. If you provide opcode, you should include the including inet_pton part, not leave a blank

15 bytes-TIO 32bit x86

you should include the extern in the answer title, since the program requires it and it is not available on all platforms.

poor answer, IMHO, just farming the bulk of the work out to an external function.

the "mov rdi,2" can be "push 2/pop rdi" for -2 bytes.  Note also that the disassembly is wrong or the code is wrong.  It's either "mov edi" (not rdi) or there's a prefix missing.

@Logern, the stack frame isn't needed, which makes is only 9 bytes.

@Logern On my machine (compiling with -m32) I'm getting a segmentation fault after the second call to inet_pton somewhere in libc, nice idea though

This answer is incorrectly scored. The string inet_pton must be included in the byte count. Furthermore, the export ipIsValid needs to be included in the byte count as well, and as such, should be renamed to f. I would also suggest adding at least 1 byte for each import and export (i.e., an extra 2 bytes on top of the lengths of the two strings). To see how these strings make it into the assembled result, look at the output of readelf -s assembly.o.

Would mov rsi, rdi save a byte if changed into push/pop? Not familiar with x64asm

“It works on my machine” is the core of this site.  No budges are left unused!

Java (JDK), 63 bytes
s->("."+s).matches("(\\.(25[0-5]|(2[0-4]|1\\d|[1-9])?\\d)){4}")

Try it online!
Credits

-1 byte thanks to Kevin Cruijssen
l4m2 for showing the previously-failing case .1.1.1.1.

You forgot to remove the trailing semi-colon. ;) And I can verify it works for all test cases, including those in the comments. Will see if I see some things to golf.

Failed on .1.2.3.4

Is it allowed to use boolean when explictly require 0/1?

@l4m2 The original question had Valid/Invalid. So I assume any truthy/falsey value is acceptable here.

Output: 0 or 1 and Java has no auto bool->int

JavaScript (Node.js), 43 bytes
x=>x.split`.`.map(t=>[t&255]==t&&[])==`,,,`

Try it online!
JavaScript (Node.js), 46 bytes
x=>x.split`.`.every(t=>k--&&[t&255]==t,k=4)*!k

Try it online!
used Arnauld's part
JavaScript (Node.js), 54 53 51 bytes
x=>x.split`.`.every(t=>k--*0+t<256&[~~t]==t,k=4)*!k

Try it online!
-2B for 0+t<256, -1B from Patrick Stephansen, +1B to avoid input 1.1.1.1e-80
RegExp solution 5854 bytes
s=>/^((2(?!5?[6-9])|1|(?!0\d))\d\d?\.?\b){4}$/.test(s)

Thank Deadcode for 3 bytes

I have added some test cases!

This gives truthy for 0.0.0.0. Everything else seems to work fine.

@KevinCruijssen 0.0.0.0 is here true one. Just why SQL injection is here?

Ah wait, I misinterpret the sentence in the challenge description. 0.0.0.0 is indeed truthy. That will golf my answer as well.. (And what do you mean by SQL injection? :S The link is to TIO with ALL test cases.)

@KevinCruijssen Why test case 'or 1=1-- exist

@l4m2 I added it since we need some testcases that even not looks like an IP address.

A regular expression is called a "regex" or a "regexp"...

The regex solution looks faulty. Shouldn´t \\. be (^|\.)? Why the double backslash?

@Titus edited..

Since t is already a string, you can save 1 more byte.

Does something involving >>8 save any bytes?

PHP, 39 36 bytes
<?=+!!filter_var($argv[1],275,5**9);

Try it online!
275 resembles the constant FILTER_VALIDATE_IP
5**9 is being used instead of the constant FILTER_FLAG_IPV4. This is sufficient, because 5**9 & FILTER_FLAG_IPV4 is truthy, which is exactly what PHP does in the background, as Benoit Esnard pointed out.
Here, filter_var returns the first argument, if it's a valid IPv4 address, or false if it's not. With +!!, we produce the output required by the challenge.

Using 5**9 instead of 1048576 saves 3 bytes here: PHP uses & to test the IPv4 / IPv6 flags, so any number between 1048576 and 2097151 is valid.

I hereby downvote your answer for being (basically) my answer: https://codegolf.stackexchange.com/a/174470/14732 which was written at 2018-10-22 09:17:34UTC while yours was written on 2018-10-22 09:21:55UTC. Even if I revert the 1-byte optimization given by @BenoitEsnard, my answer is exactly the same as yours in functionality.

I have to apologise, I didn't see your answer, though at the time I was composing it, there was no submission in PHP on this question (as you said, the time difference is less than five minutes).

I know, and I understand it. I only noticed yours just now. I can roll back mine, and you keep the optimization. But I don't know if it makes the answer be different enough from eachother.

@IsmaelMiguel I wouldn't downvote somebody for that if it's plausible yours wasn't there when they started. With a 5 minute difference, not only is it plausible, it's almost certainly the case, which is apparent even without the author saying so himself.

@IsmaelMiguel I agree with Duncan about not downvoting. If it were like half an hour later, that'd definitely make sense, but 4m21s is certainly an acceptable timeframe wherein your answer may not have been submitted yet when oktupol started writing theirs.

PHP, 36 Bytes
echo(ip2long($argv[1])===false?0:1);

ip2long is a well-known built-in function.

29 bytes

This seems to use uncodumented features present in newer versions (I presume it is from PHP7+). Keep in mind that, for PHP 4 and 5, this does accept incomplete IPs.

27 bytes

https://codegolf.meta.stackexchange.com/a/7146/12130

@DavidMulder thanks. I edited it to use php -r.

29 bytes: <?=ip2long($argv[1])!==false; Can You give a TiO? From the description, it seems that ip2long is not as restrictive as the challenge demands.

@Titus It is, for newer versions of PHP. It just isn't documented. Newer versions don't accept incomplete IP addresses. Older versions do. I know that some PHP5 versions do accept the partial IP, just don't know all because it isn't documented. This is the only reason why I didn't use this method, and even described it in my answer.

I tried on http://sandbox.onlinephpfunctions.com : it was restricted in PHP 5.2.

This will give success if you feed it any integer, such as 1 , 2 , etc. Don't think it should. And also if you feed it something as 100.100.100

@JoKing According to the OP, 0.0.0.0 is a valid IP address. This makes sense as many applications treat it as valid IP address, and also my PHP version treats it as valid. PHP 7.2.11.

Perl 6, 22 21 20 bytes
-1 byte thanks to Phil H.
{?/^@(^256)**4%\.$/}

Try it online!
Explanation
{                  }  # Anonymous Block
  /               /   # Regex match
   ^             $    # Anchor to start/end
    @(    )           # Interpolate
      ^256            #   range 0..255,
                      #   effectively like (0|1|2|...|255)
           **4        # Repeated four times
              %\.     # Separated by dot
 ?                    # Convert match result to Bool

Man, I need to spend more time figuring out Perl 6's regexes. I had no either the % modifier existed.  I wonder if it tries to checks all 256**4 possibilities?

Instead of <{^256}> you can just convert the range to an array @(^256) for -1 char TIO. By changing the code block to an array it also gets enormously faster (0.4s instead of >30).

@PhilH Cool, thanks. I tried $(^256) but now I realize why this didn't work.

05AB1E, 26 24 23 22 23 17 bytes
'.¡DgsAì₅ÝAìÃg4)Ë

-1 byte thanks to @Emigna.
+1 byte for bugfixing test case 1.1.1.1E1 incorrectly returning a truthy result.
Try it online or verify all test cases.
Explanation:
'.¡          '# Split the (implicit) input-string on "."
   D          # Duplicate this list
    g         # Pop and push the length of this copy
   s          # Swap so the list is at the top again
    Aì        # Prepend the alphabet before each item
      ₅Ý      # Push a list in the range [0,255]
        Aì    # Prepend the alphabet before each integer here as well
          Ã   # Only keep those items from the first list
           g  # Pop and push its length as well
   4          # Push a 4
    )         # Wrap all three values on the stack into a list
     Ë        # Check that all three are the same (aka all three are 4s)
              # (after which the result is output implicitly)

Prepending the alphabet is necessary, because in 05AB1E, "0", "00", "0e0", "5E0", "-0" etc. are all the same 'integer' 0.

You should be able to use Ā instead of <d

@MagicOctopusUrn I'm afraid it fails for 1.1.1.1E1, 1..1.1.1, 1.1.1.1., 192.00.0.255, and 0.00.10.255. (PS: I've fixed the 1.1.1.1E1 by adding the þ to the join-and-equal check.)

Fair enough, figured I missed something.

@MagicOctopusUrn The main issue is 05AB1E seeing numbers with leading 0s equal to those without, even as string. Which is why I use the DïþJsJQ check where ï cast it to int to remove leading 0s, and þ only leaves digits removing things like E, -, etc. :) The 1š is for test case 0.00.10.255, since 00010255 and 0010255 would be equal.

Yeah I went through the same nonsense, the reversal of all numbers worked pretty well though, except for those cases. Interesting when features beneficial for some problems become almost bug-like for others.

PowerShell, 59 51 49 bytes
-8 bytes, thanks @AdmBorkBork
-2 bytes, true or false allowed by author
try{"$args"-eq[IPAddress]::Parse($args)}catch{!1}

Test script:
$f = {

try{"$args"-eq[IPAddress]::Parse($args)}catch{!1}

}

@(
    ,("1.160.10.240" , $true)
    ,("192.001.32.47" , $false)
    ,("1.2.3." , $false)
    ,("1.2.3" , $false)
    ,("0.00.10.255" , $false)
    ,("192.168.1.1" , $true)
    ,("1.2.$.4" , $false)
    ,("255.160.0.34" , $true)
    ,(".1.1.1" , $false)
    ,("1..1.1.1" , $false)
    ,("1.1.1.-0" , $false)
    ,("1.1.1.+1" , $false)
    ,("1 1 1 1" , $false)
    ,("1"            ,$false)
    ,("10.300.4.0"   ,$false)
    ,("10.4F.10.99"  ,$false)
    ,("fruit loops"  ,$false)
    ,("1.2.3.4.5"    ,$false)

) | % {
    $s,$expected = $_
    $result = &$f $s
    "$($result-eq$expected): $result : $s"
}

Output:
True: True : 1.160.10.240
True: False : 192.001.32.47
True: False : 1.2.3.
True: False : 1.2.3
True: False : 0.00.10.255
True: True : 192.168.1.1
True: False : 1.2.$.4
True: True : 255.160.0.34
True: False : .1.1.1
True: False : 1..1.1.1
True: False : 1.1.1.-0
True: False : 1.1.1.+1
True: False : 1 1 1 1
True: False : 1
True: False : 10.300.4.0
True: False : 10.4F.10.99
True: False : fruit loops
True: False : 1.2.3.4.5

Explanation:
The script tries to parse an argument string, to construct a .NET object, IPAddress.

return $true if object created and the argument string is equal to a string representation of the object (normalized address by object.toString())
return $false otherwise

PowerShell, 59 56 54 bytes, 'don't use a .NET lib' alternative
-3 bytes, true or false allowed by author
-2 bytes, thanks to @Deadcode for the cool regexp.
".$args"-match'^(\.(2(?!5?[6-9])|1|(?!0\B))\d\d?){4}$'

Try it online!
Thanks @Olivier Grégoire for the original regular expression.

You shouldn't need to call |% t*g since PowerShell will automatically cast the right-hand-side of -eq as a string, because the left-hand-side is a string. -- try{+("$args"-eq[IPAddress]::Parse($args))}catch{0}

You can carve 2 bytes from the "don't use a .NET lib" version by using my regex (adapted to the insert-a-period trick, which of course can't be in my version because it's a pure regex): https://tio.run/##fZLRToMwFIbveYraVEcjnBQoKCYG44UvIWrIKM4EA1KIJsCz4xlbyNw625vyf/3/c2hbV9@q0RtVlhMryD3pJwosa941dT@zdr1Zvdop2L6dXITJc@TGL3zwBvwS6SPnaZ7mCe/lyFbTaFkPtkVwODb1wIsEeAJ8KShxCGubTvGFxj4I4UHgg7yZcZGV@oCDDwGcAwZdYNxcLQxNLiznRbeATRl6wUgG0mDDsPkvBATy1LdN2@cd9/gP2k5XnEXXRheZp4lQcjCcY4qN47FIENRM5dP2zOKYntKi6T5aUlZVrQ10dz8SQvqnrsXJQC5JP29j2mHqp1brVuX4rNjbTm2U7soWhSt8bUzPImX2XnfV12Lid8tuXGlqjdMv

Python 3: 81 78 70 69 66 bytes
['%d.%d.%d.%d'%(*x.to_bytes(4,'big'),)for x in range(16**8)].count

Loop over all possible IPv4 addresses, get the string representation and compare it to the input. It uh... takes a while to run.
EDIT: Removed 3 bytes by switching from full program to anonymous function.
EDIT2: Removed 8 bytes with help from xnor
EDIT3: Removed 1 byte by using an unpacked map instead of list comprehension
EDIT4: Removed 3 bytes by using list comprehension instead of the ipaddress module

I think your anonymous function can just be [str(ip_address(x))for x in range(256**4)].count. Also, 256**4 can be 16**8.

I like the extemely golfy while practically unusable approach :)

PHP 7+, 37 35 32 bytes
This uses the builtin function filter_var, to validate that it is an IPv4 address.
For it to work, you need to pass the key i over a GET request.
<?=filter_var($_GET[i],275,5**9);

Will output nothing (for a falsy result) or the IP (for a truthy result), depending on the result.
You can try this on:
http://sandbox.onlinephpfunctions.com/code/639c22281ea3ba753cf7431281486d8e6e66f68e
http://sandbox.onlinephpfunctions.com/code/ff6aaeb2b2d0e0ac43f48125de0549320bc071b4

This uses the following values directly:

275 = FILTER_VALIDATE_IP
1<<20 = 1048576 = FILTER_FLAG_IPV4
5**9 = 1953125 (which has the required bit as "1", for 1048576)

Thank you to Benoit Esnard for this tip that saved me 1 byte!
Thank you to Titus for reminding me of the changes to the challenge.

I've looked into using the function ip2long, but it works with non-complete IP addresses.
Non-complete IPv4 addresses are considered invalid in this challenge.
If they were allowed, this would be the final code (only for PHP 5.2.10):
<?=ip2long($_GET[i]);

Currently, it isn't explicit in the documentation that this will stop working (when passed an incomplete ip) with newer PHP versions.
After testing, confirmed that that was the case.
Thanks to nwellnhof for the tip!

Using 5**9 instead of 1<<20 saves one byte here: PHP uses & to test the IPv4 / IPv6 flags, so any number between 1048576 and 2097151 is valid.

In newer PHP versions, ip2long doesn't allow incomplete addresses.

@BenoitEsnard Thank you! I've added it to the answer

@nwellnhof After testing, I confirm that that is the case. However, I don't think it is a good idea to use it, since it isn't explicitly documented.

+!! is not required; the OP now accepts arbitrary truthy values.

@Titus Totally forgot about this. Thank you for reminding me

C (gcc) / POSIX, 26 bytes
f(s){s=inet_pton(2,s,&s);}

Try it online!
Works as 64-bit code on TIO but probably requires that sizeof(int) == sizeof(char*) on other platforms.

@TobySpeight Yes, if you're on x86, you should probably try in 32-bit mode (-m32).

I got it to work, by passing s as a char* (no access to a ILP32 system here), and yes, I was mixing up with inet_aton().

C# (Visual C# Interactive Compiler), 84 79 65 bytes
s=>s.Split('.').Sum(t=>byte.TryParse(t,out var b)&t==b+""?1:5)==4

Try it online!
-5 and -14 bytes saved thanks to @dana!
# C# (Visual C# Interactive Compiler), 61 bytes
s=>s.Count(c=>c==46)==3&IPAddress.TryParse(s,out IPAddress i)

Try it online!
This is a work in progress. The code use System.Net (+17 bytes if you count it). if you wonder why I count and parse:

The limitation with IPAddress.TryParse method is that it verifies if a string could be converted to IP address, thus if it is supplied with a string value like "5", it consider it as "0.0.0.5".

source
As @milk said in comment, it will indeed fail on leading zeroes. So, the 61 bytes one is not working.

@dana great. Nicely done! Four more and it will beat the 61 bytes solutions!

Python 2, 85 82 81 bytes
-1 byte thanks to Kevin Cruijssen
from ipaddress import*
I=input()
try:r=I==str(IPv4Address(I))
except:r=0
print~~r

Try it online!
113 byte answer is deleted as it fails for 1.1.1.1e-80

You can golf print 1*r to print~~r. +1 though, since it seem to work for all possible test cases suggested thus far. PS: Your 113 byte answer fails for 1.1.1.1e-80.

@KevinCruijssen Thanks! Didn't think about such notation of numbers

Isn't ipaddress a Python 3 module?

@Farhan.K Dunno, but it works in TIO

Japt, 17 15 bytes
q.
Ê¶4«Uk#ÿòs)Ê

Try it or run all test cases or verify additional test cases from challenge comments

Explanation
We split to an array on ., check that the length of that array is equal to 4 AND that the length when all elements in the range ["0","255"] are removed from it is falsey (0).
                 :Implicit input of string U
q.               :Split on "."
\n               :Reassign resulting array to U
Ê                :Length of U
 ¶4              :Equals 4?
   «             :&&!
    Uk           :Remove from U
      #ÿ         :  255
        ò        :  Range [0,255]
         s       :  Convert each to a string
          )      :End removal
           Ê     :Length of resulting array

Nice answer. Also verified for all suggested test cases thus far. Curious to see that explanation.

@KevinCruijssen, explanation added. Thanks for those additional test cases.

ECMAScript pure regex, 41 bytes
^((2(?!5?[6-9])|1|(?!0\B))\d\d?\.?\b){4}$
Try it online!
Try it on regex101
I think the logic in this regex speaks for itself, so I will merely pretty-print but not comment it:
^
(
    (
        2(?!5?[6-9])
    |
        1
    |
        (?!0\B)
    )
    \d\d?
    \.?\b
){4}
$

This can be used to shave 2 bytes off the following other answers:

Olivier Grégoire (Java (JDK))
l4m2 (JavaScript (Node.js))
mazzy (PowerShell)
Kevin Cruijssen (Retina)

Some alternative 41 byte versions:
^((2(?!5?[6-9])|1|(?!0\d))\d\d?\.?\b){4}$
^(((2(?!5?[6-9])|1|(?!0))\d)?\d\.?\b){4}$
^(((2(?!5?[6-9])|1)\d|[1-9]?)\d\.?\b){4}$
Here is an alternative version that allows leading zeros, but does so consistently (octets may be represented by a maximum of 3 decimal digits):
^((2(?!5?[6-9])|1|0?)\d\d?\.?\b){4}$
Or allow any number of leading zeros:
^(0*(2(?!5?[6-9])|1?)\d\d?\.?\b){4}$
Or if allowed to have undefined behavior regarding leading zeros (as it so happens, a leading zero is only allowed only in 2-digit octets):
^((2(?!5?[6-9])|1?)\d\d?\.?\b){4}$

\b and \B... it's smart!

@mazzy Yes, those two really come in handy! I could've used (?!0\d) instead, but I like \B better!

The powershell answer doesn't get shorter with your regexp. I'm sorry. Quotes are needed to convert an array to a string. Try it online!

@mazzy Note that I said my regex "can be used" to shave 2 bytes off your answers: Try it online! - I mean when it is adapted to the same insert-a-period trick.

The \.?\b saved me a byte on my answer too, thanks!

Saved 3 bytes thx

sfk, 176 bytes
* was originally Bash + SFK but TIO has since added a proper SFK wrapper
xex -i "_[lstart][1.3 digits].[1.3 digits].[1.3 digits].[1.3 digits][lend]_[part2]\n[part4]\n[part6]\n[part8]_" +xed _[lstart]0[digit]_999_ +hex +linelen +filt -+1 -+2 +linelen

Try it online!

Would first checking the error printout from nc [addr] 1 -w1 shorten this?

@Rogem nc accepts leading zeroes as well as IPv6 addresses, so I'd still have to handle those - and this is intended more as a sfk answer than a shell answer anyway.

Mathematica, 39 31 bytes
Original version:
¬FailureQ[Interpreter["IPAddress"][#]]&

Modified version (thanks to Misha Lavrov)
 AtomQ@*Interpreter["IPAddress"]

which returns True if the input is a valid IP address (try it).
In case you insist on getting 1 and 0 instead, then an additional 7 bytes would be necessary:
Boole/@AtomQ@*Interpreter["IPAddress"]

Since Interpreter["IPAddress"] returns a string for valid input, and some complicated failure object for invalid input, we can test for valid inputs with AtomQ[Interpreter["IPAddress"][#]]&, which can be further shortened to the function composition AtomQ@*Interpreter["IPAddress"]. Try it online!

Fails on an IPv6 address like 2001:0db8:85a3:0000:0000:8a2e:0370:7334.

Bash, 15 bytes
ipcalc -c `cat`

Try it online!
Outputs exit code 0 for truthy, 1 for falsy.

The echo $(($?)) part is not needed since programs are allowed to output their result via exit code.

Python 2, 93 89 67 53 bytes
[i==`int(i)&255`for i in input().split('.')]!=[1]*4>_

Try it online!
Thanks to Dennis for shaving another 14 bytes on the internal comparisons and exit code.
Special thanks to Jonathan Allan for shaving 22 bytes & a logic fix! Pesky try/except begone!
Taking properly formatted strings instead of raw bytes shaves off 4 bytes, thanks Jo King.

Your check can be golfed to i==`int(i)&255` . Also, you can force an error with [...]!=[1]*4>_, since you're using exit codes anyway. Try it online!

@Dennis I don't understand what >_ does. The bitwise and is quite ingenious though... I was unsuccessful in combining those myself.

If the != returns False, Python short-circuits and nothing happens; the interpreter exits normally. If it returns True, >_ raises a NameError, because the variable _ is undefined.

Figures I chain comparisons in my answer and then miss the obvious result in your comment. Thanks for the explanation.

Python3 Bash* 60
*Also other shells. Any one for which the truthy/falsy test passes on a program exit code
read I
python3 -c "from ipaddress import*;IPv4Address('$I')"

Explanation
The trouble with a pure Python solutions is that a program crashing is considered indeterminate. We could use a "lot" of code to convert an exception into a proper truthy/fasly value. However, at some point the Python interpreter handles this uncaught exception and returns a non-zero exit code. For the low-low cost of changing languages to your favourite Unix shell, we can save quite a bit of code!
Of course, this is vulnerable to injection attacks... Inputs such as 1.1.1.1'); print('Doing Something Evil are an unmitigated threat!

(Explanation it is (not Explaination).)

@PeterMortensen Yikes. It was even underlined in red. My browser tried to save me, but I wouldn't listen. Thanks for catching that!

Full programs are allowed to output via exit codes, therefore this could be 43 bytes.

@BMO Interesting. Thanks for pointing that out! I think the problem definiiton changed from "Truthy/Falsy" to also allowing arbitrary output since I posted this, but I could have just not noticed before :)

JavaScript (ES6), 49 bytes
Returns a Boolean value.
s=>[0,1,2,3].map(i=>s.split`.`[i]&255).join`.`==s

Try it online!

Red, 106 bytes
func[s][if error? try[t: load s][return off]if 4 <> length? t[return off]s =
form as-ipv4 t/1 t/2 t/3 t/4]

Try it online!
Returnd true or false
Explanation:
f: func [ s ] [
    if error? try [                  ; checks if the execution of the next block result in an error
        t: load s                    ; loading a string separated by '.' gives a tuple
    ] [                              ; each part of which must be in the range 0..255
        return off                   ; if there's an error, return 'false'
    ]
    if 4 <> length? t [              ; if the tuple doesn't have exactly 4 parts
        return off                   ; return 'false'
    ]
    s = form as-ipv4 t/1 t/2 t/3 t/4 ; is the input equal to its parts converted to an IP adress
]

Charcoal, 45 21 bytes
Ｉ∧⁼№θ.³¬Φ⪪θ.¬№Ｅ²⁵⁶Ｉλι

Try it online! Link is to verbose version of code. Edit: Saved 24 bytes by porting @Shaggy's Japt answer. Explanation:
    θ                   Input string
   №                    Count occurrences of
     .                  Literal `.`
  ⁼                     Equal to
      ³                 Literal 3
 ∧                      Logical And
       ¬                Logical Not
          θ             Input string
         ⪪              Split on
           .            Literal `.`
        Φ               Filter by
            ¬           Logical Not
               ²⁵⁶      Literal 256
              Ｅ         Map over implicit range
                   λ    Map value
                  Ｉ     Cast to string
             №          Count occurrences of
                    ι   Filter value
Ｉ                       Cast to string
                        Implicitly print

Fails for test cases with negative integers like 123.-50.0.12 or 1.1.1.-80. Everything else seems to work fine. So the <256 check should be in [0,255] instead.

@KevinCruijssen Actually the code to filter out invalid characters wasn't working because I forgot to change the variable in the inner loop. Should be fixed now.

Python 3, 109 93 bytes
import re
lambda x:bool(re.match(r'^((25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(\.(?!$)|$)){4}$',x))

Explanation
Each octet can be 0 - 255 :

starts with 25 and having 0-5 as last digit
start with 2, has 0-4 as second digit and any digit at the end
starts with 1, and 00 - 99 as rest digits
has only 2 digits - 1-9 being the first one and any digit thereafter
or just a single digit

An octet can end with a (.) or just end, with the condition that it cannot do both , the negative lookahead (?!$) takes care of this case
Thanks @Zachary for making me realize I can discard spaces (since it is code golf)
Thanks @DLosc for the improvements and making me realize my mistake, its been corrected now.

Some explanation for this might help.

x: re.match=>x:re.match; , x => ,x, and ) is => )is should save 3 bytes. Also, in the regex,  you can use \d for each occurrence of [0-9], and [1]=>1. This seems like a great first post, though!

[1-9][0-9]|[0-9] can become [1-9]\d|\d (per Zacharý's advice), which can become [1-9]?\d. Also, instead of testing re.match(...)is not None, you can do bool(re.match(...)) since match objects are truthy and None is falsey. :)

Hmm. Actually, this fails on the test case 1.2.3.4.5 (and also 1.2.3.4., which isn't in the official list of test cases), because it can match a period instead of end-of-string after the fourth number.

Retina, 46 44 bytes
^
.
^(\.(25[0-5]|(2[0-4]|1\d|[1-9])?\d)){4}$

Port of @OlivierGrégoire's Java answer, so make sure to upvote him!
-2 bytes thanks to @Neil.
Try it online.
Explanation:
^
.                           # Prepend a dot "." before the (implicit) input
^...$                       # Check if the entire string matches the following regex
                            # exactly, resulting in 1/0 as truthy/falsey:
 (                          #  Open a capture group
  \.                        #   A dot "."
    (25[0-5]                #   Followed by a number in the range [250,255]
    |(2[0-4]|         ) \d) #   or by a number in the range [200,249]
    |(      |1\d|     ) \d) #   or by a number in the range [100,199]
    |(          |[1-9]) \d) #   or by a number in the range [10,99]
    |(                )?\d) #   or by a number in the range [0,9]
 )                          #  Close capture group
  {4}                       #  This capture group should match 4 times after each other

My attempt (which I didn't post because the question got put on hold at the time) was the same length, but didn't have the \d group optimisation, so you can save two bytes because you don't need the M specification on the last line.

I managed to get Retina down to 42 bytes by porting the Perl 6 answer but this answer also works in 0.8.2 which my port doesn't.

Stax, 14 bytes
∞n·Θ3ª&JH‼∙*~Γ

Run and debug it
Unpacked, ungolfed, and commented, it looks like this.
VB      constant 256
r       [0 .. 255]
'|*     coerce and string-join with "|"; i.e. "0|1|2|3 ... 254|255"
:{      parenthesize to "(0|1|2|3 ... 254|255)"
]4*     make 4-length array of number pattern
.\.*    string join with "\\."; this forms the complete regex
|Q      is the input a complete match for the regex?

Run this one

Surprised to know that you made the language Stax! it is working well.

Thanks!  The space of golfing languages is surprisingly crowded, and I'm not sure if stax can justify its own existence on its merits, but my main goal was just to see if I could do it and maybe learn something.  It ended up being more fun than expected.

Perl 5 -pF/\./, 47 bytes
$\=@F==4&&!/[^0-9.]/;$\&&=!/^0./&&$_<256for@F}{

Try it online!

Retina, 42 41 bytes
~(K`

255*
["^(("|'|]")\.?\b){4}$"L$`
$.`

Try it online! Based on a previous version of @nwellnhof's Perl 6 answer, but 1 byte saved by stealing the \.?\b trick from @Deadcode's answer. Explanation:
K`

Clear the work area.
255*

Insert 255 characters.
["^(("|'|]")\.?\b){4}$"L$`
$.`

Generate the range 0..255 separated with |s, prefixed with ^((, and suffixed with )\.?\b){4}$, thus building the regular expression ^((0|1|...255)\.?\b){4}$.
~(

Evaluate that on the original input.

Jelly, 11 bytes
⁹ḶṾ€ṗ4j€”.ċ

A monadic link accepting a list of characters which yields \$1\$ if it's a valid address and \$0\$ otherwise. Builds a list of all \$256^4=4294967296\$ addresses and then counts the number of occurrences of the input therein.
Here's similar @ Try it online! that uses \$16\$ (⁴) rather than \$256\$ (⁹), since the method is so inefficient!
How?
⁹ḶṾ€ṗ4j€”.ċ - Link: list of characters, S
⁹           - literal 256
 Ḷ          - lowered range = [0,1,2,...,254,255]
  Ṿ€        - unevaluate €ach = ['0','1',...,['2','5','4'],['2','5','5']]
    ṗ4      - 4th Cartesian power = ALL 256^4 lists of 4 of them
            -               (e.g.: ['0',['2','5','5'],'9',['1','0']])
        ”.  - literal '.' character
      j€    - join for €ach (e.g. ['0','.','2','5','5','.','9','.','1','0'] = "0.255.9.10")
          ċ - count occurrences of right (S) in left (that big list)

Why does the version with 65,536 IPs take 1.8 seconds? o_O

C (gcc), 287 197 bytes
#import<regex.h>
g;f(char*s){regex_t r;g=regcomp(&r,"^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$",1);g=regexec(&r,s,0,0,0);return !g;}

Try it online!
Thanks to Logern for the big save !

197 bytes Try it online!Saved bytes by removing types, replacing REG_EXTENDED with its int value, removing some of the includes, instead using import, renaming variables and removing the ternary in the return.

188 bytes

Pip, 25 16 bytes
a~=X,256RL4J"\."

Takes the candidate IP address as a command-line argument. Try it online! or Verify all test cases
Explanation
Regex solution, essentially a port of recursive's Stax answer.
                  a is 1st cmdline arg (implicit)
    ,256          Range(256), i.e. [0 1 2 ... 255]
   X              To regex: creates a regex that matches any item from that list
                  i.e. essentially `(0|1|2|...|255)`
        RL4       Create a list with 4 copies of that regex
           J"\."  Join on this string
 ~=               Regex full-match
a                 against the input

R, 59 bytes
Passes special cases not in test with periods at start/end
function(s)length(a<-scan(,t=s,s,,,"."))==4&all(a%in%0:255)

Try it online!

JavaScript, 89 bytes
(_,r=`(${[...Array(256).keys()].join`|`})`)=>RegExp(`^${(r+'\\.').repeat(3)+r}$`).test(_)

Try it online!
Create RegExp capture groups from indexes of an array having length 256 for range 0-255 joined with | and followed by escaped . character (^(0|1...|255)\.(0|1...|255)\.(0|1...|255)\.(0|1...|255)$) repeated 3 times closing with joined array followed by $ to match end of string, return true or false result of input passed to RegExp.prototype.test().

Ruby, 123 107 bytes
Try it online!
a=gets.chomp
e=a.split'.'
(p 0;exit)if(e.map(&:to_i).join'.')!=a
p(e.all?{|i|(0..255)===i.to_i}&&e.size==4)

This could definitely be shorter, probably with a regex of some sort, but I wanted to do it without a regex.
Thanks to MegaTom for Array#all?
0 or false is falsy; true is truthy.
Explanation:
The input is taken from stdin. It's split into an array of the numbers (as strings) on the periods.
If the array isn't the same as it is with the elements converted to numbers and back to strings, the program outputs 0 and exits. This eliminates cases with leading zeros and illegal characters.
The array is converted to an array of true/false values representing whether the value is between 0 and 255, inclusive.
true is outputted if the array is only true values, meaning that all the numbers were between 0 and 255, and only if it has exactly 4 elements, meaning that there were 4 original numbers. false is outputted otherwise, meaning invalid numbers (higher than 255) or too many numbers.

Hello and welcome to PPCG. Could you possibly provide a link to an online interpreter for ease of verifying your solution?

I've added a TIO link. The default input is 255.255.255.255.

I think the all? method could make this code a good bit shorter.

Thanks! I didn't think of that.

APL(NARS), 45 chars
{'...'≢⍵∼⎕D:0⋄4≠+/255≥⍎¨a←⍵⊂⍨⍵≠'.':0⋄a≡⍕¨⍎¨a}

test
  f←{'...'≢⍵∼⎕D:0⋄4≠+/255≥⍎¨a←⍵⊂⍨⍵≠'.':0⋄a≡⍕¨⍎¨a}
  f '1.160.10.240'
1
  f '192.001.32.47'
0
  f '1.2.3.'
0
  f '1.2.3'
0

Batch, 53 bytes
@(ping -4 %1&echo g 255.255.255.255 w)|find/c"g %1 w"

Disconnect your Internet connection first to avoid the standard loophole.
I can't find information on how to avoid ^".

Deleted cuz can't handle 255.255.255.255

APL(NARS) 50 chars, 100 bytes
{'...'≢⍵∼⎕D:0⋄4≠≢w←⍵⊂⍨⍵≠'.':0⋄w≢⍕¨m←⍎¨w:0⋄256>⌈/m}

test:
  p←{'...'≢⍵∼⎕D:0⋄4≠≢w←⍵⊂⍨⍵≠'.':0⋄w≢⍕¨m←⍎¨w:0⋄256>⌈/m}
  {⍞←'[',⍵,'=',(p ⍵),']'⋄⍬}¨a
[1.160.10.240= 1 ][192.001.32.47= 0 ][1.2.3.= 0 ][0.00.10.255= 0 ][1.2.$.4= 0 ][255.160.0.34= 1 ][.1.1.1= 0 ][1..1.1.1= 0 ][1.1.1.-0= 0 ][.1.1.+1= 0 ][1 1 1 1= 0 ][1= 0 ][10.300.4.0= 0 ][10.4F.10.99= 0 ][fruit loops= 0 ][1.2.3.4.5= 0 ][0.0.0.0= 1 ][0.0 0.0.= 0 ][1.23..4= 0 ][1:1:1:1:1:1:1:1= 0 ]

Scala, 87 bytes
A port of @Olivier Grégoire's answer.
Try it online!
val f:String=>Boolean=s=>("." + s).matches("(\\.(25[0-5]|(2[0-4]|1\\d|[1-9])?\\d)){4}")

Thunno 2, 15 bytes
'./Ẋl4=ɠL€ṘxƇp&

Try it online!
Explanation
'./Ẋl4=ɠL€ṘxƇp&  '# Implicit input
'./              '# Split the input on "."s
   Ẋ              # Store this in x without popping
    l4=           # Check if the length equals 4
       ɠL         # Push the range [0..255]
         €Ṙ       # Convert each to a string
           xƇp    # Check if each of the values in x
                  # is in this list of strings
                  # (NOTE: this checks three things at once:
                  #   1. all the parts are numbers
                  #   2. all of them are in the range [0..255]
                  #   3. none of them have leading zeros)
              &   # Check if both things are true
                  # Implicit output

Go, 81 bytes
import."net/netip"
func f(s string)bool{a,e:=ParseAddr(s)
return e==nil&&a.Is4()}

Attempt This Online!
Uses the net/netip package from the standard library.
Go, 119 bytes
import."regexp"
func f(s string)bool{return MustCompile(`^(\.(25[0-5]|(2[0-4]|1\d|[1-9])?\d)){4}$`).MatchString("."+s)}

Attempt This Online!
Using the regex from @Olivier Grégoire's post.

PHP, 27 26 24 Bytes
<?=+!!ip2long($argv[1]);

Based on @rexkogitans and @nwellnhof solutions
Fails for 0.0.0.0 because PHP internal function 0.0.0.0 is not considered a valid IP address
Try it!


text:
Find the closest RGB color
Input: A valid 6 HEX digit color code wihout a # prefix
Valid:

000000
FF00FF
ABC123

Your job is to find to which one of these:
Red:   FF0000
Green: 00FF00
Blue:  0000FF
White: FFFFFF
Black: 000000

the input color is the closest too, in this case you try to only match it to black or white when the RGB is the same value for all 3 (the color is grey, or black or white ofc), if there is a "tie" you can pick whichever
The output is one of the aforementioned color codes.
Examples:
Input: FF0000, Output: FF0000
Input: F10000, Output: FF0000
Input: 22FF00, Output: 00FF00
Input: FFFF00, Output: FF0000 or 00FF00
Input: 111112, Output: 0000FF
Input: 010101, Output: 000000
Input: A0A0A0, Output: FFFFFF

This is code-golf, so fewest bytes will win!

Ah my mistake lol

Define "closest". What distance definition should be use?

You can take the RGB parts as seperate values R[FF], G[FF], B[FF] and check which RGB part of the input number has the highest value, except for grey, black and white colors. So F0F0F1 would be blue and F2F0F1 would be red since the red part of the RGB code is the greatest

@KevinCruijssen "if there is a tie you can pick whichever"

@Arnauld No; you're only allowed to pick 000000 and FFFFFF when the color is completely grey.

@HyperNeutrino Ah, ok. I missed that part.

@LuisMendo As I read it, the function is var masked = [color >> 16, color >> 8 & 0xff, color & 0xff]; if (masked.allEqual()) return (~color&24)>color ? Black : White; else return [Red, Green, Blue][masked.indexOf(masked.max)]

Are we allowed to take input as a list of 3 hex values, or even better, 3 integers from 0 to 255?

Does input/output case matter?

input has to be uppercase and in the same style as shown (6 uppercase hex chars)

@KevinCruijssen Why 888888? Surely 808080 is nearer to FFFFFF than 000000?

@Neil Ah, you're completely right..

05AB1E, 32 31 30 bytes
3äHDËiнžy@Di'F}6∍ë¾5∍sZk·„FFsǝ

Not really happy with it, so will see if I can golf it further..
When two RGB parts are the largest and equal, it will use the first one (i.e. 11ABAB will result in 00FF00). When all three parts are equal it will output 000000 when it's the range [00,7F] and FFFFFF for the range [80,FF].
Try it online or verify all test cases.
Explanation:
3ä                  # Split the (implicit) input into three parts
  H                 # Convert each part from Hexadecimal to a base-10 decimal
   D                # Duplicate this list
    Ëi              # If all three values are equal:
      н             #  Leave only the first item of the list
       žy@          #  Check if it's larger than or equal to 128 ("80" in hex)
          D         #  Duplicate this truthy/falsey result
           i  }     #  If the result is truthy:
            'F     '#   Push "F"
                    #  (Implicit else:)
                    #   (Take the duplicated falsey 0)
               6∍   #  Lenghten it to size 6
     ë              # Else:
      ¾5∍           #  Push 0, lenghtened to size 5: "00000"
         s          #  Swap so the duplicated list is at the top of the stack
          Z         #  Take the max (without popping)
           k        #  Take the index of this max in the list
            ·       #  Double this index
             „FFsǝ  #  Replace the "0" in "00000" at this doubled index with "FF"
                    # (And output the top of the stack implicitly as result)

Python 3, 163 162 150 bytes
-1 byte thanks to Kevin Cruijssen
-12 bytes by some small tricks (thanks to HyperNeutrino for the "0F"[bool] idea)
def f(i):m=i[:2],i[2:4],i[4:];a,b,c=(e==max(m)for e in m);return"".join("0F"[e]*2for e in([i[:2]>"7E"]*3if a&b&c else([a,b,c]if a^b^c else[a,1^a,0])))

Try it online!
I was able to find a solution without turning the three hex values to integers (mainly because 'A' comes later in the ASCII table than '9', and so '9'<'A' is true). I am not really happy with some parts, but this was the shortest I could find.
Because this solution uses a different approach than the other python3 solution, I'm posting this as a seperate answer.

Nice answer, +1 from me. You can remove the space at else "00" for -1 byte.

JavaScript (ES6), 94 bytes
s=>'00FF000000FFFFFF'.substr(([r,g,b]=s.match(/../g),r+g==g+b?r<'8'?4:10:r>b?r>g&&2:b>g&&6),6)

Try it online!
How?
We could convert a bitmask to upper case hexadecimal with leading zeros using:
.slice(1).toString(16).toUpperCase()

But that would cost 36 bytes, and building such a bitmask is not especially cheap either.
It's significantly shorter to extract the relevant substring from "00FF000000FFFFFF", using the following offsets:
 pattern | offset | 00FF000000FFFFFF
---------+--------+------------------
 000000  |    4   |     ^^^^^^
 FFFFFF  |   10   |           ^^^^^^
 FF0000  |    2   |   ^^^^^^
 00FF00  |    0   | ^^^^^^
 0000FF  |    6   |       ^^^^^^

Python 3, 219 112 110 bytes
def f(s):h=max([0,1,2],key=lambda i:s[i*2:][:2]);return["00"*h+"FF"+"00"*(2-h),"F0"[s[:2]<"80"]*6][s==s[:2]*3]

Try it online!
-107 bytes by not being bad; drew a bit of inspiration from @Heitera by avoiding input integer parsing entirely.
-2 bytes thanks to @Heitera

You can at least shorten this to 193 bytes by turning it into a true function and just define g, h once.

@Heiteira Thanks! I've already gotten it to 112 bytes with a bit of inspiration from your answer.

"0"*h*2 can be shortened to "00"*h, saving 1 byte. The same with "0"*(2-h)*2

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
Validate a barcode
A barcode of EAN-13 symbology consists of 13 digits (0-9). The last digit of this barcode is its check digit. It is calculated by the following means (the barcode 8923642469559 is used as an example):

Starting from the second digit, sum up all alternating digits and multiply the sum by 3:
8 9 2 3 6 4 2 4 6 9 5 5 9
  |   |   |   |   |   |
  9 + 3 + 4 + 4 + 9 + 5 = 34
                           |
                           34 × 3 = 102

Then, sum up all of the remaining digits, but do not include the last digit:
8 9 2 3 6 4 2 4 6 9 5 5 9
|   |   |   |   |   |
8 + 2 + 6 + 2 + 6 + 5 = 29

Add the numbers obtained in steps 1 and 2 together:
29 + 102 = 131

The number you should add to the result of step 3 to get to the next multiple of 10 (140 in this case) is the check digit.

If the check digit of the barcode matches the one calculated as explained earlier, the barcode is valid.

More examples:
6537263729385 is valid.
1902956847427 is valid.
9346735877246 is invalid. The check digit should be 3, not 6.

Your goal is to write a program that will:

Receive a barcode as its input.
Check whether the barcode is valid
Return 1 (or equivalent) if the barcode is valid, 0 (or equivalent) otherwise.

This is code-golf, so the shortest code in terms of bytes wins.

why did the last digit (9) become a 4

Sorry, will fix it :)

I recommend removing the 13-char check because it's trivial but annoying in certain languages. Up to you though whether you want to do input validation (most people leave it out but you can leave it in)

OK, I will do that.

Can we take input as a list of digits? (sorry for all the questions)

What do you mean by list of digits? (Never mind the questions :))

(Assuming you didn't) I'd recommend posting challenges to The Sandbox first in the future so these questions can be addressed before the challenge is posted to the main site.

Let us continue this discussion in chat.

Quite related, but for EAN-8 instead of EAN-13.

Use this to generate valid barcode.

You may want to edit your challenge description stating the input should be a number or string as you mentioned in the chat, since I see a few answers assuming they can input a list of digits (flexible I/O is usually the default).

Ruby, 45 40 37 bytes
->n{(n+n.scan(/.(.)/)*''*2).sum%10<1}

Try it online!

Python 3, 55 bytes
lambda s:not sum(int(i)*d for i,d in zip(s,[1,3]*7))%10

Try it online!

05AB1E, 15 10 bytes
εNÉ·>*}OTÖ

Try it online!
Explanation
    ε     }      # apply to each digit
     NÉ          # is the current index odd?
       ·>        # double and increment(yielding 1 or 3)
         *       # multiply by the current number
           O     # sum all modified digits
            TÖ   # is evenly divisible by 10

Nice answer! Definitely shorter than what I was working on. I like the x you've used in combination with O to sum the entire stack in one go to combine the *3 and + of the two numbers. As well as the (T% to get the remainder.

@KevinCruijssen: The comparison feels a bit surperflous. Can you think of a counterexample to εNÉ·>*}OTÖ working?

Hmm, not really. It would be useful to have more test cases than the 4 we have now. Can't really think of anything where S13S13∍*OTÖ would fail right now (so well done golfing 4 bytes). It also seems similar as the Python answer (and Jelly as well I think; I can't really read Jelly all that well).

Jelly, 10 bytes
D0;s2Sḅ3⁵ḍ

Try it online!
-4 bytes thanks to Kevin Cruijssen (semi-port @Dennis)

%⁵¬ can be ⁵ḍ, or you could golf it to 10 bytes: D0;s2Sḅ3⁵ḍ. with a semi-port of @Dennis♦' answer here.

@KevinCruijssen oh cool, thanks

Japt -!, 14 bytes
¬Ë*(Ev ª3Ãx %A

¬Ë*(Ev ª3Ãx %A  Full prgram.
¬               Convert to array -_-
 Ë              Map
  *             Multiply current number by
   (Ev ª3Ã      1 if index is even, else 3
          x     sum
           %A   mod 10?

Try it online!

It may be in the comments instead of question, but you aren't allowed to take the input as a list of digits: Question from HyperNeutrino: "Can we take input as a list of digits? For example, instead of reading the barcode as "123", I'd read it as [1, 2, 3]" Response from OP: "No, it should be input as 123, string or number doesn't matter."

@KevinCruijssen Sorry, I though it was allowed :c

Yeah, I thought so too until I saw the comments in the chat.. >.> I've asked OP to add it to the challenge description (or just allow an array of digits since I/O is usually flexible by default..)

Perl 6, 29 26 bytes
{:1[.comb «*»(1,3)]%%10}

Try it online!
-3 bytes if a list of digits is acceptable.
Explanation
{                      }  # Anonymous Block
    .comb                 # Split into characters
          «*»(1,3)        # Multiply with 1 and 3 alternately
 :1[              ]       # Sum (conversion from base 1 is shorter than sum())
                   %%10   # Check if divisible by 10

Wolfram Language (Mathematica), 34 bytes
Check[#~BarcodeImage~"EAN13";1,0]&

Try it online!
A port of my EAN-8 answer.

Java 8, 69 67 62 bytes
n->{int s=0,m=3;for(;n>0;n/=10)s+=n%10*(m^=2);return s%10<1;}

-5 bytes thanks to @OlivierGrégoire.
-1 byte thanks to my own 1-year old answer for the Is my barcode valid? challenge, and @OlivierGrégoire to remind me of it.. xD
Try it online.
Explanation:
s->{               // Method with long parameter and boolean return-type
  int s=0,         //  Sum, starting at 0
      m=3;         //  Multiplier, starting at 3
  for(;n>0;        //  Loop as long as the input is not 0 yet
      n/=10)       //    After every iteration: integer-divide the input by 10
    s+=            //   Increase the sum by:
      n%10*        //    The last digit of the input multiplied by:
       (m^=2);     //    either 1 or 3 (alternating every iteration)
  return s%10<1;}  //  Then return whether the sum is divisible by 10

58 bytes by taking the digits as an array of integers.

@OlivierGrégoire OP disallowed it I'm afraid, although I've asked to reconsider the default flexible I/O rules. My 69-bytes version was the same as yours, except with added .getBytes()

Ok. The question itself wasn't clear on it. Anyways, here's a 62 bytes golf: n->{int s=0,i=3;for(;n>0;n/=10)s+=n%10*(i=4-i);return s%10<1;}

Also, indeed, the version was the same because I took your version, removed the .getBytes() and switch the input parameter just to show that different input meant shorter answer, before I saw that the chat showed that indeed that input method wasn't allowed.

@OlivierGrégoire Nice golf with i=4-i. And it indeed looked suspiciously the same including variable names. ;p

Actually, you could even take your answer as idea for a golf and gain one more byte: i^=2.

@OlivierGrégoire Lol, completely forgot about that answer. Funny how it's the exact same m++%2*2*i+i to (m=4-m)*i to (m^=2)*i (pretty obvious since the challenges are the same), hence the duplicated vote.

Retina 0.8.2, 23 22 bytes
.(.)
$&$1$1
.
$*
M`
1$

Try it online! Link includes test cases. Edit: Saved 1 byte thanks to Martin Ender's comment on @Leo's Retina answer to the EAN-8 question. Explanation:
.(.)
$&$1$1

Triplicate alternate digits.
.
$*

Convert each digit to unary.
M`

Count the number of character boundaries, which is one more than the number of characters.
1$

Check for divisibilty by 10, but allow for the 1 we just added.

APL (Dyalog Unicode), 15 bytes
0=10|⊢+.×1 3⍴⍨≢

Try it online!
Anonymous train, outputs 1 for True and 0 for False. TIO links to a prettified version of the output.
Totally not helped at all by @ngn or @dzaima (thanks guys).
How:
0=10|⊢+.×1 3⍴⍨≢ ⍝ Main fn
              ≢ ⍝ Tally the argument (will always be 13)
         1 3⍴⍨  ⍝ Reshape the vector (1 3) to 13 elements
     ⊢+.×       ⍝ Multiply the original vector by that, then sum
  10|           ⍝ Modulo 10
0=              ⍝ equals 0

Python 2, 50 bytes
lambda x,k=1,a=0:f(x/10,4-k,a+x*k)if x else a%10<1

Try it online!

Pyth, 11 10 bytes
!es*V*jT7l

Accepts input as a list of digits. Try it online here, or verify all test cases at once here.
!es*V*jT7lQQ   Implicit: Q=eval(input())
               Trailing QQ implied
      jT7      10 in base 7 - yields [1,3]
     *   lQ    Repeat the above len(input) times
   *V      Q   Vectorised multiply the above with the input
  s            Take the sum
 e             % 10
!              Logical not

Edit: saved a byte by replacing ,1 3 with jT7

R, 65 bytes
function(b,y=b%/%10^(12:0)%%10)!sum(y[-1],y[(1:6)*2]*2)%%-10+y[1]

Try it online!

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
The Written Digits Sequence
Here's a reasonably trivial sequence which is not in the Online Encyclopedia of Integer Sequences.
Start with an empty sequence then define each term as the number of characters required to write out, in English, all of the digits of the sequence so far without spaces.*
For reference the number of characters of all of the (base ten) digits in English are:
zero   one    two    three  four   five   six    seven  eight  nine
4      3      3      5      4      4      3      5      5      4

(Which is the start of both A52360 and A5589.)
This makes the first entry \$a(0) = 0\$ since there are zero digits present in the empty sequence.
This makes the second entry \$a(1) = 4\$ as it takes four characters to write "zero", the only digit present so far.
This makes the third entry \$a(2) = 8\$ as it takes four more characters to write the "four" for a total of eight to write "zerofour".
This makes the fourth entry \$a(3) = 13\$ as it takes five more characters to write "eight" for a total of thirteen to write "zerofoureight".
This makes the fifth entry \$a(4) = 21\$ as it takes eight more characters to write "onethree" for a total of twenty-one to write "zerofoureightonethree".
...and so on. Here are the first 100 entries:
0, 4, 8, 13, 21, 27, 35, 44, 52, 59, 67, 75, 84, 93, 102, 112, 121, 130, 142, 152, 162, 171, 182, 193, 205, 216, 225, 235, 247, 259, 270, 282, 293, 305, 318, 331, 344, 357, 371, 384, 398, 412, 422, 432, 444, 456, 467, 479, 492, 503, 516, 526, 536, 548, 561, 571, 583, 597, 610, 620, 630, 642, 652, 662, 671, 682, 693, 705, 718, 731, 744, 757, 771, 784, 798, 812, 823, 836, 849, 862, 873, 888, 903, 916, 926, 936, 948, 961, 971, 983, 997, 1010, 1024, 1038, 1055, 1070, 1086, 1101, 1114, 1127

* We could define it for other languages and/or other bases or with spaces of course
The challenge
Given \$n\$ output, in as few bytes of code as possible, any of:

The first \$n\$ terms of the sequence (should work for non-negative integers)
The value of \$a(n)\$  (should work for non-negative integers)
The \$n\$th term of the sequence (should work for positive integers - i.e. value of \$a(n-1)\$)

This is code-golf so the shortest answer in bytes wins for each language, and the shortest answer in bytes wins. Don't let golfing languages stop you from entering in your favourite language be it a practical one or an esoteric one!

By the first option, do you mean that 1) 1 should output [0] and 0 should output [] or 2) 0 should output [0] (as in my former answer)?

@EriktheOutgolfer I mean (1) as it should return the first n terms. That is, the options are "output the sequence up to but not including a(n)", "output a(n)", or "output a(n-1)".

So, a(x) = a(x-1) + f(a(x-1)) where f(x) is the amount of characters needed to write x?

@FireCubez yes, if a(0)=0 and f(x) is non-space characters to write the digits of x

Perl 6, 45 bytes
{({[+] @_.join.uninames>>.comb X-6}...*)[$_]}

Try it online!
No need for fancy moduloing when you can get the name of the digit directly! Anonymous code block that returns the nth value of the sequence, or you can pass in a range to get a list of values
Explanation:
{(                                     )[$_]}  # Index input into:
  {                               }...*        # An infinite sequence
                                               # Where each element is
   [+]   # The sum of
       @_.join  # All previous elements joined together
              .uninames  # The unicode names for each character
                         # These are names in the form "DIGIT ONE"
                       >>.comb  # Split each to lists of characters
                               X-6  # Subtract 6 from each

@JonathanAllan Ah, I had assumed you had allowed an infinite sequence as a return, sorry. I'll fix this

Nice, that's good :)

Nice! » is one byte, right? Also, [+] might be cuter and hint at how binary ops can become reducers but sum is also three bytes and in keeping with the rest of the solution which might not be the shortest but sure is the most elegant golf imo.

@raiph » is two bytes so it's interchangable.

Maybe this is cheating but doesn't Rakudo handle Latin1 source code correctly? If so, note that say '»'.encode('latin1').bytes  displays 1. :)

JavaScript (ES6), 69 68 61 58 bytes
Returns \$a(n)\$.
f=(n,s=0)=>n?f(n-1,[...s+''].map(d=>s+=(d+10)%23%3+3)|s):s

Try it online!
How?
A digit \$d\$ is converted to a number \$n\$ of letters with:
$$n=(((d \times 100 + 10) \bmod 23) \bmod 3)+3$$
 d | *100 | +10 | MOD 23 | MOD 3 | +3 | word
---+------+-----+--------+-------+----+-------
 0 |    0 |  10 |   10   |   1   |  4 | zero
 1 |  100 | 110 |   18   |   0   |  3 | one
 2 |  200 | 210 |    3   |   0   |  3 | two
 3 |  300 | 310 |   11   |   2   |  5 | three
 4 |  400 | 410 |   19   |   1   |  4 | four
 5 |  500 | 510 |    4   |   1   |  4 | five
 6 |  600 | 610 |   12   |   0   |  3 | six
 7 |  700 | 710 |   20   |   2   |  5 | seven
 8 |  800 | 810 |    5   |   2   |  5 | eight
 9 |  900 | 910 |   13   |   1   |  4 | nine

Because the number is split into digit characters, we can process \$d\times 100+10\$ by just adding \$10\$ (as a string concatenation).

Stax, 14 13 bytes
┴♥7[╘⌂←─üTJ‼√

Run and debug it
The key insight here is that digit d requires ((4 - 2 * d) // 3) % 3 + 3 letters to spell.  (That's python integer division, and python-style non-negative modulus)

Pip, 21 bytes
Lai+:$+4335443554@^Pi

Takes input \$n\$ as a command-line argument and outputs the first \$n\$ terms. Try it online!
Explanation
Lai+:$+4335443554@^Pi
                       a is 1st cmdline arg; i is 0 (implicit)
La                     Loop (a) times:
                   Pi   Print i
                  ^     Split it into a list of characters (i.e. digits)
       4335443554@      Use each digit to index into this number, giving the length of the
                        name of the digit (0 -> 4, 1 -> 3, etc.)
     $+                 Sum the results
  i+:                   Increment i by that amount

I read this as large constant to the power of pi and was monumentally impressed. (It's still impressive, but my initial interpretation was just.. more)

05AB1E, 15 14 bytes
ÎFD•Qb₁ñ•sSèOO

Try it online!
Explanation
Î                # initialize stack with 0 and input
 F               # input times do:
  D              # duplicate the current number
         sSè     # and use one copy to index into
   •Qb₁ñ•        # 433544355
            OO   # sum digits and sum the stack

Wolfram Language (Mathematica), 57 bytes
Nest[#+Tr@StringLength@IntegerName@IntegerDigits@#&,0,#]&

Try it online!
Tr@StringLength@IntegerName@IntegerDigits@#& lists the digits of #, converts each of them to an English name, counts the length, and sums the results. Lots of things thread over lists, it's very exciting. Then we just iteratively apply the definition.
TIO complains that it doesn't have an Internet connection, but I'm not sure why, because it figures out the right answer anyway. Maybe it's checking for updates to the names of integers?
Outputs the value of \$a(n)\$, but we could change it to give the entire list \$a(0), a(1), \dots, a(n)\$ by changing Nest to NestList.

Clean, 82 bytes
import StdEnv,Text
$a=iter a(\n=n+sum[3+indexOf{c}" 9810324765"rem 3\\c<-:""<+n])0

Try it online!

APL (Dyalog Unicode), 29 28 bytes
{{⍵++/3+3|⌊3÷⍨4-2×⍎¨⍕⍵}⍣⍵⊢0}

Try it online!
Dfn. Prints \$f(input)\$
Thanks to the guys @The APL Orchard for helping with this one:
@ngn for 2 bytes; @H.PWiz for 3 4 bytes.
Now using @recursive's formula.
How:
{{⍵++/3+3|⌊3÷⍨4-2×⍎¨⍕⍵}⍣⍵⊢0} ⍝ Main fn

 {                     }⍣⍵⊢0 ⍝ Starting with 0, repeat (⍣) the inner fn input times
      3+3|⌊3÷⍨4-2×⍎¨⍕⍵      ⍝ @recursive's formula
  ⍵++/                       ⍝ Sum with the input.

Python 2, 71 bytes
f=lambda n,k=0:n and f(n-1,k+sum(632179420>>3*int(d)&7for d in`k`))or k

Try it online!

f=lambda n,k=0:n and f(n-1,k+sum(632179420>>3*int(d)&7for d in\k`))or k` is the same count but avoids outputting an enclosing list.

Looks like recursive's algorithm from their staxx answer would save 2 bytes. I do like this though!

Python 2, 61 bytes
n=0
exec"for c in`n`:n+=(4-2*int(c))/3%3+3\n"*input()
print n

Try it online!
Uses recursive's digit count mapping.

Python 2, 63 bytes
f=lambda n:n and f(n-1)+sum((4-2*int(c))/3%3+3for c in`f(n-1)`)

Try it online!
A recursive function version. It takes exponential time to run because it has two recursive calls to f(n-1).

Nice! I'm curious if the expression-finding script you've mentioned using before finds this expression (or maybe an even shorter one?)

@Lynn I had run the script but didn't find a better one. 13 chars is too much for a full search, and didn't find anything at most 9 chars long. When I cut off the +3 and limited it to arithmetic operators (no bitwise) and numbers <=4, I found this solution but nothing shorter or even the same length except equivalents.

Pyth, 21 bytes
u+Gs@L+L3jC\᯻3jGTQ0

Try it online here.
u+Gs@L+L3jC\᯻3jGTQ0   Implicit: Q=eval(input()), T=10

u                Q0   Starting at 0, repeat the following Q times, with current value as G:
          C\᯻           Get character code 7163
         j   3          Convert the above to base 3, yields [1, 0, 0, 2, 1, 1, 0, 2, 2]
      +L3               Add 3 to each to generate digit length dictionary
              jGT       Get digits of G (convert to base 10)
    @L                  Lookup each value in the above in the dictionary, modular indexing
   s                    Take the sum
 +G                     Add G to the above

᯻ very likely isn't a single byte in Pyth's codepage. (I think it uses UTF-8, in which case it's 3 bytes, and j7163 3 has the same length; but tio.run says Pyth has a SBCS. Mysterious!)

@Lynn You're absolutely right, I'd forgotten about the byte count, my bad. I'll leave the code as is for now and update the byte count

MathGolf, 17 bytes
0\{_▒♀*♂+L%3%3+Σ+

Try it online!
This uses Arnauld's method. Outputs the nth element of the sequence.. If the empty string is okay for a(0), then we could remove the 0\ at the beginning.
Explanation:
0\                 Setup 0 as the counter
  {                Loop input times
   _▒              Duplicate counter and split to list of digits
     ♀*            Multiply each element by 100
       ♂+          Add 10
         L%        Modulo by 23
           3%      Modulo by 3
             3+    Add 3
               Σ   Sum list
                +  And add to counter

Ruby, 54 bytes
->n{s=0;n.times{s+=s.digits.sum{|d|4+392[d]-70[d]}};s}

Try it online!

Java (JDK), 95 bytes
n->{int l=0;while(n-->0)l+=(""+l).chars().map(x->"4335443554".charAt(x-48)-48).sum();return l;}

Try it online!

Vyxal, 13 bytes
0?(»Þ([ǒ»Ȯİ∑Ṡ

Try it Online!
A port of the 05AB1E answer
Explained
0?(»Þ([ǒ»Ȯİ∑Ṡ
0?              # Push 0 followed by the input number
  (             # Input number of times:
   »Þ([ǒ»       #     Push the number 433544355
         Ȯİ     #     And get the indexes corresponding to the numbers in the second last item on the stack
           ∑Ṡ   #     Sum that list and then the stack

JavaScript (Node.js), 82 bytes
f=(a,b=1,s=4)=>a?b<a?f(a,++b,s+=[...s+''].reduce((q,w)=>+'4335443554'[w]+q,0)):s:0

Try it online!

Jelly, 13 bytes
ṃ“vẋç’ḃ5¤S+Ɗ¡

Try it online!
0-indexed.
Full program; takes input from STDIN.

Red, 99 95 bytes
func[n][d:"4335443554"s: 0 repeat i n[print s foreach c form s[s: s - 48 + do d/(-47 + do c)]]]

Try it online!
Just a straightforward solution.

J, 37 bytes
(+1#.|(3+3|23|10+100*]),.&.":)@]^:[&0

Try it online!
Uses Arnauld's method
Explanation:
The argument is n
                                 ^:    - apply the verb on the left hand site
                                   [   - n times
                                    &0 - to a starting value 0
 (                             )@]     - calculate for the current value of the argument
                         ,.&.":        - convert to string and then each char to digit
        (3+3|23|10+100*])              - map each digit to its word length
       |                               - a filler for the fork
    1#.                                - sum the lengths
   +                                   - add them to the current value

Edited after 1st comment.
Prints all terms
Scala, 76 bytes
def^(n:Int)=(1 to n).scanLeft(0)((y,_)=>y+(y+"").map(x=>(x*9+1)%13%3+3).sum)

Try it online!
Prints nth term
Scala, 72 bytes
def^(n:Int)=Stream.iterate(0)(x=>x+(x+"").map(x=>(x*9+1)%13%3+3).sum)(n)

Scala, 69 bytes
def^(n:Int)=(0/:(1 to n))((y,_)=>y+(y+"").map(x=>(x*9+1)%13%3+3).sum)

Scala, 67 bytes
def s(b:Int):Stream[Int]=b#::s(b+(b+"").map(x=>(x*9+1)%13%3+3).sum)

Scala, 67 bytes
val s:Stream[Int]=0#::s.map(x=>x+(x+"").map(x=>(x*9+1)%13%3+3).sum)

Try it online!

I don't know Scala, but I think this is neither a program or a function but rather a snippet (i.e. it runs on the REPL once n is defined). If you know Scala it's probably easy to fix. Also note that there is a tips for golfing in Scala question which may help. Lastly it's nice to post a link to an online interpreter, TIO has Scala and is used by a lot of PPCG members.

@JonathanAllan, thank you, it was very helpful.


text:
What Inning is it?
Goal
In light of the World Series being around the corner, I need a program that can read the box scores and tell me what inning it is. This is complicated slightly because baseball uses an odd method to record the score. They don't write down the at-bat team's score for the inning until they've scored a run (and are still going) or have finished their at-bat. Thus a 0 on the scoreboard always means a finished at-bat. For example:
Example A:
Inning| 1| 2| 3| 4| 5| 6| 7| 8| 9|
  Them| 0| 0| 0| 0| 0| 2|  |  |  |
    Us| 0| 0| 2| 0| 0| 0|  |  |  |

Example B:
Inning| 1| 2| 3| 4| 5| 6| 7| 8| 9|
  Them| 0| 0| 0| 0| 0| 2|  |  |  |
    Us| 0| 0| 2| 0| 0| 1|  |  |  |

Example C:
Inning| 1| 2| 3| 4| 5| 6| 7| 8| 9|
  Them| 0| 0| 0| 0| 0| 2|  |  |  |
    Us| 0| 0| 2| 0| 0|  |  |  |  |

#Them is the Away Team, Us is the Home Team (who are the guys you root for)

Example A: We know we're at the top of the 7th because Us has a recorded 0 in the Bottom of the 6th and the Top of the 7th is blank.
Example B: It can either be the Bottom of the 6th or the Top of the 7th.
Example C: It can either be the Top or Bottom of the 6th.

Your task is to return which inning(s) it could be.
Input
Two lists of non-negative integers. Lists will be assumed jagged with the Away team's list being either the same size or one element larger in comparison to the Home team's. You can take the scores in either order but state in your answer if you do not use the default. I.e., Away Team then Home team (the default), or Home team then Away team (reversed). They can also be padded with dummy data if you want, state in your answer if you do so.
Output
A string or something equivalent which identifies the inning number and whether it's the top or bottom. E.g. 7B 8T, B7 T8, ['7B','8T'] are all fine. If there are two answers, you must output both. The format is pretty flexible though.
Rules

Input will always be valid
Games can go into indefinite extra innings. Your program should be able to support up to 255 innings.
Standard Loopholes are forbidden
This is code-golf so shortest code wins

Test Cases
#Input:
[[],
 []]
#Output: 1T

#Input:
[[0],
 []]
#Output: 1B

#Input:
[[0,0,0,1],
 [0,0,0,0]]
#Output: 5T

#Input:
[[0,0,0,1],
 [0,0,0,1]]
#Output: 4B, 5T

#Input:
[[0,0,0,1,0,0,1,0,0,1],
 [0,0,0,0,1,0,0,1,0,1]]
#Output: 10B, 11T

#Input:
[[0,0,0,1],
 [0,0,0]]
#Output: 4T, 4B

#Input:
[[0,0,0,0],
 [0,0,0]]
#Output: 4B

Can we take the two lists in reverse order? i.e. bottom then top?

@JoKing Sure, as long as it's noted and the answer still matches up correctly.

Is positive/negative integer return value acceptable output?

@Rogem That's pushing it a bit but reading your write-up, that's fine. I did say output is quite flexible.

C (gcc), 50 bytes
Takes input as a pointer to an interleaved list (i.e. {them#1, us#1, them#2,...}).
Returns one option via modification, and the other via return value.
Negative values indicate bottom of the inning, positive values indicate top of the inning. Zeroes are "empty". The absolute value of the output is the number of the inning. So, -4,5 indicates the possibilities being top of the fifth and bottom of the fourth, and 1,0 indicates the only possibility being the top of the first.
The return value of the macro can be used to determine whether there's one or two possible innings; the return value is 0 if there's no other inning. Otherwise, it is the number of the inning.
Zero bytes of source code. Use the following as a preprocessor flag:
-Df(o,n,l)=({o=n%2?~n/2:n/2+1;l[n-1]?-o-~n%2:0;})

Try it online!
Degolf
-Df(o,n,l)=({
// Define a function-like macro f(o,n,l)
// o is the output variable, n is the size of the list,
// l is a pointer to the first element of the list.
o=n%2?~n/2:n/2+1;
// If there's an odd number of elements, first possible inning is -(n+1)/2.
// Else, it is (n/2)+1.
l[n-1]?-o-~n%2:0})
// If the score from the last inning is non-zero, the other possible inning
// needs to be determined; flip the sign of first output value then deduct
// 1 from it if the number of elements is even.

Also, this could be golfed an additional 4 bytes if I can assume the list to be in reverse order (last to first), or the pointer to point to the last element in the array. Didn't go for that, as it felt like too much of a cheat.

I'd love to hear from @veskah if taking input as you did is ok, because it seems quite different (and useful) from the original spec.

@BLT By convention, interleaving is how lists of lists are done in C; multiple dereferencing is very taxing on resources. Other option would be to have one list after the other, but then it would be very impractical to append new elements to.

Perl 6, 52 48 45 bytes
-3 bytes thanks to some restructuring from nwellnhof!
->\a,\b{(+a,a==b if (b,a)[a>b].tail;b+1,a>b)}

Try it online!
Anonymous code block that takes input as two lists, top then bottom. Output is a list of tuples, where the first element is the inning number and the second element is True or False, corresponding to Bottom or Top.
Explanation:
       {                                    }  # Anonymous code block
->\a,\b   # That takes input lists a and b
        (                                  )   # Return a list of
                                    b+1,a>b    # A list of
                                               #  The length of the second list plus 1
                                               #  And top/bottom
         +a,a==b     # And the length of the first list
                     # And the other of top/bottom
                 if  # Only if:
                    (b,a)[a>b]      # The current of top/bottom's
                              .tail # Last element exists and is not 0

R, 103 96 bytes
function(a,b,l=sum(a|1),k=sum(b|1))I(l,I(l-k,I(a[l],c(l,-l),-l),I(b[l],c(-l,l+1),l+1)),1)
I=`if`

Try it online!
 @digEmAll saved 7 bytes!
Takes two lists vectors as input, and outputs one or two integers representing the possible innings. Positive integers are the top of the inning, and negative integers are the bottom of the inning.
In R, positive integers are truthy, so I can use the difference in lengths as the first argument to if().

You'd probably have better luck with [[ as an if replacement since you use [ in your code.

@Giuseppe I tried it with < and ^. I think [ was the one used in the example I remember.

You can also give another name to 'if' (and remove {} and move f= outside) : 96 bytes

JavaScript (Node.js), 75 bytes
f=(a,c=1,p=0,z=0)=>1/(t=a[p][c-1])?f(a,c+p,1-p,t):[c,p]+(z?[,c+p-1,1-p]:'')

Try it online!

Python 2, 135 129 126 125 123 119 bytes
a,b=input()
c=len(a)
e,f=`c+1`+"T",`c`+"B"
print((f+e,e)[b[-1]<1],(`c`+"T"+f,f)[a[-1]<1])[len(b)<c]if b else"1"+"TB"[c]

Try it online!
-1 with thanks to @ovs
-4 thanks again to @ovs

if d else"11BT"[c<1::2] for -3

if d I can see (shouldn't have missed that!) but else"11BT"[c<1::2] doesn't come out any shorter for me unless I am missing something.

No worries @ovs as I found another way inspired by your if d anyway.

Instead of if d you can do if b, then you do not need to store len(b) in variable.

@ovs I looked at that but also need d for [d<c]. Can't see a way round that. Any ideas?

@ovs Ah got you. Very smart. Thanks!

Jelly, 11 bytes
ZẎṖṠṪ$Ð¡Ẉd2

Try it online!
First element: 0-based index of column.
Second element: 0 for top, 1 for bottom.
Output is a list of one or two pairs as specified above (prettified to show it better). The output innings are in reverse order.

Python 2, 65 bytes
a,b=input()
exec"a,b=[0]+b,a;print[len(b)][a[-1]<len(a+b)%2:];"*2

Try it online!
Prints two lines, first the bottom inning possibility then the top one, as a singleton list. If either one is not possible, that list is empty.

Clean, 84 75 bytes
import StdEnv
$ =length
?v|last[0:v]>0= $v=0
@a b| $b< $a=(?a,$a)=($a+1,?b)

Try it online!
Defines the function @ :: [Int] [Int] -> (Int, Int) and some helpers.
Gives output in the form (Top, Bottom) where a zero signifies a null possibility.


text:
Html Indentation
Given an inconsistently indented piece of html code your task is to return the same text but correctly indented

Indent space = 4
Assume input will be non-empty.
Input can be taken as string or array/list of lines
Opening and closing tags must be on the same line as long as there is not any other tag inside.
Assume there will be only html tags, no text elements whatsoever
All opening tags that aren't self-closing will have closing tags, and will be given in the correct nesting order. Self-closing tags will be closed with />
Standard code-golf rules apply

Example and test-cases
Input
--------------

Output
----------

Input
------------

Output
--------------------

Input
--------------

<input/><input/>

Output
-------------

    <input/>
    <input/>

Do we need to support single-label tags like img or a?

@AdmBorkBork Yes

Then how should

 be indented? Like
\n

 or
\n
\n
?

 is valid HTML (tag soup). Are you confusing HTML with XML?

By specifying HTML I'm assuming that you do not care about significant whitespace? <foo></foo> can be meaningfully different than <foo>\n</foo> if we're just talking about XML in general.

Also worth noting that xmllint can probably be used to trivialize this problem.

 is not valid Xhtml.
@edc65: This question is not about xhtml

@recursive yes I kwow. Maybe the OP does not

@LuisfelipeDejesusMunoz You can add a rule "Each tag that is not self-closing has a matching (open/close) tag", regarding

.

I voted that this question should remain closed. It still needs clarification in the challenge description about text nodes and whitespace.

One could do that problem for general indentation that gets string as "(" or "{" for open the correspondence for close... it seems to me something one can handle with one little recursive function...

Apologies to you all. I'll edit the question right now to make it more clear

Do we need to consider <input type=text value="you_guess" onclick=f("2'3'4"); disabled />?

@l4m2 no.......

@LuisfelipeDejesusMunoz I'd make a note that all tags are guaranteed to match /\w( (\w*="\w*"))*/ or something. Maybe more lax than \w in "\w*" but that's up to you

@LuisfelipeDejesusMunoz May we split self-closing tags into an opening and a closing tag?

Retina, 101 bytes
L`<.*?>
T`¶`_`<(.+)¶</\1
^.+
$&/
{`(( *)((?!.*(</|/>)))?.+)/¶(.+)
$1¶$2$#3*4* $5/
    (</.+>/)
$1
/$

Try it online! Explanation:
L`<.*?>

List just the tags.
T`¶`_`<(.+)¶</\1

Join matching pairs of tags.
^.+
$&/

Add a marker to the end of the first line.
{`(( *)((?!.*(</|/>)))?.+)/¶(.+)
$1¶$2$#3*4* $5/

Copy the indentation from each line to the next, adding 4 spaces if the current line is an opening tag.
    (</.+>/)
$1

But if the next line (which is now the current line) is a closing tag then delete 4 spaces.
/$

Delete the marker once it reaches the last line.

Python 2, 170 bytes
def f(o,i=-4):
 s,c,n,h,l=" <\n  "
 for t in"".join(o.split()).split(c):
	if'/'==t[:1]:i-=4;h+=(n+i*s)*(l!=t[1:])+c+t
	else:h+=n+i*s+c+t;i+=4-4*('/'in t);l=t
 print h[4:]

Try it online!

This removes the space between img and src in

Python 2, 174 bytes
import re
def F(I):
 m=x=0
 n,s,b='\n/<'
 for d in re.findall(r'<(.*?>)',I):
	if d[0]==s:print(n+' '*~-m*4)*x+b+d,;m-=1;x=1
	else:print n+' '*m*4+b+d,;x*=s in d;m+=not s in d

Try it online!

JavaScript 115 Bytes
s=>(n=c=-1,m=f=>"\n"+" ".repeat(4*c)+f,s.replace(/<\/?|\/>/g,w=>w[1]?(n?k=m(w):k=w,n=1,c--,k):m(w,n=0*c++)).trim())

I lost the original code so whoops no explanation on this one. It's short though so think of it as a reversing challenge :)
Adds some newlines, but it is correctly tabbed.

PHP, 141bytes
preg_match_all("%(<.*>)%U",$argn,$m);foreach($m[1]as$t)echo!$p|($p=$t[1]!="/")?str_pad("\n",($t[-2]!="/"?$p?++$i:$i--:$i+!$p=0)*4-3):!$i--,$t;

Run as pipe with -nR or try it online.


text:
Playing with the musical turtle
My two kids like to play with the following toy:

The colored areas with the shapes inside can be touched and the turtle then lights the area and plays a sound or says the name of the color or the shape inside. The middle button changes the mode. There is one mode in which the areas play different musical notes when touched, with a twist: if the kid touches three consecutive areas clockwise, a special melody 1 is played. If the three consecutive areas touched are placed counterclockwise, a special melody 2 is played.
The challenge
Let's simulate the internal logic of the toy. Given a string with 3 presses of the kid, return two distinct, coherent values if the three presses are for consecutive areas (clockwise or counterclockwise) and a third distinct value if they are not.
Details

The input areas will be named with a character each, which can be their color: ROYGB for red, orange, yellow, green and blue; or their shape: HSRTC for heart, square, star (R), triangle and circle. Case does not matter, you can choose to work with input and output just in uppercase or in lowercase.
The program will receive a string (or char array or anything equivalent) with three presses. Examples (using the colors): RBO, GYO, BBR, YRG, YGB, ORB...
The program will output three distinct, coherent values to represent the three possible outcomes: a first value if the combination does not trigger a special melody, a second value if the combination triggers the clockwise special melody, and a third value if the combination triggers the counterclockwise special melody. Example: 0 for no special combination, 1 for the melody triggered by a clockwise combination and -1 for the melody triggered by a counterclockwise combination.
You do not need to worry about handling wrong input.

Test cases
Input   Output      // Input based on colors
--------------
RBO     0           // No special combination
GYO     -1          // Counterclockwise melody triggered
BBR     0           // No special combination
YRG     0           // No special combination
YGB     1           // Clockwise melody triggered
ORB     -1          // Counterclockwise melody triggered
OOO     0           // No special combination
BRO     1           // Clockwise melody triggered

This is code-golf, so may the shortest code for each language win!

Is [0,0], [1,0], [0,1] allowed as output? I see the Mathematica answer doing that, and it would save 3 bytes in the 05AB1E answer.

@KevinCruijssen of course you can. The output values can be anything as long as they are distinct and consistent.

Java 8, 48 39 33 bytes
s->"ROYGBRO BGYORBG".indexOf(s)|7

-6 bytes thanks to @RickHitchcock, so make sure to upvote him as well!
Takes uppercase color as input-String. Outputs -1 for none, 7 for clockwise, and 15 for counterclockwise.
Try it online.
Explanation:
s->      // Method with String parameter and integer return-type
   "ROYGBRO BGYORBG".indexOf(s)
         //  Get the index of the input in the String "ROYGBRO BGYORBG",
         //  which will result in -1 if the input is not a substring of this String
    |7   //  Then take a bitwise-OR 7 of this index, and return it as result

Old 39 bytes answer:
s->(char)"ROYGBRO BGYORBG".indexOf(s)/7

Takes uppercase color as input-String. Outputs 9362 for none, 0 for clockwise, and 1 for counterclockwise.
Try it online.
Explanation:
s->      // Method with String parameter and integer return-type
   (char)"ROYGBRO BGYORBG".indexOf(s)
         //  Get the index of the input in the String "ROYGBRO BGYORBG",
         //  which will result in -1 if the input is not a substring of this String
         //  And cast it to a char (-1 becomes character with unicode value 65535)
    /7   //  Integer-divide it by 7 (the char is implicitly converted to int doing so)

I think 9632 is the best distinct and consistent value I've seen in these answers so far :)

@MishaLavrov It could also be 10922 (integer-division by /6) or 8191 (integer-division by /8), but I choose /7 because it's the index of the space in the String. :)

@RickHitchcock Thanks! I thought I had tried some bitwise operations, but apparently not properly enough..

JavaScript (ES6), 41 bytes
Takes color initials as input. Returns 2 for none, true for clockwise or false for counterclockwise.
s=>~(x='ROYGBRO_ORBGYOR'.search(s))?x<5:2

Try it online!

At least an answer from Arnauld I can understand!! :)

@Charlie I think Arnauld is sick or something.. Not only is his answer readable and easy to understand, it's even longer than my Java answer! o.Ô Something is clearly wrong here. ;p

s=>('ROYGBRO_ORBGYOR'.search(s)+8)/8|0

Do you even royg, bro?

Python 2, 36 bytes
lambda i:'ROYGBRO ORBGYOR'.find(i)/7

-1 - None
0 - Clockwise
1 - Counterclockwise
Try it online!

Heh, great minds (or something)... https://codegolf.stackexchange.com/a/174635/53748 (if I'd seen this before trying stuff myself, I'd just have given you the byte save :p)

@JonathanAllan Don't worry, stuff happens :D I've upvoted your answer, as I can't dislike it!

05AB1E, 15 11 bytes
Saved 4 bytes thanks to Kevin Cruijssen and Magic Octopus Urn.
Uses shapes.
Output [0, 0] for none, [1, 0] for clockwise and [0, 1] for counter-clockwise
Â‚.•ÌöJη•så

Try it online!
or as a Test suite
Explanation
Â‚            # pair the input with its reverse
  .•ÌöJη•     # push the string "hsrtchs"
         så   # check if the input or its reverse is in this string

Very similar as my 15-byte answer that I was about to post: .•1´₃éC•Â‚εXå}¥ resulting in [0], [1], or [-1], so +1 from me. Btw, I think (not sure) you can save three bytes by removing the last three, outputting [0, 0], [1, 0], and [0, 1] as distinct values. I see that the Mathematica answer does the same. Will ask OP for verification.

Just asked OP, and you are indeed allowed to drop the last three bytes. As long as the three outputs are consistent and distinct it's fine whatever it is.

Â‚.•ÌöJη•så is 11 bytes if [1,0], [0,1] and [0,0] are considered unique (unless I'm missing something obvious here, adding ƶO to the end of that 11-byter is still 13 for the same 0, 1, 2 answer you have now). Test cases. Test cases 2. Order reversal removes the need for the loop.

According to the comment on the original thread the 11-byter should be fine, as it uses 3 distinct values, you can beat Jelly with that one :).

@KevinCruijssen Thank you! I always seem to think of unique as "single digit" for no reason :)

@MagicOctopusUrn Thanks! I did try using Â but somehow I ended up at 15 (or 13) with that as well. Great to see that someone managed better :)

@Emigna if "better" means "tried switching argument order 60 different ways", sure :P.

Wolfram Language (Mathematica), 42 36 bytes
{"ROYGBRO","ORBGYOR"}~StringCount~#&

Try it online!
Counts the number of times the input appears in both "ROYGBRO" and "ORBGYOR". Returns {1,0} for clockwise, {0,1} for counterclockwise, and {0,0} for no special combination.
At the cost of only one more byte, we can get outputs of 0 for nothing, 1 for clockwise, and 2 for counterclockwise with "ROYGBRO.ORBGYORBGYOR"~StringCount~#&.

Excel, 29 bytes
=FIND(A1,"ROYGBRO_RBGYORB")<6

Uppercase colours as input.
Returns #VALUE! for no pattern, TRUE for clockwise, FALSE for anti-clockwise.
Can wrap in IFERROR(    ,0) for +11 bytes to handle exception , and return '0' for no-pattern cases instead.

JavaScript (ES6), 32 bytes
s=>'ROYGBRO_ORBGYOR'.search(s)|7

Returns -1 if no combination, 15 if counterclockwise, 7 if clockwise.

let f =
s=>'ROYGBRO_ORBGYOR'.search(s)|7

console.log(f('RBO')) // -1
console.log(f('GYO')) // 15
console.log(f('BBR')) // -1
console.log(f('YRG')) // -1
console.log(f('YGB')) // 7
console.log(f('ORB')) // 15
console.log(f('OOO')) // -1
console.log(f('BRO')) // 7

x86 machine code, 39 36 bytes
00000000: f30f 6f29 b815 0000 0066 0f3a 6328 0c89  ..o).....f.:c(..
00000010: c883 c807 c352 4f59 4742 524f 2042 4759  .....ROYGBRO BGY
00000020: 4f52 4247                                ORBG

Assembly:
section .text
	global func
func:					;the function uses fastcall conventions
					;no stack setup needed because we don't need to use stack
	movdqu xmm5,[ecx]		;Move DQword (16 bytes) from 1st arg to func(ecx) to SSE reg
	mov eax, msg			;Load address of constant str 'msg' into eax
	PcmpIstrI xmm5, [eax], 1100b	;Packed Compare String Return Index, get idx of [eax] in xmm5
	mov eax, ecx			;Move returned result into reg eax
	or eax, 7			;Bitwise OR eax with 7 to get consistent values
	ret				;return to caller, eax is the return register
	msg db 'ROYGBRO BGYORBG'

Try it online!
Output is 23 for none, 7 for clockwise, and 15 for counter-clockwise. Based on @RickHitchcock 's answer.
Edit 1: Saved 3 bytes by using an SSE string comparison instruction instead of using libc.
Edit 2: Use proper calling convention for SSE (use XMM5 instead of XMM2) and improve formatting on Bash.

Can you count the machine code bytes here, since those bytes rely on the plafement of strstr in the binary? You can't just take those same bytes in another context and expect them to work the same.

There are pure machine code replacements that dont rely on the standard library https://www.strchr.com/strcmp_and_strlen_using_sse_4.2

@RobertFraser The placement of the function is resolved during linking, the byte count will always be the same because the address of the function strstr will always be a 32-bit (4 byte) address. The machine code in my post is unlinked.

I guess it's kind of a gray area. The function relies on data in the object file (linker map) before it can be used. But you could argue that's no different than a Java lambda needing a type declaration.

Note to be fully compliant with the ABI you'd have to use xmm5 or xmm6 which are caller-saved registers, instead of xmm2 which is callee-saved (but that shouldnt cost any bytes).

Python 2, 45 43 bytes
lambda i,a='ROYGBRO':(i in a)-(i[::-1]in a)

Try it online!
With ideas from and serious credit to @DeadPossum
-2 with thanks to @JoKing. Now outputs -1 = counterclockwise, 0 = none, 1 = clockwise.
My original effort is below for historical purposes.
Python 2, 52 51 bytes
lambda i,a='ROYGBRO':((0,1)[i[::-1]in a],2)[i in a]

Try it online!
0 = none, 1 = counterclockwise, 2 = clockwise

45 bytes

@DeadPossum That is seriously cool and different enough from mine for you to post as your own answer. I will upvote.

APL(Dyalog), 22 18 bytes
+/(⍷-⍷∘⌽)∘'ROYGBRO'

-4 bytes thanks to @ngn
Takes a string of color initials. Outputs 0 for no special pattern, -1 for counterclockwise, 1 for clockwise.
Try it online!

Perl 5 -p, 30 bytes
$_=ROYGBRO=~/$_/-ORBGYOR=~/$_/

Try it online!

Python 2,  35  36 bytes
+1 - for some reason I thought all buttons would be distinct >_<
Developed independently from what I have just seen (and now up-voted) by Dead Possum
lambda s:'ORBGYO.BROYGBR'.find(s)/7

Try it online!

I think you need to separate the strings of characters.  This returns 0 (anti-clockwise) for "RBR," which isn't in your list of combinations.

@RickHitchcock ah I had assumed 3 different presses which is certainly incorrect. That'll make this effectively exactly the same as Dead Possum's!

Can't delete from mobile... will delete or address later

Yeah, it could be ambiguous, but one of the test cases ("OOO") shows that they could repeat.

@RickHitchcock yep that's what I saw after your comment - thanks!

@RickHitchcock ...fixed it up by replacing the R with a . (which is what I actually had prior to "optimising" by use of a non-existent spec :p)

Stax, 14 13 bytes
ù♀e▌d─█£F'♦O▬

Run and debug it
The output is

1 for no special combination
2 for counter-clockwise melody
3 for clockwise melody

Jelly, 12 bytes
,Ṛẇ€“¤ƈẎṬ%Ȥ»

Try it online!
-4 thanks to Jonathan Allan.
Clockwise: [1, 0]
Counter-clockwise: [0, 1]
Other: [0, 0]

@JonathanAllan Phew, thanks. Just saw again what I did, you were just 15 hours quicker. :P

Pip, 19 bytes
Y"ROYGBRO"OaNyaNRVy

Outputs 10 for clockwise, 01 for counterclockwise, 00 for neither. Try it online!
Explanation
                     a is 1st cmdline argument
Y"ROYGBRO"           Yank that string into y variable
           aNy       Count of occurrences of a in y
          O          Output without newline
                RVy  y reversed
              aN     Count of occurrences of a in that string
                     Print (implicit)

J, 21 bytes
-&(OR@E.&'ROYGBRO')|.

Try it online!
How it works
-&(OR@E.&'ROYGBRO')|.  Monadic 2-verb hook. Input: a string.

                   |.  Map over [input string, input string reversed]:
      E.&'ROYGBRO'     Find exact matches of input in 'ROYGBRO'
  (OR@            )    Reduce with OR; is it a substring of 'ROYGBRO'?
-&                     Reduce with -; result is 1 for CW, -1 for CCW, 0 otherwise

Achieves maximum amount of function reuse.

R, 38 bytes
grep(scan(,''),c('ROYGBRO','ORBGYOR'))

Try it online!
Returns :

No special combination            : integer(0)
Counterclockwise melody triggered : 2
Clockwise melody triggered        : 1

Charcoal, 18 bytes
≔ROYGBROηＩ⁻№ηθ№⮌ηθ

Try it online! Link is to verbose version of code. Explanation:
 ROYGBRO            Literal string
≔       η           Assign to variable
            η   η   Value of variable
               ⮌    Reversed
             θ   θ  Input string
           №  №     Count matches
          ⁻         Subtract
         Ｉ          Cast to string
                    Implicitly print

Common Lisp, 68 bytes
(defun x(s)(cond((search s "ROYGBRO")1)((search s "BGYORBG")-1)(0)))

Try it online!

Clean, 63 bytes
import StdEnv,Text
$s=map((>)0o indexOf s)["ROYGBRO","BGYORBG"]

Try it online!
[True, True] for no special noises, [True, False] for counterclockwise, [False, True] for clockwise.

Japt, 17 14 bytes
Takes the colours as input, in lowercase. Returns 0 for clockwise, 1 for counterclockwise or -1 if there's no combo.
`ygß`ê qÔbøU

Try it

Expanation
`...`            :Compressed string "roygbrow"
     ê           :Palindromise
       qÔ        :Split on "w"
         b       :Index of the first element
          ø      : That contains
           U     :  The input string

Ruby, 53 36 bytes
->n{"\a\fDch+".index(""<<n%111)&./3}

Try it online!
Input: a 3-digit integer, where the digits represent colors:

1 - red
2 - orange
3 - yellow
4 - green
5 - blue

Output:0 for clockwise, 1 for counterclockwise, nil otherwise.

C (gcc), 55 bytes
Returns 0 for none, -1 for CCW and 1 for CW.
f(char*s){s=!strstr("ORBGYOR",s)-!strstr("ROYGBRO",s);}

Try it online!