42
\$\begingroup\$

Given a non-negative integer input, write a program that converts the number to hexadecimal and returns a truthy value if the hexadecimal form of the number contains only the characters A through F and a falsey value otherwise.


Test cases

10
==> True (A in hexadecimal)

100
==> False (64 in hexadecimal)

161
==> False (A1 in hexadecimal)

11259375
==> True (ABCDEF in hexadecimal)

0
==> False (0 in hexadecimal)

Bonus: -40 bytes if your program prints Only letters for the challenge described above, Only numbers if the hexadecimal version of the number only contains the digits 0-9 and Mix if the hexadecimal number contains at least one number and at least one letter.


This is code golf. Standard rules apply. Shortest code in bytes wins. Either functions or full programs are allowed.

\$\endgroup\$
  • 2
    \$\begingroup\$ Currently drafting an answer in Golfical. \$\endgroup\$ – SuperJedi224 Dec 12 '15 at 20:42
  • \$\begingroup\$ My current idea: covert to base 16 string, then See if trying to parse that string as a base 10 number returns NaN \$\endgroup\$ – Cyoce Dec 12 '15 at 20:54
  • \$\begingroup\$ @Cyoce That may work, depending on your choice of language \$\endgroup\$ – SuperJedi224 Dec 12 '15 at 20:56
  • 3
    \$\begingroup\$ Unrealistic bonus (once again): just the string MixOnlynumbersletters is 21 chars \$\endgroup\$ – edc65 Dec 12 '15 at 21:51
  • 3
    \$\begingroup\$ You say "positive integer input", but 0 is a test case. \$\endgroup\$ – xnor Dec 12 '15 at 22:30

48 Answers 48

22
\$\begingroup\$

Pyth, 43 - 40 = 3 bytes

?&K@J.HQG-JG"Mix"%"Only %sers"?K"lett""numb

Test suite

This achieves the bonus. Only numbers and Only letters fortunately only differ by 4 letters. printf-style formatting is used with %.

The selection system is done by both taking the intersection of the hex with G, the alphabet, and subtracting out G. If neither ends up falsy, it's a mix, while if the intersection is falsy, it's numbers, and if the subtraction is falsy, it's letters.

\$\endgroup\$
  • 1
    \$\begingroup\$ Damn this Pyth is weird. Would be very cool if you could get a negative score though. \$\endgroup\$ – KaareZ Dec 14 '15 at 20:55
15
\$\begingroup\$

Pyth, 6 bytes

!-.HQG

  .HQ   # Converts the input to hexadecimal
 -   G  # Deletes all letters
!       # If empty, output True, else False

Test it here

\$\endgroup\$
12
\$\begingroup\$

Jelly, 6 bytes

b16>9P

Try it online!

How it works

b16>9P  Input: z

b16     Convert the input to base 16.
   >9   Compare each resulting digit with 9; return 1 iff greater.
     P  Take the product of the resulting Booleans.
\$\endgroup\$
  • \$\begingroup\$ Isn't there a built in for 16 or is that not a thing? \$\endgroup\$ – CalculatorFeline Apr 20 '16 at 4:36
  • 1
    \$\begingroup\$ There is now. This was one of the first Jelly answers... \$\endgroup\$ – Dennis Apr 20 '16 at 4:41
11
\$\begingroup\$

TeaScript, 11 bytes 13 15 16

xT(16)O(Sz)

Pretty simple. This uses TeaScript 2.0. You can get this version from the Github

Explanation

        // Implicit: x = input, Sz = alphabet
xT(16)  // input -> hex
O(Sz)   // Only letters?

Try it online (slightly modified version that works on web)

\$\endgroup\$
  • 3
    \$\begingroup\$ Is the down-vote because this is long? Is there something else wrong with this answer that I'm not aware of? Or does someone just not personally like this answer? \$\endgroup\$ – Downgoat Dec 12 '15 at 19:32
  • 2
    \$\begingroup\$ I wouldn't say 16 or 13 bytes is long! \$\endgroup\$ – Luis Mendo Dec 12 '15 at 19:37
  • 23
    \$\begingroup\$ You have to admit that down-goating your posts is pretty tempting. \$\endgroup\$ – Dennis Dec 12 '15 at 19:57
10
\$\begingroup\$

Python, 24 bytes

lambda n:min('%x'%n)>'9'

Converts the input a hex string (without 0x prefix) with '%x'%n. Sees if all its chars are greater than '9' (which letters are) by seeing if the min is above '9'.

