37
\$\begingroup\$

This challenge is inspired by Fortran's idiosyncratic implicit typing rules. Your task will be to determine the data type of the object GOD according to the implicit typing rules explained below.

Background

Fortran 77 has six data types: CHARACTER, COMPLEX, DOUBLE PRECISION, INTEGER, LOGICAL, and REAL. Any object not explicitly declared to have one of these types is implicitly assigned a type by the compiler, as determined by the first letter of the object's name. The default implicit types are:

----------------------------
First letter | Implicit type 
-------------+--------------
    A-H      |     REAL          
    I-N      |   INTEGER
    O-Z      |     REAL
----------------------------

For example, the object called NUMBER (first letter N) has implied type INTEGER whereas the object called DUMBER (first letter D) has implied type REAL. These rules lead to the old joke that GOD is REAL . . . unless declared INTEGER.

The default implicit types can be overridden using IMPLICIT statements. For example,

IMPLICIT DOUBLE PRECISION (D,X-Z), INTEGER (N-P)

means that all objects whose names start with D, X, Y, or Z now have implied type DOUBLE PRECISION and those starting with N, O, or P have implied type INTEGER. Objects whose names start with any other letter retain their default implied types (in this example, REAL for A–C, E–H, and Q–W and INTEGER for I–M).

For the purposes of this challenge, we will adopt a more concise syntax: the IMPLICIT keyword (redundant here) will be dropped and we will use the single-character identifiers C, D, I, L, R, and X to represent the six data types (X represents COMPLEX). Thus, the example IMPLICIT statement given above becomes

D(D,X-Z), I(N-P)

i.e. a series of identifier–range pairs.

The challenge

Assume that the object GOD exists in a Fortran 77 program and does not have an explicitly declared type. Write a program or function that returns the implied type of GOD, given a compact IMPLICIT statement as input. This is : the shortest submission (in bytes) in each language wins.

Input

  • Input is either empty or otherwise consists of 1 to 26 identifier–range pairs.
  • Input may be taken in any reasonable format (e.g. one long string, list of identifier–range pairs). If you divide the input into identifier–range pairs, each pair may either be taken as is, e.g. 'D(D,X-Z)', or split, e.g. ['D', '(D,X-Z)'].
  • In ranges, letters appear in alphabetical order and are separated either by commas (for single letters) or dashes (indicating a span of letters). One-letter spans, e.g. G-G, are valid. The outer parentheses must be included, but may be replaced with other paired delimiters (e.g. [] or {}) if desired.
  • IMPLICIT statements are guaranteed not to overlap. That is, no letter has its implied type specified more than once.
  • Alphabetic characters must be uppercase.

Output

The uppercase identifier, C, D, I, L, R, or X, that represents the implied type of the object GOD. If the input is empty, your code must return R (the default type of GOD).

Test cases

Input -> Output

'' -> R
I(M-Z) -> R
I(A-Z) -> I
I(G) -> I
I(G-G) -> I
L(A,B,D-H,M-X,Z) -> L
D(D,X-Z), I(N-P) -> R
L(B,D,F,H,J,L,N,P,R,T,V,X,Z), C(A,C,E,G,I,K,M,O,Q,S,U,W,Y) -> C
D(S-Z), D(J-Q), D(A-H) -> D
I(I-K,M,R-T), R(N-P,U-Z), D(D-F,H), X(C,G), C(A,B,Q), L(L) -> X
I(F), X(N), R(P-P), I(C-C), C(A-A), I(J-J), R(V), D(H-H), X(O), L(B-B), C(R), L(Q-Q), I(D), L(X), R(S-S), C(Y), L(T-T), L(Z), X(U), D(K-K), R(G), X(W-W), D(I), C(L-L), R(E), I(M) -> R

Note: In the first test case, single quotes denote string boundaries.

Bonus imaginary internet points!

Awarded to answers that only use characters from the standard Fortran 77 character set: the 26 uppercase letters A-Z, the 10 digits 0-9, the space , and the 12 characters +-*/=().,’:$