\$\endgroup\$
  • \$\begingroup\$ I don't know how Python handles characters / numbers, but the ASCII code of '9' is 54. So if you can write ...>54 you can save a byte. \$\endgroup\$ – CompuChip Dec 15 '15 at 10:06
  • \$\begingroup\$ @CompuChip Python doesn't treat chars or strings as numbers. In fact, Python 2 considers them to be greater than all numbers. \$\endgroup\$ – xnor Dec 15 '15 at 10:27
8
\$\begingroup\$

MATL, 10

i16YA1Y2mA

Examples

>> matl i16YA1Y2mA
> 240
0
>> matl i16YA1Y2mA
> 255
1

Explanation

i       % input                         
16YA    % convert to string representation in base 16
1Y2     % predefined literal: 'A':'Z'
m       % true for set member             
A       % all

Bonus challenge: 53−40 = 13

i16YA1Y2mXKA?'Only letters'}Ka?'Mix'}'Only numbers']]

Examples

>> matl
 > i16YA1Y2mXKA?'Only letters'}Ka?'Mix'}'Only numbers']]
 > 
> 255
Only letters

>> matl
 > i16YA1Y2mXKA?'Only letters'}Ka?'Mix'}'Only numbers']]
 > 
> 100
Only numbers

>> matl
 > i16YA1Y2mXKA?'Only letters'}Ka?'Mix'}'Only numbers']]
 > 
> 240
Mix

Explanation

i                       % input                                                 
16YA                    % convert integer to string representation in base 16
1Y2                     % predefined literal: 'A':'Z'
m                       % true for set member       
XK                      % copy to clipboard K                 
A                       % all                                   
?                       % if (top of the stack)                 
  'Only letters'        % string literal                                        
}                       % else                 
  K                     % paste from clipboard K      
  a                     % any                
  ?                     % if (top of the stack)      
    'Mix'               % string literal    
  }                     % else                                                  
    'Only numbers'      % string literal           
  ]                     % end             
]                       % end          
\$\endgroup\$
  • 2
    \$\begingroup\$ hmmm what is that ? seems like matlab got some nuc power now ! \$\endgroup\$ – Abr001am Dec 12 '15 at 20:12
  • \$\begingroup\$ @Agawa001 Hahaha. Sort of \$\endgroup\$ – Luis Mendo Dec 13 '15 at 4:14
8
\$\begingroup\$

LabVIEW, 52-40 = 12 LabVIEW Primitives

Praise the built-ins!

enter image description here

\$\endgroup\$
8
\$\begingroup\$

C, 46 43 37 bytes

Now with more recursion! (Thanks Dennis):

F(x){return(x%16>9)*(x<16?:F(x/16));}

Bonus: even shorter (33 bytes), but fails for x = 0:

F(x){return!x?:(x%16>9)*F(x/16);}

b;F(x){for(b=x;x;x/=16)b*=x%16>9;return b;}

F() takes an int and returns either 0 (false) or non-zero (true).

I didn't even try to achieve the bonus, "MixOnly lettersnumbers" takes 23 bytes alone, tracking the new condition would have required 9 additional bytes, printf() is 8 bytes, which adds up to 40, nullifying the effort.

Test main:

#include <stdio.h>

int main() {
  int testdata[] = {10, 100, 161, 11259375, 0};
  for (int i = 0; i < 5; ++i) {
    int d = testdata[i];
    printf("%d (0x%x) -> %s\n", d, d, F(d)?"yep":"nope");
  }
}
\$\endgroup\$
  • \$\begingroup\$ What's ?:? I had to replace it with || to get it to compile. Also, can you save a byte by replacing the * with an & thus avoiding the ()s on the left (although you then have to add a space)? \$\endgroup\$ – Neil Dec 16 '15 at 0:21
  • \$\begingroup\$ @Neil a?:b is a GNU extension that evaluates to a if a is a truthy value, otherwise to b. Comes handy to handle null pointers like send(message ?: "(no message)");. I know it's not portable, but code portability is never a concern in code golf :) \$\endgroup\$ – Stefano Sanfilippo Dec 17 '15 at 0:37
  • \$\begingroup\$ @StefanoSanfilippo you can get this down to 33 bytes by doing this: F(x){x=(x%16>9)*(x<16?:F(x/16));} this abuses a (GCC) bug where if there is no return variable in a function and the main argument was set, it will auto-return the main-argument in some cases (based on what logic was done), and this happens to be one of those cases! Try it online: bit.ly/2pR52UH \$\endgroup\$ – Albert Renshaw Apr 22 '17 at 19:58