\$\endgroup\$
  • \$\begingroup\$ Can we use different encoding for Fortran's types? E.g 1, 2, 3, 4, 5, 6 instead of C, D, I, L, R, X. \$\endgroup\$ – Surculose Sputum Mar 28 at 0:22
  • 3
    \$\begingroup\$ @JonathanAllan in hindsight, allowing whitespace input creates an unnecessary edge case. Edited. \$\endgroup\$ – Dingus Mar 28 at 1:16
  • 1
    \$\begingroup\$ Great challenge! About the 'any reasonable format" for input, are the ranges specified as strings of a form like "(D,X-Z)" or is that bit flexible too? For instance, can we take this part without parentheses? \$\endgroup\$ – xnor Mar 28 at 1:20
  • 2
    \$\begingroup\$ Can the input have square braces instead of the round ones you use in this example: ['D', '(D,X-Z)']? So would ['D', '[D,X-Z]'] be valid input?. \$\endgroup\$ – Noodle9 Mar 28 at 2:20
  • 3
    \$\begingroup\$ This is heresy. GOD objects are widely thought to be an anti-pattern by most programming linguistic theologists. \$\endgroup\$ – Mateen Ulhaq Mar 28 at 8:07

15 Answers 15

24
\$\begingroup\$

FORTRAN IV (Compiled with gfortran -ffixed-form), 309 291 290 280 398 393 392 334 237 231 bytes + Bonus imaginary Internet points