8
\$\begingroup\$

Python 3, 30 29 bytes

1 byte stripped thanks to sysreq and Python 3.

lambda n:hex(n)[2:].isalpha()

Simple lambda and slicing.

\$\endgroup\$
7
\$\begingroup\$

Perl 6, 18 bytes

{.base(16)!~~/\d/} # 18 bytes

usage:

# give it a name
my &code = {.base(16)!~~/\d/}

for 10, 100, 161, 11259375, 0 {
  printf "%8s %6s %s\n", $_, .base(16), .&code
}

      10      A True
     100     64 False
     161     A1 False
11259375 ABCDEF True
       0      0 False
\$\endgroup\$
7
\$\begingroup\$

Mathematica, 32 bytes

Tr@DigitCount[#,16,0~Range~9]<1&

Explanation:

                               &   A function returning whether
Tr@                                 the sum of elements of
   DigitCount[ ,  ,         ]        the numbers of
                   0~Range~9          zeros, ones, ..., nines in
                16                    the hexadecimal expansion of
              #                       the first argument
                             <1     is less than one.
\$\endgroup\$
7
\$\begingroup\$

Javascript, ES6, no regexp, 28 bytes

F=n=>n%16>9&&(n<16||F(n>>4))

There's also this 27-byte version but it returns the inverse value.

F=n=>n%16<10||n>15&&F(n>>4)
\$\endgroup\$
  • \$\begingroup\$ Nice! You could also rearrange it like this for 23 bytes: F=n=>!n||n%16>9&F(n>>4) \$\endgroup\$ – user81655 Dec 14 '15 at 13:52
  • \$\begingroup\$ @user81655 - Unfortunately, that version returns true for 0, so it's incorrect. \$\endgroup\$ – zocky Dec 14 '15 at 14:59
  • \$\begingroup\$ Oh right, I guess the shortest would be F=n=>n%16>9&&n<16|F(n>>4) then. \$\endgroup\$ – user81655 Dec 14 '15 at 21:56
  • \$\begingroup\$ @user81655 I'm pretty sure you need to short-circuit the ||, but I think you could get away with using & instead of && in that case. \$\endgroup\$ – Neil Dec 16 '15 at 0:13
  • \$\begingroup\$ @Neil Why's that? Did you test it? \$\endgroup\$ – user81655 Dec 16 '15 at 2:00
7
\$\begingroup\$

Julia, 18 bytes

n->isalpha(hex(n))

This is an anonymous function that accepts an integer and returns a boolean. To call it, give it a name, e.g. f=n->....

The input is converted to a hexadecimal string using hex, then we check whether its entirely comprised of alphabetic characters using isalpha.

\$\endgroup\$
6
\$\begingroup\$

JavaScript ES6, 29

No bonus

n=>!/\d/.test(n.toString(16))

With the new value of -40 the bonus is nearer now ... but not enough. Bonus score 70 71 - 40 => 30 31

n=>/\d/.test(n=n.toString(16))?1/n?'Only numbers':'Mix':'Only letters'

Test snippet (type a number inside the input box)

#I { width:50%}
<input id=I oninput="test()"/><br>
Hex <span id=H></span><br>
Result <span id=R></span>

\$\endgroup\$
  • \$\begingroup\$ -n-1=~n, right? \$\endgroup\$ – CalculatorFeline Apr 22 '16 at 5:42
  • \$\begingroup\$ @CatsAreFluffy if n is not numeric like 'A' (that's the whole point in this challenge), ~n == -1 while -n-1 == NaN \$\endgroup\$ – edc65 Apr 22 '16 at 8:53
4
\$\begingroup\$

GS2, 6 bytes

V↔i/◙s

The source code uses the CP437 encoding. Try it online!

How it works

V       Evaluate the input.
 ↔      Push 16.
  i     Perform base conversion.
   /    Sort.
    ◙   Push [10].
     s  Perform greater-or-equal comparison.
\$\endgroup\$
4
\$\begingroup\$

Octave, 22 bytes

@(n)all(dec2hex(n)>64)
\$\endgroup\$
4
\$\begingroup\$

Java, 46 44 38 bytes

i->i.toHexString(i).matches("[a-f]+");

Pretty simple one-liner that converts the integer to a hexadecimal string and uses regex to determine if all characters are letters.

-2 bytes thanks to @Eng.Fouad.

\$\endgroup\$
  • \$\begingroup\$ "[a-f]+" would save 2 bytes. \$\endgroup\$ – Eng.Fouad Dec 13 '15 at 18:56
  • \$\begingroup\$ Fails for 516.. \$\endgroup\$ – CalculatorFeline Apr 22 '16 at 15:14
  • \$\begingroup\$ @CatsAreFluffy No it doesn't. \$\endgroup\$ – TNT Apr 22 '16 at 15:23
  • \$\begingroup\$ Well now it determines if the string contains a hex letter, so remove the +–it's a waste of byte. \$\endgroup\$ – CalculatorFeline Apr 22 '16 at 15:53
  • \$\begingroup\$ @CatsAreFluffy No. matches returns true if the entire string can be matched by the given regex. [a-f] without the plus sign is incorrect since it doesn't match the entire string given that it contains more than one character; it would if and only if one valid character is present. \$\endgroup\$ – TNT Apr 22 '16 at 16:28
3
\$\begingroup\$

CJam (9 8 bytes)

{GbA,&!}

Online demo

\$\endgroup\$
  • 2
    \$\begingroup\$ Equally short: {Gb$N<!} \$\endgroup\$ – Dennis Dec 13 '15 at 2:33
3
\$\begingroup\$

Ruby, 19 bytes

->n{!('%x'%n)[/\d/]}

Ungolfed:

-> n {
  !('%x'%n)[/\d/]
}

Usage:

f=->n{!('%x'%n)[/\d/]} # Assigning it to a variable
f[0]
=> false
f[10]
=> true
f[100]
=> false
f[161]
=> false
f[11259375]
=> true

With bonus, 70 - 40 = 30 bytes

->n{'%x'%n=~/^(\d+)|(\D+)$/;$1?'Only numbers':$2?'Only letters':'Mix'}

Usage:

f=->n{'%x'%n=~/^(\d+)|(\D+)$/;$1?'Only numbers':$2?'Only letters':'Mix'}
f[10]
=> Only letters
f[100]
=> Only numbers
f[161]
=> Mix
\$\endgroup\$
  • \$\begingroup\$ Late, but '%x'%n!~/\d/ is a shorter check for solution one, and solution two has a raw byte count of 70, not 75. \$\endgroup\$ – Value Ink Jan 26 '17 at 19:39
3
\$\begingroup\$

Perl, 69 - 40 = 29 bytes

$_=sprintf"%X",<>;print s/\d//?$_?"Mix":"Only numbers":"Only letters"
\$\endgroup\$
2
\$\begingroup\$

Ceylon, 55 bytes

Boolean l(Integer n)=>!any(formatInteger(n,16)*.digit);

Straightforward ... we format n as a hexadecimal number (which produces a string), call on each character of that string the .digit number (which returns true if it is a digit), then check whether any of them are true, then negate this.

The version with bonus has a lot higher score of 119 - 25 = 94:

String c(Integer n)=>let(s=formatInteger(n),d=s*.digit)(every(d)then"Only numbers"else(any(d)then"Mix"else"Only letters"));

I'm not sure how anyone could make a bonus version short enough to be better than the no-bonus version, even those strings alone have length 28 together. Maybe a language which makes it really hard to produce a truthy/falsey value.

Here is a formatted version:

String c(Integer n) =>
        let (d = formatInteger(n,16)*.digit)
    (every(d) then "Only numbers"
                else (any(d) then "Mix"
                    else "Only letters"));
\$\endgroup\$
2
\$\begingroup\$

Rust, 70 bytes

fn f(n:i32)->bool{format!("{:x}",n).chars().all(|c|c.is_alphabetic())}

Because, ya know, Java Rust.

It's actually quite elegant, though:

format!("{:x}", n)         // format n as hex (:x)
  .chars()                 // get an Iter over the characters
  .all(                    // do all Iter elements satisfy the closure?
    |c| c.is_alphabetic()  // self-explanatory
  )

But it's a shame the function definition boilerplate is so long.... :P

\$\endgroup\$
  • \$\begingroup\$ I have an idea. More closures! \$\endgroup\$ – CalculatorFeline Apr 22 '16 at 15:18
2
\$\begingroup\$

CJam, 44 bytes - 40 bonus = 4 bytes

2,riGbAf/&:-"Only numbersOnly lettersMix"C/=

Try it here~

\$\endgroup\$
2
\$\begingroup\$

Seriously, 12 bytes

4ª,¡OkúOkd-Y

Hex Dump:

34a62cad4f6b
a34f6b642d59

Try It Online

It's the same as the other stack language answers. It would be only 7 bytes if Seriously supported string subtraction yet.

EDIT: Seriously now supports string subtraction and the following 7 byte solution now works:

ú4╙,¡-Y

Hex Dump:

a334d32cad2d59

Try It Online

\$\endgroup\$
  • 1
    \$\begingroup\$ 11: 4╙,¡#S;ú∩S= (or or , lots of ways to spell :16: in two bytes :P) \$\endgroup\$ – Mego Dec 14 '15 at 1:06
  • \$\begingroup\$ I didn't know S I think. \$\endgroup\$ – quintopia Dec 14 '15 at 18:31
2
\$\begingroup\$

05AB1E, 2 bytes (non-competing)

Code:

ha

Ha! That is two bytes! Sadly non-competing because this language postdates the challenge :(

Explanation:

h   # Convert input to hexadecimal
 a  # is_alpha, checks if the value only contains letters

Try it online! or Verify all test cases!

\$\endgroup\$
  • 1
    \$\begingroup\$ hdÔ©1åi•4?ŸâτΛ•}®0åi•4?ŸàpÕTà•}®g2Qi•²•}36B` for the bonus resulting in... 6 more! Wooooo bonuses! \$\endgroup\$ – Magic Octopus Urn Jan 24 '17 at 18:40
2
\$\begingroup\$

Python 3, 28 bytes

lambda x:min(hex(x)[1:])>'@'
\$\endgroup\$
2
\$\begingroup\$

Common Lisp, 40 bytes

(every'alpha-char-p(format()"~x"(read)))

Try it online!

\$\endgroup\$
2
\$\begingroup\$

SmileBASIC 3.2.1, 78 bytes

INPUT V FOR I=0 TO 9
IF INSTR(HEX$(V),STR$(I))>-1 THEN ?"FALSE"END
NEXT?"TRUE"
\$\endgroup\$
  • \$\begingroup\$ I don't see any non-ASCII characters here (unless there are some); this counter is the definitive decider and it says 81. \$\endgroup\$ – cat Dec 12 '15 at 21:08
  • 1
    \$\begingroup\$ It doesn't matter that the implementation uses UTF-16 internally; to the rest of the world they may as well be UTF-8 chars in the range 0-127, thus your byte count is 81. \$\endgroup\$ – cat Dec 12 '15 at 21:10
  • \$\begingroup\$ Thanks for the feedback, wasn't sure if "bytes" meant I should count 2 per char. 81 it is. \$\endgroup\$ – snail_ Dec 13 '15 at 18:17
  • \$\begingroup\$ Actually, the current +10/-0 consensus (which, by the way, I now disagree with) is that we must always use the encoding that an interpreter uses. If you disagree, please post a dissenting opinion on that question. \$\endgroup\$ – lirtosiast Dec 13 '15 at 18:25
  • \$\begingroup\$ @ThomasKwa pfft, okay, oops, now I know better. I didn't realise there was a consensus about that, and I spend a fair bit of time on meta. \$\endgroup\$ – cat Dec 13 '15 at 20:57
1
\$\begingroup\$

Japt, 12 bytes

!UsG r"[a-f]

Try it online!

How it works

!UsG r"[a-f] // Implicit: U = input integer, G = 16
 UsG         // Convert U to a base-16 string.
     r"[a-f] // Replace all lowercase letters with an empty string.
!            // Take the logical NOT of the result.
             // This returns true for an empty string; false for anything else.
\$\endgroup\$
  • \$\begingroup\$ I think !!UsG r"\\d might work and save a byte \$\endgroup\$ – Downgoat Dec 13 '15 at 0:53
  • \$\begingroup\$ @Downgoat Good observation, but that returns true for any number that contains a letter. \$\endgroup\$ – ETHproductions Dec 13 '15 at 1:09
1
\$\begingroup\$

Gema, 41 characters

*=@c{@radix{10;16;*}}
c:<D>=f@end;?=;\Z=t

There is no boolean in Gema, so it simply outputs “t” or “f”.

Sample run:

bash-4.3$ echo -n '11259375' | gema '*=@c{@radix{10;16;*}};c:<D>=f@end;?=;\Z=t'
t
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.