This should now be a proper FORTRAN IV program, with no anachronisms!


	REALS(200)
	DATAG,R,H,A/1HG,1HR,1H-,1H(/
	READ 9,S
    9	FORMAT(200A1)
	DO1 I=1,200
	C=S(I)
	IF(C.NE.A)GOTO2
	T=S(I-1)
	GOTO1
    2	IF(C.LT.G.AND.S(I+1).EQ.H.AND.S(I+2).GE.G.OR.C.EQ.G)GOTO8
    1	CONTINUE
	T=R
    8	PRINT 9,T
	END

Try it online!

Here's the same code embedded in a loop that runs through the entire test suite. I don't think this can be done with TIO's header and footer.


18 bytes off thanks to @JonathanAllan, who pointed out that one IF statement wasn't needed.

1 more byte off by eliminating a stray space between CHARACTER and S at the top.

And 10 more bytes by rearranging the spaghetti code a bit.

Added 118 bytes to put it in proper FORTRAN IV fixed-column punch-card formatting. (This is for historical accuracy -- it isn't necessary for proper functioning under gfortran.)

Shaved off 5 more bytes: Cleaned up the GOTOs a bit, and changed the treatment of characters so it's actually correct for FORTRAN IV.

1 more byte off from removing an unneeded space in the DATA statement.

58 bytes off by streamlining the flow of control through the various IF statements.

97 more bytes off by: (1) eliminating variable P; and (2) replacing the spaces required at the beginning of a line with a tab character, which I found is allowed, according to an old FORTRAN IV manual. (I was thinking of punch card machines, which, as I recall, didn't have a horizontal tab, but I forgot about teletype machines, which did have a tab key.)

Thanks to @Dingus for 6 more bytes (from removing the B in the DATA statement which was no longer needed after P was eliminated).


I've limited myself to FORTRAN IV constructs here. This should now be a correct FORTRAN IV program, without such things as the CHARACTER data type and quote-delimited strings, which were only introduced later.

Characters in FORTRAN IV needed to be entered as Hollerith constants, and they could be stored in variables of type REAL (and probably other types sometimes too, but there was no CHARACTER type originally). (As I recall, a real could hold 5 ASCII characters from what we now call a string. I think they were padded with spaces if there were fewer than 5 characters in a grouping. The single characters I use are each stored as a real, padded with extra space characters in the real.)

Input is on stdin, on one line, just like the OP's test cases.

Output is on stdout.


FORTRAN IV was my introduction to computer programming -- it was the first programming language I ever learned. When I was a boy, I read through my dad's textbooks when he took a class in it at NYU, which was required by his musicology graduate program. Computer programming (as well as FORTRAN itself) has changed quite a bit since then :) .


| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Does it work for the empty input? The loop version suggests so, but the normal version suggests it fails - maybe a TIO thing? \$\endgroup\$ – Jonathan Allan Mar 28 at 17:04
  • \$\begingroup\$ Also can't you have input with no spaces and remove the space-goto-1? \$\endgroup\$ – Jonathan Allan Mar 28 at 17:07
  • 2
    \$\begingroup\$ @JonathanAllan It does work on a blank line, as the loop version shows. For the standalone answer, TIO requires a newline for that one blank line to be processed as valid input. (If not, the program gets an end-of-fille error.) I've had that input issue on TIO with some programs in other languages as well. \$\endgroup\$ – Mitchell Spector Mar 28 at 17:08
  • \$\begingroup\$ @JonathanAllan You're right about not needing the test for space -- thanks, I'll get rid of it. \$\endgroup\$ – Mitchell Spector Mar 28 at 17:10
  • 2
    \$\begingroup\$ Wow! I'd imagined solutions using the character intrinsics in newer Fortrans, but your spaghetti code takes the cake. Enjoy those well-earned bonus imaginary internet points! \$\endgroup\$ – Dingus Mar 28 at 23:57
12
\$\begingroup\$

Python 3, 61 bytes

lambda i:[a for a,b in i if re.match(b,'G')]or['R']
import re

Try it online!

Input a list of lists of the form ["<type char>", "[<var letters/ranges separated by commas>]"] (eg [['D','[D,X-Z]'],['X','[E,A-J]']]).
Output a list of of one string of type char.

| improve this answer | |
\$\endgroup\$
6
\$\begingroup\$

Jelly,  21  20 bytes

ṪḊṣ”,Om2r/71eƲƇµƇȯ”R

A full program accepting a list of pairs as defined in the specification (each being [type_character, ranges_string]) which prints the appropriate type character.

Try it online! Or see the test-suite.

How?

ṪḊṣ”,Om2r/71eƲƇµƇȯ”R - Main Link: list of pairs, [[type_char, range_str],...]
               µƇ    - filter keep those for which:
Ṫ                    -   tail & yield (removes the range_str which we now process
                         ...leaving [type_char] as what the filter might keep)
 Ḋ                   -   dequeue - remove the leading '(' 
  ṣ”,                -   split at commas (e.g. 'A,F-H,K-K)' -> ['A', 'F-H', 'K-K)']
     O               -   to ordinal (vectorises)            -> [[65], [70,45,72], [75,45,75]]
              Ƈ      -   filter keep those for which:
             Ʋ       -     last four links as a monad:
      m2             -       modulo-2 slice                 ->  [65]  [70,72]  [75,75]
          /          -       reduce by:
         r           -         inclusive range              ->  [65]  [70,71,72] [75]
           71        -       71
             e       -       exists in?                     ->  0     1          0
                     -   }-->                               -> [[70,45,72]]
                                                               (non-empty is truthy)
                     - }--> [[type_char]] or []
                  ȯ”R - logical or with 'R' (i.e. 'R' if empty) 
                      - implicit, smashing print
| improve this answer | |
\$\endgroup\$
4
\$\begingroup\$

sed -E, 50 45 44 bytes

1 byte off thanks to @user41805.

s/^/R(G/;s/(.)*\([^)]*(G|[A-F]-[H-Z]).*/\1/;

Try it online!

This takes input on stdin formatted on one line just as in the OP's test cases, and output is on stdout.

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ From my regex tip, .*(.) can become (.)* \$\endgroup\$ – user41805 Mar 28 at 18:00
  • \$\begingroup\$ @user41805 Thanks -- I missed that optimization. \$\endgroup\$ – Mitchell Spector Mar 28 at 18:22
4
\$\begingroup\$

JavaScript (ES6), 39 bytes

Takes input as an array of ['type','[patterns]'].

a=>(a.find(a=>'G'.match(a[1]))||'R')[0]

Try it online!

Commented

a => (              // a[] = input array of [type, pattern]
  a.find(a =>       // find in a[]:
    'G'.match(a[1]) //   an entry whose pattern is matching 'G'
  )                 // end of find()
  || 'R'            // find() returns undefined if nothing is found,
                    // in which case we use the string 'R' instead
)[0]                // extract either the type of the entry that was found
                    // or the first (and only) character of 'R'
| improve this answer | |
\$\endgroup\$
3
\$\begingroup\$

Perl 5 -MList::Util=pairmap -ap, 53 bytes

pairmap{map$k{$_}=$a,eval$b=~s/-/../gr}@F;$_=$k{G}||R

Try it online!

Input:

A single line:

type letter|range[,letter|range] ...

| improve this answer | |
\$\endgroup\$
2
\$\begingroup\$

Retina 0.8.2, 37 36 bytes

$
R(G
1!`.(?=\([^)]*(G|[A-F]-[H-Z]))

Try it online! Link includes test cases. Edit: Saved 1 byte thanks to @MitchellSpector. Explanation:

$
R(G

Default to Real.

.(?=\([^)]*(G|[A-F]-[H-Z]))

Match a letter that's followed by a ( and then any non-( characters including a G or a range that includes a G.

1`

Only output the first match, in case the default is a duplicate.

!`

Print the match rather than the count of matches.

| improve this answer | |
\$\endgroup\$
2
\$\begingroup\$

Ruby, 37 bytes

->x{(x.find{|_,r|/#{r}/=~?G}||?R)[0]}

Try it online!

Takes input as pairs with brackets, and interprets the second element of each pair as a regexp.

| improve this answer | |
\$\endgroup\$
2
\$\begingroup\$

Ruby -pl, 47 bytes

Takes space-separated arguments from STDIN.

t=?R
gsub(/(\w)(\S+)/){t=$1if"G".tr!$2,''}
$_=t

Try it online!

| improve this answer | |
\$\endgroup\$
2
\$\begingroup\$

Java 10, 63 bytes

m->{var r="R";for(var p:m)r="G".matches(p[1])?p[0]:r;return r;}

Input as an array of String-pairs in the format ["type", "[declaration]"].

Try it online.

Explanation:

m->{                     // Method with String-matrix as input and String return-type
  var r="R";             //  Result-String, starting at "R" as default
  for(var p:m)           //  Loop over each pair `p`
    r=                   //   Set the result to:
      "G".matches(p[1])? //    If "G" regex-matches the second part of the pair
       p[0]              //     Set the result to the first part of the pair
      :                  //    Else:
       r;                //     Leave the result unchanged
  return r;}             //  After the loop: return the result-String
| improve this answer | |
\$\endgroup\$
2
\$\begingroup\$

PowerShell, 38 bytes

+ to @Noodle9

$r=$args|?{'G'-match$_[1]}
"R$r"[!!$r]

Expects input via splatting.

Try it online!

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Japt -g, 12 bytes

k@'GrXÌÃΪ'R

Try it

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

05AB1E, 23 21 20 bytes

ʒθ',¡εáÇŸ}˜71å}˜'Rªн

Input as a list of pairs in the format ["type","(declaration)"].

Try it online or verify all test cases.

Explanation:

ʒ           # Filter the (implicit) list of pairs by:
 θ          #  Pop and push the last value of the pair
            #   i.e. ["I","(I-K,M,R-T)"] → "(I-K,M,R-T)"
  ',¡      '#  Split it by ","
            #   → ["(I-K","M","R-T)"]
     ε      #  Map each inner range to:
      á     #   Remove the "(", "-", and ")" by only leaving the letters
            #    → ["IK","M","RT"]
       Ç    #   Convert each letter to its codepoint integer
            #    → [[73,75],[77],[82,84]]
        Ÿ   #   And then convert it to a range
            #    → [[73,74,75],[77],[82,83,84]]
     }˜     #  After the map: flatten the list of lists of integers
            #   → [73,74,75,77,82,83,84]
       71å  #  Check if 71 is in this list (the codepoint for "G")
            #   → 0 (falsey)
}˜          # After the filter: flatten the remaining list of pairs (potentially empty)
            #  i.e. [["X","(C,G)"]] → ["X","(C,G)"]
  'Rª      '# Append an "R" to this list
            #  → ["X","(C,G)","R"]
     н      # Pop and only leave the first item of this list
            #  → "X"
            # (after which it is output implicitly as result)
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ You forgot to remove the ¦¨ in your source code. \$\endgroup\$ – user92069 Apr 1 at 1:55
  • \$\begingroup\$ @petStorm Ah, already did, but only in the explanation and byte-count I see.. >.> Somehow forgot to update the actual program and TIOs.. Thanks for noticing. \$\endgroup\$ – Kevin Cruijssen Apr 1 at 6:27
1
\$\begingroup\$

PowerShell, 38 37 bytes

($args+'RG'|?{'G'-like"[$_ ]"})[0][0]

Try it online!

Takes strings as is, e.g. 'D(D,X-Z)'.

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Perl 5 with -apF'(?=\[)', 25 bytes

Accepts input as:

A
[A-F,H-M]
B
[N-Z]
$\||=$_ x"G
"=~<>}{$\||=R

Try it online!

Verify all test cases.

Note: the empty test case is missing from the verify all link because my test suite is bad and I should feel bad, but it works when tested in isolation.

| improve this answer | |
\$\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.