Compute number of matrices with appropriate sums When multiplying monomials in the Milnor basis for the Steenrod algebra, part of the algorithm involves enumerating certain "allowable matrices".

Given two lists of nonnegative integers r1, ... ,rm and  s1, ... ,sn, a matrix of nonnegative integers X

is allowable if

The sum of the jth column is less than or equal to sj:

The sum of the ith row weighted by powers of 2 is less than or equal to ri:

Task

Write a program which takes a pair of lists r1, ... ,rm and s1, s1, ... ,sn and computes the number of allowable matrices for these lists. Your program may optionally take m and n as additional arguments if need be.

These numbers may be input in any format one likes, for instance grouped into lists or encoded in unary, or anything else.
Output should be a positive integer
Standard loopholes apply.

Scoring

This is code golf: Shortest solution in bytes wins.

Examples:

For [2] and [1], there are two allowable matrices:

For [4] and [1,1] there are three allowable matrices:

For [2,4] and [1,1] there are five allowable matrices:

Test cases:

   Input: [1], [2]
   Output: 1

   Input: [2], [1]
   Output: 2

   Input: [4], [1,1]
   Output: 3

   Input: [2,4], [1,1]
   Output: 5

   Input: [3,5,7], [1,2]
   Output: 14

   Input: [7, 10], [1, 1, 1]
   Output: 15

   Input: [3, 6, 16, 33], [0, 1, 1, 1, 1]
   Output: 38

   Input: [7, 8], [3, 3, 1]
   Output: 44

   Input: [2, 6, 15, 18], [1, 1, 1, 1, 1]
   Output: 90

   Input: [2, 6, 7, 16], [1, 3, 2]
   Output: 128

   Input: [2, 7, 16], [3, 3, 1, 1]
   Output: 175

JavaScript (ES7), 163 bytes

f=([R,...x],s)=>1/R?[...Array(R**s.length)].reduce((k,_,n)=>(a=s.map((_,i)=>n/R**i%R|0)).some(c=>(p+=c<<++j)>R,p=j=0)?k:k+f(x,s.map((v,i)=>v-a[i])),0):!/-/.test(s)

Test cases

NB: I've removed the two most time-consuming test cases from this snippet, but they should pass as well.

f=([R,...x],s)=>1/R?[...Array(R**s.length)].reduce((k,_,n)=>(a=s.map((_,i)=>n/R**i%R|0)).some(c=>(p+=c<<++j)>R,p=j=0)?k:k+f(x,s.map((v,i)=>v-a[i])),0):!/-/.test(s)

console.log(f([1],[2]))            // 1
console.log(f([2],[1]))            // 2
console.log(f([4],[1,1]))          // 3
console.log(f([2,4],[1,1]   ))     // 5
console.log(f([3,5,7],[1,2]))      // 14
console.log(f([7,10],[1,1,1]))     // 15
console.log(f([7,8],[3,3,1]))      // 44
console.log(f([2,6,7,16],[1,3,2])) // 128
console.log(f([2,7,16],[3,3,1,1])) // 175

Commented

f = (                               // f = recursive function taking:
  [R,                               //   - the input array r[] splitted into:
      ...x],                        //     R = next element / x = remaining elements
  s                                 //   - the input array s[]
) =>                                //
  1 / R ?                           // if R is defined:
    [...Array(R**s.length)]         //   for each n in [0, ..., R**s.length - 1],
    .reduce((k, _, n) =>            //   using k as an accumulator:
      (a =                          //     build the next combination a[] of
        s.map((_, i) =>             //     N elements in [0, ..., R - 1]
          n / R**i % R | 0          //     where N is the length of s[]
        )                           //
      ).some(c =>                   //     for each element c in a[]:
        (p += c << ++j)             //       increment j; add c * (2**j) to p
        > R,                        //       exit with a truthy value if p > R
        p = j = 0                   //       start with p = j = 0
      ) ?                           //     end of some(); if truthy:
        k                           //       just return k unchanged
      :                             //     else:
        k +                         //       add to k the result of
        f(                          //       a recursive call to f() with:
          x,                        //         the remaining elements of r[]
          s.map((v, i) => v - a[i]) //         s[] updated by subtracting the values of a[]
        ),                          //       end of recursive call
      0                             //     initial value of the accumulator k
    )                               //   end of reduce()
  :                                 // else:
    !/-/.test(s)                    //   return true if there's no negative value in s[]


Spanish Verb Conjugator Explanation

¡Hola! For those of you who don't take Spanish, a verb is conjugated based on the person who does the action. Here's a chart:

English                   Spanish
I                         Yo
You                       Tú
He                        Él
She                       Ella
You (formal)              Usted
We all                    Nosotros
You all                   Vosotros
They (masculine, plural)  Ellos
They (feminine, plural)   Ellas
You (plural)              Ustedes

In Spanish, all verbs end with ar, er, or ir. Here's another helpful chart:

          Ar    Er    Ir
Yo        o     o     o
Tú        as    es    es
Él        a     e     e
Ella      a     e     e
Usted     a     e     e
Nosotros  amos emos imos
Vosotros  áis  éis  ís
Ellos     an   en   en
Ellas     an   en   en
Ustedes   an   en   en

Given a pronoun and a verb, print the verb conjugated using the pronoun in the present tense. Don't worry about stem changing and odd verbs.

Examples

Input        Output
Yo escribir  Escribo
Tu enseñar   Enseñas
Ella querer  Quere (It should be quiere but ignore stem changes)

If your language doesn't support printing with accents, you can omit them. Otherwise, it shouldn't take any more characters to use á instead of a in your code.

You can find more words with which to test here: http://spanish.speak7.com/spanish_vocabulary_verbs.htm. Note that contester should be contestar.

Challenge: Stem Changes

In Spanish, some verbs have stem changes. Let's take the verb querer for example. In all forms except nosotros and vosotros, the first e changes to ie. So, yo quiero, but nosotros queremos. If your program can account for stem changes, you may subtract twice the length of each word you support from your final score. For example, if you support the i -> ie change querer and only querer, you can subtract twice the length of querer, or 12, from your score.

For some stem-changing verbs, try this: https://conjuguemos.com/chart.php?language=spanish&id=2&etre=no&commands=no&all=no&source=public

Small Bonuses

Just for fun, if you explain what your code does in Spanish, take off 30 from your score. Don't just use Google Translate or I'll be able to tell that you cheated.

(As I am not a native Spanish speaker, please correct me on any mistakes)

Python, 172 168 743 characters - 1796 bonus = -1053

Updated to take the stem-changing challenge.

p,v=raw_input().split()
y="aee";z=y+'n'
x=["ooo",y+'s',y,y,y,"aeimos","ae\x00is",z,z]["YoTuElEaUdNsVsEsUs".index(p[0]+p[-1])/2]
s=v[:-2]
X=v='eJw1UuHS5CAIe1aqrNsZhR6w/tj5Hv4Sv7uODRYDxEzlylKTplHS3xrS/3yIm4kntCTVSipkazaZ\n+AA32h3tY1ut+VL7NreXxsEEsgSheGynlJv/GNVvsPs9CIl2hoCSV+gYfuH7rdAyIQdr3+x92yCg\n2g7WEp4vMfTKgogyHabbL4z1l1p/1PLBCF4o9AjtmJBc6wpOTJykM+O0Ib2Y+FyCAuv5wcwCd+Ks\n4+XCdSwhqMIf/eJOFPMjV/rc0jw6IEvm8vjKdBuy/JryMPmEXwIiDInhtK01n1iDPrGu6/A5uy4/\nkBVd89R1OjvHCXbSnoDyaB23nhseElHosf45rzYC1zOevyDojQ548fjGCGg8M5aD8EAmB9GqgFHk\nBzRwDwJ6EcgK5aSDZ2/4TSAjKOMXd3gPh6sTq/+GApG0wkSYdzSBz/AXclUQ+g=='.decode('base64').decode('zip')
if s in X:
 j=X.index(s)<326
 s=(s.replace('oe'[j],'ui'[j]+'e'),s)[p[0]in'NV']
print s+x["aei".index(v[-2])]+x[3:]

Usage:

$ echo "Ellas querer" | python conj_golf2.py
quieren

Test on non-stem-changing inputs:

Yo ensenar -> enseno
Yo escribir -> escribo
Tu ensenar -> ensenas
Tu escribir -> escribes
El ensenar -> ensena
El escribir -> escribe
Ella ensenar -> ensena
Ella escribir -> escribe
Usted ensenar -> ensena
Usted escribir -> escribe
Nosotros ensenar -> ensenamos
Nosotros escribir -> escribimos
Vosotros ensenar -> ensenais
Vosotros escribir -> escribis
Ellos ensenar -> ensenan
Ellos escribir -> escriben
Ellas ensenar -> ensenan
Ellas escribir -> escriben
Ustedes ensenar -> ensenan
Ustedes escribir -> escriben

Stem-changing input examples:

It does both e->ie changes and o->ue changes, properly avoiding the nostros + vostros cases:

$ echo "Yo abstenir"|python conj_golf2.py
abstieno
$ echo "Nostros abstenir"|python conj_golf2.py
abstenimos
$ echo "Tu almorzar"|python conj_golf2.py
almuerzas
$ echo "Vostros almorzar"|python conj_golf2.py
almorzais

Here is how the bonus was determined and the data string generated, from which you can deduce the verbs on which it works:

e="absten.acert.adher.adquer.advert.apret.asent.atraves.calent.cerr."+\
  "circunven.comenz.confer.confes.consent.conten.contraven.conven.convert."+\
  "difer.diger.discern.disent.freg.gobern.hed.hel.her.herv.infer.inger."+\
  "invern.invert.malher.manifest.ment.neg.nev.obten.ofend.pens.perd."+\
  "quer.recomend.reg.seg.sembr.sent.serr.sosegsosten.soterr.subarrend."+\
  "suger.tembl.tend.ten.tent.transfer.tropez.ven.vert"

u="absolv.acord.acost.almorz.along.amobl.apost.aprob.asol.avergonz."+\
  "coc.col.colg.cont.cost.degoll.demol.demostr.desaprob.descolg.descontr."+\
  "desos.destorc.devolv.disolv.dol.dorm.encontr.engros.envolv.forz.holg."+\
  "holl.llov.mol.mor.mostr.mov.ol.pobl.prob.record.reforz.remord.remov.renov."+\
  "repobl.resolv.resoll.reson.retorc.revolc.revolv."+\
  "rod.rog.sol.sold.sol.solt.son.torc.tost.tron.vol.volc.volv"

words = e.split(".") + u.split(".")
bonus = 0
for word in words:
    bonus += (len(word)+2)*2
print "Bonus: %d from %d stem-changing verbs" % (bonus, len(words))

s=(e+"|"+u).replace(".","")
zipped = s.encode('zip')
b64 = zipped.encode('base64')
print "The separator is at index %d" % s.index("|")
print "Uncompressed: %d chars, %d repr" % (len(s), len(`s`))
print "Compressed: %d chars, %d repr" % (len(zipped), len(`zipped`))
print "Comp+B64: %d chars, %d repr" % (len(b64), len(`b64`))

print "v="+`b64`

Which gives:

$ python conj_help.py
Bonus: 1796 from 127 stem-changing verbs
The separator is at index 326
Uncompressed: 645 chars, 647 repr
Compressed: 331 chars, 1015 repr
Comp+B64: 450 chars, 458 repr
v='eJw1UuHS5CAIe1aqrNsZhR6w/tj5Hv4Sv7uODRYDxEzlylKTplHS3xrS/3yIm4kntCTVSipkazaZ\n+AA32h3tY1ut+VL7NreXxsEEsgSheGynlJv/GNVvsPs9CIl2hoCSV+gYfuH7rdAyIQdr3+x92yCg\n2g7WEp4vMfTKgogyHabbL4z1l1p/1PLBCF4o9AjtmJBc6wpOTJykM+O0Ib2Y+FyCAuv5wcwCd+Ks\n4+XCdSwhqMIf/eJOFPMjV/rc0jw6IEvm8vjKdBuy/JryMPmEXwIiDInhtK01n1iDPrGu6/A5uy4/\nkBVd89R1OjvHCXbSnoDyaB23nhseElHosf45rzYC1zOevyDojQ548fjGCGg8M5aD8EAmB9GqgFHk\nBzRwDwJ6EcgK5aSDZ2/4TSAjKOMXd3gPh6sTq/+GApG0wkSYdzSBz/AXclUQ+g==\n'


Group a List by Frequency Given a list of integers, group the elements which occur most first, then group the next most and so on until each unique element in the list has been grouped once.

Examples:
Input: [1,2,3]
Output: [[1,2,3]]

Input: [1,1,1,2,2,3,3,4,5,6]
Output: [[1],[2,3],[4,5,6]]

Input: [1,1,1,4,5,6,6,6,7,7,8,8,8,8,8,8,8,9,5,6,5,6,5,6,5,6,-56]
Output: [[6, 8],[5],[1],[7],[9,4,-56]]

Input: []
Output: []

Input: (empty input)
Output: ERROR/Undefined/Doesn't matter

Rules

Groupings must go from maximal frequency to minimal frequency.
Internal order of the groupings are arbitrary (E.G. example 3 could have [8,6] instead).
This is code-golf, lowest byte-count wins.

Related

Sort the distinct elements of a list in descending order by frequency

Mathematica, 43 bytes

Union/@SortBy[l=#,f=-l~Count~#&]~SplitBy~f&

Try it online! (Using Mathics.)

Alternatively:

SortBy[Union[l=#],f=-l~Count~#&]~SplitBy~f&


Determine whether a car can get around a route with a limited amount of gas Using any programming language that supports functions, have the function

is_enough(strArr)

that take strArr which will be an an array consisting of the following elements:

N which will be the number of gas stations in a circular route
and each subsequent element will be the string g:c where

g is the amount of gas in gallons at that gas station and
c will be the amount of gallons of gas needed to get to the following gas station.

For example strArr may be:

["4","3:1","2:2","1:2","0:1"].

Your goal is to return the index of the starting gas station that will allow you to travel around the whole route once, otherwise return the string "impossible".

For the example above there are 4 gas stations, and your program should return the string "1" because:

Starting at station 1 you receive 3 gallons of gas and spend 1 getting to the next station.
Then you have 2 gallons + 2 more at the next station and you spend 2 so you have 2 gallons when you get to the 3rd station.
You then have 3 but you spend 2 getting to the final station,
At the final station you receive 0 gallons and you spend your final gallon getting to your starting point.

Starting at any other gas station would make getting around the route impossible, so the answer is "1".

If there are multiple gas stations that are possible to start at, return the smallest index (of the gas station). N will be >= 2.

Correct Sample Outputs:

Input: ["4","1:1","2:2","1:2","0:1"]
Output: "impossible"

Input: ["4","0:1","2:2","1:2","3:1"]
Output: "4"

The winner will be the one to use the shortest code although it will be long.


Do a BackFlip for ais523! This challenge is a prize for ais523 for winning the "Rookie of the Year" category in "Best of PPCG 2016". Congratulations!

BackFlip is an esoteric programming language made by user ais523, who has created well over 30 other interesting esolangs.

BackFlip is a 2D language like Befunge or ><> where the instruction pointer traverses a grid of text (the program), moving up, down, left, and right, changing direction depending on the character it's on. Critically, the grid in a BackFlip program changes as it is being traversed, a bit like Langton's Ant.

For this challenge you may assume that a BackFlip program is always a rectangular grid of text (all lines the same length), 1×1 in size at minimum, only containing the characters ./\<>^V. (. is used for visibility rather than space.) Semantically the BackFlip we'll use here is identical to the original spec.

The instruction pointer (IP) in BackFlip always starts just left of the top-left corner of the program, heading right. There are three types of commands it can encounter:

. is a no-op. The IP continues on in the direction it was going. The no-op stays a no-op.
/ and \ are mirrors. They reflect the IP in the direction indicated by their angle, then they change into the other type of mirror.

For example, if the IP heads left into a \, it starts moving upward instead of left and the \ becomes a /.

<, >, ^, and V are arrows. They redirect the IP to the direction they point in, then they change into an arrow that points in the direction the IP came from (opposite the direction the IP was moving).

For example, if the IP heads downward into >, it starts moving right instead of downwards and the > becomes a ^ because that is the direction the IP came from.

A BackFlip program terminates when the IP moves out of bounds, i.e. goes off the grid. It turns out all BackFlip programs eventually end because infinite loops are impossible. (You may assume this is true.)

Your goal in this challenge is to write a program or function that takes in a BackFlip program and outputs the number of moves the instruction pointer takes before the program terminates. That is, how many steps does the IP take in the course of running a program? This includes the initial step onto the grid and the final step off of it.

For example, the instruction pointer takes 5 steps in the trivial grid ....:

 ....  <- empty 4×1 grid
012345 <- step number of the IP

So the output to .... is 5.

In the more complex 4×2 grid

\...
\.><

the IP exits the grid on its 9th step, so the output is 9:

step  grid  IP position (@)
0     \...  @....
      \.><   ....

1     \...   @...
      \.><   ....

2     /...   ....
      \.><   @...

3     /...   ....
      /.><   .@..

4     /...   ....
      /.><   ..@.

5     /...   ....
      /.<<   ...@

6     /...   ....
      /.<<   ..@.

7     /...   ....
      /.><   .@..

8     /...   ....
      /.><   @...

9     /...   ....
      \.><   ....
             @

The shortest code in bytes wins.

You may take input as an array of lines or matrix of characters instead of a multiline string if desired, but you must use the characters ./\<>^V (not integer opcodes). You may use space instead of . if preferred. It's fine if characters like \ need to be escaped in input. Output is always an integer more than one.

Test Cases

....
5

\...
\.><
9

.
2

..
3

.
.
2

\
2

^
2

.^.
3

<.
2

\\
\/
7

>V
^<
6

>\
>/
6

\><
2

\><
\><
7

\><
\><
\><
12

\.V.
\.\<
5

\.V.
\./<
9

V./\
V./\
>./<
..\/
14

\V..
.^..
\/><
.V..
.^..
20

\.V.V.
\./.\<
.>\<..
..^.^.
31

\.V.V.V.
\./>/.\<
.>\>\<..
..^.^.^.
69

\.V.V.V.V.
\./>/>/.\<
.>\>\>\<..
..^.^.^.^.
145

\.V.V.V.V.V.V.V.V.V.V.
\./>/>/>/>/>/>/>/>/.\<
.>\>\>\>\>\>\>\>\>\<..
..^.^.^.^.^.^.^.^.^.^.
9721

JavaScript (ES6), 158 bytes

f=(a,x=0,y=0,d=3)=>a[x]&&(c=a[x][y])?(a[x][y]=c=='.'?c:c=='/'?(d^=3,'\\'):c=='\\'?(d^=1,'/'):'v>^<'[d][d='^<v>'.search(c),0],f(a,d<3?x+d-1:x,d?y+d-2:y,d)+1):1

Developed independently from @tsh's answer although strikingly similar.

The mapping of directions ^<v> to integers 0-3 is governed by the fact that .search('^') returns 0 since ^ is a regexp metacharacter.


Where did you COME FROM? INTERCAL is a wonderful language, but it is not always easy to understand other people's code. This is particularly the case if they use the COME FROM statement.

Challenge definition

Write a program or function which take the source code of an INTERCAL program as a text/data stream. If you write a function it is recommended that you also provide a program to call the function, but it will not count towards your score.
The function output will be a text/data stream of the jumps that program makes, according to the following instructions. The output does not need to be printed, but it does need to be a single text, not an array of strings (for example).
Each line of output will consist of the statement which will be COME FROM and the line number of its COME FROM statement, separated by a ->. An example:

(310)   DO .4 <- .3 -> 55

You can trim these lines of source code, but it is not necessary to.
The test cases will only consist of noncomputed labels (i.e., integer labels).
The output must be sorted by the source code order of the statements which will be COME FROM, not their label, nor the order of the COME FROM statements or their labels.
It is possible for multiple statements to COME FROM the same label. In such cases the COME FROM line numbers must be sorted, and separated by commas.
It is possible for a statement to COME FROM itself.
A COME FROM statement may be prefixed with a NOT statement. In such cases the line number must be wrapped in square brackets.
The words COME FROM can appear in a comment and must be ignored. You do not need to fully parse the file: if they are followed by a label (a number in parentheses) then you can assume it is a real statement.

Scoring

Entrants will be scored by the character length of their program or function.

Test cases

These test cases all come from the calvinmetcalf/intercal Github repo. Although any useful application will safely accept any input, for the purposes of this challenge you need only account for these five test cases.

rot13.i

(10) PLEASE DON'T GIVE UP -> 87
(33) DON'T GIVE UP -> 92

primes.i

(15)    DO (13) NEXT -> 26
(16)    DO .12 <- .1 -> 6
(23)    DO (21) NEXT -> 3

unlambda.i

(7202)  DO RETRIEVE .203+,202 -> 75
(4202)  DO ,202SUB.201.202#7 <- ,201SUB.201.202#7 -> 108
(6202)  DO ,201SUB.201.202#7 <- ,202SUB.201.202#7 -> 117
(4203)  DO READ OUT ,201SUB.201.202#7 -> 133
(4302)  DO .302 <- .2 -> 181
(5410)  DO ,400SUB#124 <- #4 $ #17 -> 293
(3410)  PLEASE (4410) NEXT -> 288
(5402)  DO (412) NEXT -> 328
(4412)  PLEASE (3412) NEXT -> 334
(3423)  DO FORGET #2 -> 375
(4404)  DO RETRIEVE .311+.312 -> 411
(5404)  PLEASE DO (414) NEXT -> 430
(4434)  DO FORGET #1 -> 441
(3454)  DO (103) NEXT -> 451
(5502)  DO .512 <- .312 -> 520
(8503)  PLEASE RETRIEVE .311+.312 -> 621
(7503)  DO (302) NEXT -> 515
(3622)  DO (302) NEXT -> 514
(603)   PLEASE FORGET #2 -> 622

pass.i

(10)    DO  NOTHING -> 5, 11
(20)    PLEASE  (100) NEXT -> 6
(30)    PLEASE  (200) NEXT -> 12
(103)   DO  (104) NEXT -> 27
(104)   DO  (105) NEXT -> 19
(1) DO  (2) NEXT -> 36
(2) DO  (105) NEXT -> 194
(202)   DO NOT  .2 <- #2 AGAIN -> [196]
(203)   DO  (204) NEXT -> 167
(204)   DO  (205) NEXT -> 159

continuation.i

(8201)  DO NOTHING -> 165, 271
(8202)  PLEASE NOTE Fork threads, one dormant, one alive -> 53, 58
(8211)  DO COME FROM (8211) -> 60
(8216)  DO NOTHING -> 71
(8215)  DO NOTHING -> 68
(8217)  DO COME FROM (8217) AGAIN -> 118
(8299)  DO COME FROM (8299) AGAIN -> 141
(8274)  DO (8273) NEXT ONCE -> 158
(8259)  PLEASE DO NOTHING -> 166
(8276)  DO COME FROM (8276) AGAIN -> 199
(8278)  PLEASE DO COME FROM (8278) AGAIN -> 237

JavaScript, 232 bytes

function c(d){for(var l,o,f,c,p=/^.(\d+).+?$/gm,a=/(T\s+)?C.{7}M .(\d+)/g,r='';l=p.exec(d);)for(f=0;o=a.exec(d);)o[2]==l[1]&&(c=d.slice(0,o.index).split('\n').length,r+=f++?', ':'\n'+l[0]+' -> ',r+=o[1]?'['+c+']':c);return r.trim()}

To be called with

var data = require( 'fs' ).readFileSync( process.argv[2] ).toString();
console.log( c( data ) );

Explanation

function c(d){
    for(
        // Initialise variables
        var l,o,f,c,p=/^.(\d+).+?$/gm,a=/(T\s+)?C.{7}M .(\d+)/g,r='';
        // Find lines beginning with a label
        l=p.exec(d);)
            for(
                // Reset a have-we-output-this-line flag
                f=0;
                // Find CALL FROM statements
                o=a.exec(d);)
                    // Filter to CALL FROM statements which have the current line
                    o[2]==l[1]&&(
                        // Calculate the line number of this CALL FROM statement
                        c=d.slice(0,o.index).split('\n').length,
                        // Concat the output for this line
                        r+=f++?', ':'\n'+l[0]+' -> ',r+=o[1]?'['+c+']':c);
    // Trim an initial new line
    return r.trim()}


Don't google "google" We all know that if you google the word "google" it will break the internet.

Your task is to create a function that accepts one string and returns its length, in the fewest possible Unicode characters.

However, if the given string is google (lowercase), it will cause an error.

For example, g('bing') will return 4 but g('google') will cause an error.

Please provide an example of usage, and the error if possible.

Python 2, 29

lambda x:len(x)/(x!='google')

Gives a ZeroDivisionError on "google", and the length otherwise. This takes advantage of Python's booleans equaling 0 and 1.


Gluing tetrahedra together (This challenge exists to extend sequence A276272 in the On-Line Encyclopedia of Integer Sequences, and perhaps create a new OEIS sequence1.)
This is a code-challenge, which will have you write code to compute as many terms of this sequence as possible.

Background

A polytet is a kind of polyform which is constructed by gluing regular tetrahedra together face-to-face in such a way that none of the interiors of the tetrahedra overlap. These are counted up to rotation in 3-space but not reflection, so if a particular shape is chiral it is counted twice: once for itself and once for its mirror image.

\$A267272(1) = 1\$ because there is one such configuration you can make out one tetrahedron.
\$A267272(2) = 1\$ because due to symmetry of the tetrahedra, gluing to a face is the same as any other face. This gives you the triangular bipyramid.
\$A267272(3) = 1\$ because the triangular bipyramid itself is symmetric, so adding a tetrahedron to any face results in a biaugmented tetrahedron.
\$A267272(4) = 4\$ because there are three distinct ways to add a tetrahedron to the biaugmented tetrahedron, and one is chiral (so it's counted twice). These are shown in the animated GIFs above.
\$A267272(5) = 10\$ as shown in George Sicherman's catalog. Three are chiral and four are achiral.

Rules
Run your code for as long as you'd like. The winner of this challenge will be the user who posts the most terms of the sequence, along with their code. If two users post the same number of terms, then whoever posts their last term earliest wins.
(Once more terms are computed, then whoever computed the code can add the new terms to the OEIS or I can add them and list the contributor if he or she desires.)

1 A sequence which (presumably) isn't already in the OEIS is the number of polytets up to reflection (i.e. chiral compounds are counted once, not twice). The first few values of this alternative sequence can be found in the George Sicherman link.

Rust, 11 (hopefully correct) terms

use ::std::ops::{Add, Sub, Mul};
use ::std::rc::Rc;
use ::std::hash::{Hash, Hasher};
use ::std::collections::HashSet;
use ::std::iter;
use ::std::fmt::{self, Formatter, Display};
use ::std::time::Instant;

type Coord = i128;

#[derive(Copy, Clone, PartialEq, Eq, Debug)]
struct Vec3([Coord; 3]);

impl Vec3 {
    fn dot(self, other: Vec3) -> Coord {
        self.0.iter().zip(other.0.iter()).map(|(a, b)| a * b).sum()
    }
}

impl Display for Vec3 {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        write!(f, "({}, {}, {})", self.0[0], self.0[1], self.0[2])
    }
}

impl Mul<Vec3> for Coord {
    type Output = Vec3;

    fn mul(self, mut vec: Vec3) -> Vec3 {
        for i in &mut vec.0 {
            *i *= self;
        }
        vec
    }
}

impl Add for Vec3 {
    type Output = Vec3;

    fn add(mut self, other: Vec3) -> Vec3 {
        for (i, n) in self.0.iter_mut().enumerate() {
            *n += other.0[i];
        }
        self
    }
}

impl Sub for Vec3 {
    type Output = Vec3;

    fn sub(self, other: Vec3) -> Vec3 {
        self + (-1 * other)
    }
}

#[derive(Clone, Debug)]
struct Tetrahedron([Vec3; 4]);

impl Default for Tetrahedron {
    fn default() -> Tetrahedron {
        Tetrahedron([
            Vec3([-1, -1, -1]),
            Vec3([-1,  1,  1]),
            Vec3([ 1, -1,  1]),
            Vec3([ 1,  1, -1]),
        ])
    }
}

impl Display for Tetrahedron {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        write!(f, "Tetrahedron({}, {}, {}, {})", self.0[0], self.0[1], self.0[2], self.0[3])
    }
}

impl Tetrahedron {
    fn collides(&self, other: &Tetrahedron) -> bool {
        let mut othervecs = [3 * self.0[1], 3 * self.0[2], 3 * self.0[3]];
        let sum = self.0[0] + self.0[1] + self.0[2] + self.0[3];
        let mut same = 0;

        for (i, &vec) in self.0.iter().enumerate() {
            let sum = sum - vec;
            let vec = 3 * vec;
            let through = vec - sum;
            for (j, &u) in other.0.iter().enumerate() {
                let u = 3 * u;
                if u == vec { same += 1 }
                let up = (sum - u).dot(through);
                for &v in &other.0[j+1..] {
                    let v = 3 * v;
                    let edge = v - u;
                    let ep = edge.dot(through);

                    if up.signum() != ep.signum() || up.abs() >= ep.abs() {
                        continue
                    }

                    let intersection = ep * u + up * edge;
                    if othervecs.iter().enumerate().all(|(i, &ov)| {
                        let mid = othervecs[(i+1)%3] + othervecs[(i+2)%3];
                        let ov = 2 * ov - mid;
                        (2 * intersection - ep * mid).dot(ep * ov) > 0
                    }) {
                        return true
                    }
                }
            }

            if i != 3 { othervecs[i] = vec; }
        }
        if same == 4 { panic!("EQUAL TETRAHEDRA IN .collides()"); }
        false
    }

    // Mirroring also scales by 3
    fn mirror(&self, i: usize) -> Tetrahedron {
        let mut sum = Vec3([0; 3]);
        for (j, &vec) in self.0.iter().enumerate() {
            if j != i { sum = sum + vec; }
        }

        let mut copy = self.clone();
        copy.scale();

        copy.0[i] = 2 * sum - copy.0[i];
        copy.swap(i, 3);
        copy.rotate_left(i);

        copy
    }

    fn scale(&mut self) {
        for vec in self.0.iter_mut() {
            *vec = 3 * *vec;
        }
    }

    fn rotate_left(&mut self, n: usize) {
        self.0[..3].rotate_left(n)
    }

    fn swap(&mut self, a: usize, b: usize) {
        self.0.swap(a, b)
    }

    fn reverse(&mut self) {
        self.0.reverse()
    }
}

type EndpointIter<'a> = Box<dyn Iterator<Item = Endpoint> + 'a>;

#[derive(Debug, Clone)]
struct Endpoint {
    tree: Rc<TetraTree>,
    hedron: Rc<Tetrahedron>,
}

impl Endpoint {
    fn iter_endpoints(&self) -> EndpointIter {
        let mut hedron = Rc::clone(&self.hedron);
        //Rc::make_mut(&mut hedron).swap(0, 3);
        Rc::make_mut(&mut hedron).reverse();

        Box::new(self.clone().into_iter_directions()
            .chain(self.tree.iter_endpoints(
                Rc::new(TetraTree {
                    subtrees: [None, None, None],
                    hedron,
                })
            ))
        )
    }

    fn into_iter_directions(self) -> EndpointIter<'static> {
        Box::new(iter::successors(Some(self), |this| {
            let mut this = this.clone();
            Rc::make_mut(&mut this.tree).rotate_left(1);
            Rc::make_mut(&mut this.hedron).0[1..].rotate_left(1);
            Some(this)
        }).take(3))
    }

    fn iter_extensions(&self) -> EndpointIter {
        let mut tree = self.tree.as_ref().clone();
        tree.scale();

        let mut hedron = self.hedron.as_ref().clone();
        //hedron.swap(0, 3);
        hedron.reverse();
        hedron.scale();

        Box::new(Endpoint {
            tree: Rc::new(tree),
            hedron: Rc::clone(&self.hedron),
        }.into_iter_directions().filter_map(|endpoint| {
            let mut new = endpoint.hedron.mirror(3);
            new.swap(0, 3);
            if endpoint.tree.collides(&new) {
                None
            } else {
                let mut hedron = endpoint.hedron;
                Rc::make_mut(&mut hedron).scale();

                Some(Endpoint {
                    tree: Rc::new(TetraTree {
                        subtrees: [Some(endpoint.tree), None, None],
                        hedron,
                    }),
                    hedron: Rc::new(new),
                })
            }
        }).chain(self.tree.iter_extensions(Rc::new(TetraTree {
            subtrees: [None, None, None],
            hedron: Rc::new(hedron),
        }))))
    }

    fn iter_tetrahedra<'a>(&'a self)
      -> Box<dyn Iterator<Item = &Tetrahedron> + 'a> {
        Box::new(
          iter::once(self.hedron.as_ref()).chain(self.tree.iter_tetrahedra())
        )
    }
}

impl Default for Endpoint {
    fn default() -> Endpoint {
        Endpoint::from(Tetrahedron::default())
    }
}

impl From<Tetrahedron> for Endpoint {
    fn from(mut hedron: Tetrahedron) -> Endpoint {
        let mirrored = hedron.mirror(0);
        hedron.scale();

        Endpoint {
            tree: Rc::new(TetraTree {
                subtrees: [None, None, None],
                hedron: Rc::new(mirrored),
            }),
            hedron: Rc::new(hedron),
        }
    }
}

impl Hash for Endpoint {
    fn hash<H: Hasher>(&self, hasher: &mut H) {
        let mut stuff: Vec<_> = self.tree.hash_helper(1).collect();
        stuff.push(self.tree.len());
        stuff.sort();
        stuff.hash(hasher);
    }
}

impl PartialEq for Endpoint {
    fn eq(&self, other: &Endpoint) -> bool {
        self.iter_endpoints().any(|ep| ep.tree == other.tree)
    }
}

impl Eq for Endpoint {}

#[derive(Debug, Clone)]
struct TetraTree {
    subtrees: [Option<Rc<TetraTree>>; 3],
    hedron: Rc<Tetrahedron>,
}

impl TetraTree {
    fn iter_endpoints<'x>(&'x self, behind: Rc<TetraTree>) -> EndpointIter<'x> {
        let mut iterator = self.subtrees.iter().enumerate()
          .filter_map(|(i, opt)| opt.as_ref().map(|some| (i, some)));

        if let Some(first) = iterator.next() {
            let closure = move |(i, subtree): (usize, &'x Rc<TetraTree>)| -> EndpointIter<'x> {
                let mut behind = behind.as_ref().clone();
                behind.rotate_left(3-i);

                let mut this = self.clone();
                this.rotate_left(i);

                Rc::make_mut(&mut this.hedron).reverse();

                this.subtrees.swap(1, 2);
                this.subtrees[0] = Some(Rc::new(behind));

                for (j, subtree) in this.subtrees.iter_mut().enumerate().skip(1)
                  .filter_map(|(j, s)| s.as_mut().map(|s| (j, s))) {
                    Rc::make_mut(subtree).rotate_left(j);
                }

                subtree.iter_endpoints(Rc::new(this))
            };
            Box::new(closure(first).chain(iterator.flat_map(closure)))
        } else {
            let mut hedron = self.hedron.as_ref().clone();
            //hedron.swap(0, 3);
            hedron.reverse();
            Endpoint {
                tree: Rc::clone(&behind),
                hedron: Rc::new(hedron),
            }.into_iter_directions()
        }
    }

    fn rotate_left(&mut self, i: usize) {
        self.subtrees.rotate_left(i);
        Rc::make_mut(&mut self.hedron).rotate_left(i);
    }

    fn collides(&self, hedron: &Tetrahedron) -> bool {
        self.hedron.collides(hedron) ||
          self.subtrees.iter()
            .filter_map(Option::as_ref)
            .any(|subtree| subtree.collides(hedron))
    }

    fn scale(&mut self) {
        for subtree in self.subtrees.iter_mut().filter_map(Option::as_mut) {
            Rc::make_mut(subtree).scale();
        }
        Rc::make_mut(&mut self.hedron).scale();
    }

    fn iter_extensions(&self, behind: Rc<TetraTree>) -> EndpointIter {
        Box::new(self.subtrees.iter().enumerate().flat_map(move |(i, next)| {
            let mut behind = behind.as_ref().clone();
            behind.rotate_left(3-i);

            let mut this = self.clone();
            this.rotate_left(i);

            let hedron = Rc::make_mut(&mut this.hedron);
            hedron.reverse();

            this.subtrees.swap(1, 2);
            this.subtrees[0] = Some(Rc::new(behind));

            for (j, subtree) in this.subtrees.iter_mut().enumerate().skip(1)
              .filter_map(|(j, s)| s.as_mut().map(|s| (j, s))) {
                let subtree = Rc::make_mut(subtree);
                subtree.scale();
                subtree.rotate_left(j);
            }

            if let Some(next) = next {
                hedron.scale();
                next.iter_extensions(Rc::new(this))
            } else {
                let mut mirrored = hedron.mirror(3);
                mirrored.swap(0, 3);
                hedron.scale();

                if this.collides(&mirrored) {
                    Box::new(iter::empty()) as EndpointIter
                } else {
                    Box::new(iter::once(Endpoint {
                        tree: Rc::new(this),
                        hedron: Rc::new(mirrored),
                    }))
                }
            }
        }))
    }

    fn iter_tetrahedra<'a>(&'a self)
      -> Box<dyn Iterator<Item = &Tetrahedron> + 'a> {
        Box::new(iter::once(self.hedron.as_ref()).chain(
          self.subtrees.iter()
            .filter_map(Option::as_deref)
            .flat_map(TetraTree::iter_tetrahedra)
        ))
    }

    fn len(&self) -> usize {
        1usize + self.subtrees.iter()
              .filter_map(Option::as_deref).map(TetraTree::len).sum::<usize>()
    }

    fn hash_helper<'a>(&'a self, behind: usize)
      -> Box<dyn Iterator<Item = usize> + 'a> {
        let sub: Vec<_> = self.subtrees.iter().filter_map(Option::as_deref)
          .map(|a| (a, a.len())).collect();
        let sum = sub.iter()
          .map(|&(_, len)| len).sum::<usize>() + behind + 1;
        Box::new(iter::once(behind).chain(
            sub.into_iter().flat_map(move |(sub, len)|
                        iter::once(len).chain(sub.hash_helper(sum - len)))
        ))
    }
}

impl PartialEq for TetraTree {
    fn eq(&self, rhs: &TetraTree) -> bool {
        self.subtrees == rhs.subtrees
    }
}

impl Eq for TetraTree {}

fn main() {
    let verbose = std::env::args().skip(1).any(|arg| arg == "-v");
    let begin = Instant::now();

    println!("1: 1 [{}ms]", begin.elapsed().as_millis());
    if verbose {
        println!("{}\n--", Tetrahedron::default());
    }

    let mut polytets = HashSet::new();
    polytets.insert(Endpoint::default());

    for i in 2.. {
        println!("{}: {} [{}ms]", i, polytets.len(), begin.elapsed().as_millis());

        if verbose {
            for polytet in &polytets {
                for hedron in polytet.iter_tetrahedra() {
                    println!("{}", hedron);
                }
                println!("--");
            }
        }

        polytets = polytets.iter()
          .flat_map(Endpoint::iter_extensions)
          .collect();
    }
}

Try it online! The footer contains some compatability implementations because TIO's Rust is a little old. (This has already been reported and added to the list.)
Output:
1: 1 [0ms]
2: 1 [0ms]
3: 1 [2ms]
4: 4 [8ms]
5: 10 [35ms]
6: 39 [139ms]
7: 164 [738ms]
8: 767 [4328ms]
9: 3656 [31298ms]
10: 18186 [287871ms]
11: 91532 [3154716ms]

As you can see, it also reports how long it took. (These are cumulated times.) You can use the -v option to list all tetrahedra for each polytet.
I don't really have a good way of verifying the results beyond A267272(5). I hope it works, but I'm not sure.
The idea is that we store the polytet as a tree of tetrahedra that also encodes orientation. But for collision detection we need actual tetrahedra. We start with the tetrahedron with vertices (-1, -1, -1), (-1, 1, 1), (1, -1, 1), (1, 1, -1) and scale all tetrahedra by 3 for every term. This avoids the need for fractions.
Can probably be made faster, but I don't know how.


Babylon.js - loop through a scene and apply a simple fragment shader to all of the objects You have a library - a fully loaded 2014 Babylon.js.

You have a fragment shader - let's call it sample.fragment.fx.

You have a scene - loaded ahead of time, possibly from a .babylon JSON file.

Your goal is to assign the fragment shader to every textured object in the scene using a snippet of JavaScript or TypeScript code.

Scoring:

The main multiplier is calculated in the form of one divided by the total number of bytes in the snippet not counting whitespace characters used for formatting.

Additional multipliers (apply one for each condition met) -

*0.5 (bad) - The solution does not reference the "sample" fragment shader by name.

*0.8 (bad) - The solution is presented in TypeScript.

*1.1 (good) - The solution implements a proper for loop (either the for or forEach keyword is used).

*1.2 (good) - The solution intelligently applies the shader only to objects that meet a certain arbitrary criterion, for example: it has texture, or it has a certain prefix in its name.

*1.3 (good) - After all multipliers are applied, the score is greater than 0.008.

This should remain open indefinitely. The highest score wins.

In Javascript

// The suffix of all meshes wich should have the shader applied
var suffix = "shader";

//If true, the shader will be applied on this mesh
var predicate = function(mesh) {
    return (
       mesh.material
       && mesh.name.indexOf(suffix , mesh.name.length - suffix.length) !== -1
    );
};

// Creation of the shader material
var shaderMaterial = new BABYLON.ShaderMaterial("sampleShader", scene, "sample", {
            attributes: ["position"],
            uniforms: ["worldViewProjection"]
            });

// Apply the shader on all meshes
scene.meshes.forEach(function(m) {
    if (predicate(m)) {
        m.material = shaderMaterial;
    }
});


Tips for golfing in Befunge 93 What general tips do you have for golfing in Befunge 93? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to Befunge 93 (e.g. "remove comments" is not an answer). Please post one tip per answer.

As little white space as possible.

If you have a 10x5 (50) code, can you make it into a 6x8 (48):

some code
goes here
and it is
exactly 50
characters

goes to

put a bi
t of cod
e here a
nd count
all of 4
0 chars!


Quotes around sequence of chars Challenge

Your goal is to write a function that puts quotes around a sequence of capital letters in a string.

So some examples (everything on the left (before function) and right (after function) are STRINGS):

Hello the name's John Cena -> "H"ello the name's "J"ohn "C"ena

I got BIG OLD truck -> "I" got "BIG" "OLD" truck

[OLD, joe, SMOE] ->["OLD", joe, "SMOE"]

'BIG') -> '"BIG"')

fOOd -> f"OO"d

"78176&@*#dd09)*@(&#*@9a0YOYOYOYOYOYOOYOYOYOY28#@e -> "78176&@*#dd09)*@(&#*@9a0"YOYOYOYOYOYOOYOYOYOY"28#@e

Assumptions and Clarifications

The sequence of capital letters can have a length of one (e.g. a string containing one character: H -> "H")
You can assume there will be only a string inputted.

Winning Criteria

Code golf, fewest bytes wins.

05AB1E, 13 bytes

0.ø.γ.u}'"ý¦¨

Try it online!

0.ø              # surround input string with 0s
   .γ  }         # group characters by:
     .u          #  is uppercase?
        '"ý      # join groups with quotes
           ¦¨    # remove the first and last characters (0s)


Wait, what language is this? Recently I had the pleasure of writing a Haskell program that could detect if the NegativeLiterals extension was engaged.  I came up with the following:

data B=B{u::Integer}
instance Num B where{fromInteger=B;negate _=B 1}
main=print$1==u(-1)

Try it online!

This will print True normally and False otherwise.

Now I had so much fun doing this I'm extending the challenge to all of you.  What other Haskell language extensions can you crack?

Rules

To crack a particular language extension you must write a Haskell program that compiles both with and without the language extension (warnings are fine) and outputs two different non-error values when run with the language extension and it turned off (by adding the No prefix to the language extension).  In this way the code above could be shortened to just:

data B=B{u::Integer}
instance Num B where{fromInteger=B;negate _=B 1}
main=print$u(-1)

which prints 1 and -1.

Any method you use to crack a extension must be specific to that extension.  There may be ways of arbitrarily detecting what compiler flags or LanguageExtensions are enabled, if so such methods are not allowed.  You may enable additional language extensions or change the compiler optimization using -O at no cost to your byte count.

Language extensions

You cannot crack any language extension that does not have a No counterpart (e.g. Haskell98, Haskell2010, Unsafe, Trustworthy, Safe) because these do not fall under the terms outlined above.  Every other language extension is fair game.

Scoring

You will be awarded one point for every language extensions you are the first person to crack and one additional point for every language extension for which you have the shortest (measured in bytes) crack. For the second point ties will be broken in favor of earlier submissions.  Higher score is better

You will not be able to score a point for first submission on NegativeLiterals or QuasiQuotes because I have already cracked them and included them in the body of the post.  You will however be able to score a point for the shortest crack of each of these.  Here is my crack of QuasiQuotes

import Text.Heredoc
main=print[here|here<-""] -- |]

Try it online!

MagicHash, 30 bytes

x=1
y#a=2
x#a=1
main=print$x#x

-XMagicHash outputs 1, -XNoMagicHash outputs 2

MagicHash allows variable names to terminate in a #. Therefore with the extension, this defines two functions y# and x# which each take a value and return a constant 2, or 1. x#x will return 1 (because it is x# applied to 1)

Without the extension, this defines one function # which takes two arguments and returns 2. The x#a=1 is a pattern that never gets reached. Then x#x is 1#1, which returns 2.


2D Collision Detection This challenge is based on actual collision detection I had to write for a simple game recently.

Write a program or function which, given two objects, returns a truthy or falsy value depending on whether the two objects are in collision (i.e. intersect) or not.

You need to support three types of objects:

Line segments: represented by 4 floats, indicating the two endpoints, i.e. (x1,y1) and (x2,y2). You may assume that the endpoints are not identical (so the line segment is not degenerate).
Discs: i.e. filled circles, represented by 3 floats, two for the centre (x,y) and one (positive) for the radius r.
Cavities: these are a disc's complement. That is, a cavity fills all of 2D space, except a circular region, specified by a centre and radius.

Your program or function will receive two such objects in the form of an identifying integer (of your choice) and their 3 or 4 floats. You can take input via STDIN, ARGV or function argument. You may represent the input in any convenient form that is not preprocessed, e.g. 8 to 10 individual numbers, two comma-separated list of values or two lists. The result can be returned or written to STDOUT.

You may assume that the objects are either at least 10-10 length units apart or intersect by that much, so you don't need to worry about the limitations of floating point types.

This is code golf, so the shortest answer (in bytes) wins.

Test Cases

Representing line segments with 0, discs with 1 and cavities with 2, using a list-based input format, the following should all produce a truthy output:

[0,[0,0],[2,2]], [0,[1,0],[2,4]]        # Crossing line segments
[0,[0.5,0],[-0.5,0]], [1,[0,0],1]       # Line contained in a disc
[0,[0.5,0],[1.5,0]], [1,[0,0],1]        # Line partially within disc
[0,[-1.5,0.5],[1.5,0.5]], [1,[0,0],1]   # Line cutting through disc
[0,[0.5,2],[-0.5,2]], [2,[0,0],1]       # Line outside cavity
[0,[0.5,0],[1.5,0]], [2,[0,0],1]        # Line partially outside cavity
[0,[-1.5,0.5],[1.5,0.5]], [2,[0,0],1]   # Line cutting through cavity
[1,[0,0],1], [1,[0,0],2]                # Disc contained within another
[1,[0,0],1.1], [1,[2,0],1.1]            # Intersecting discs
[1,[3,0],1], [2,[0,0],1]                # Disc outside cavity
[1,[1,0],0.1], [2,[0,0],1]              # Disc partially outside cavity
[1,[0,0],2], [2,[0,0],1]                # Disc encircling cavity
[2,[0,0],1], [2,[0,0],1]                # Any two cavities intersect
[2,[-1,0],1], [2,[1,0],1]               # Any two cavities intersect

while the following should all result in a falsy output

[0,[0,0],[1,0]], [0,[0,1],[1,1]]        # Parallel lines
[0,[-2,0],[-1,0]], [0,[1,0],[2,0]]      # Collinear non-overlapping lines
[0,[0,0],[2,0]], [0,[1,1],[1,2]]        # Intersection outside one segment
[0,[0,0],[1,0]], [0,[2,1],[2,3]]        # Intersection outside both segments
[0,[-1,2],[1,2]], [1,[0,0],1]           # Line passes outside disc
[0,[2,0],[3,0]], [1,[0,0],1]            # Circle lies outside segment
[0,[-0.5,0.5],[0.5,-0.5]], [2,[0,0],1]  # Line inside cavity
[1,[-1,0],1], [1,[1,1],0.5]             # Non-intersecting circles
[1,[0.5,0],0.1], [2,[0,0],1]            # Circle contained within cavity

APL, 279 208 206 203

s←1 ¯1
f←{x←⊣/¨z←⍺⍵[⍋⊣/¨⍺⍵]
2 2≡x:∧/0∧.=⌊(2⊃-⌿↑z)⌹⍣(≠.×∘⌽/x)⍉↑x←s×-/2⊢/↑z
2≡2⌷x:∨/((2⊃z)∇2,x[1]×(2⌷⊃z)+,∘-⍨⊂y÷.5*⍨+.×⍨y←⌽s×⊃-/y),x[1]=(×⍨3⊃⊃z)>+.×⍨¨y←(s↓⌽↑z)-2⌷⊃z
~x∨.∧x[1]≠(.5*⍨+.×⍨2⊃-⌿↑z)<-/⊢/¨z×s*1⌷x}

Line breaks in the function f are for clarity. They should be replaced with the statement separator ⋄

It has been so long since I last made such a complex APL program. I think the last time was this but I am not even sure that was as complex.

Input format
Basically same as the OP, except using 0 for cavity, 1 for disc and 2 for line segment.

Major update

I managed to golf a lot of chars using a different algorithm. No more g bulls**t!!

The main function f is divided into cases:

2 2≡x: Segment-segment

In this case, calculate the vector from the end points of each line and solve a system of linear equations to check if the intersection is contained within the vectors.

Caveats:

The end point of a vector is not considered as a part of the vector (while its origin is). However, if only the tip of a vector is on the other one, the input is invalid according to spec.
Non-degenerate parallel segments always returns false, regardless of collinearity.
If one of the segments is degenerate, always return false. If both segments are degenerate, always return true.

Examples: (Note caveat 1 in action in the figure on the right)

2≡2⌷x: Segment-other

In this case, the other object is a circular one. Check if the end points of the segment is within the circle using distance check.

In the disc case, also construct a line segment of the diameter perpendicular to the given segment. Check if the segments collide by recursion.
In the cavity case, sneak in a "times 0" in the construction of the said segment to make it degenerate. (See why I use 0 for cavity and 1 for disc now?) As the given segment is not degenerate, the segment-segment collision detection always return false.

Finally combine the results of the distance checks and the collision detection. For the cavity case, negate the results of the distance checks first. Then (in both cases) OR the 3 results together.

Regarding the segment-segment caveats, numbers 3 is addressed (and exploited). Number 2 is not a problems as we are intersecting perpendicular segments here, which are never parallel if they are not degenerate. Number 1 takes effect only in the disc case, when one of the given end points is on the constructed diameter. If the end point is well inside the circle, the distance checks would have taken care of it. If the end point is on the circle, since the constructed diameter is parallel to the given segment, the latter must be tangent to the circle with only one point touching the disc, which is not valid input.

Examples:

Default case: Other-other

Calculate the distance between the centers. Disc-disc collision occurs if and only if the distance is smaller than the sum of radii. Disc-cavity collision occurs if and only if the distance is greater than the difference in radii.

To take care of the cavity-cavity case, negate the result of the distance check, AND with each of the identifying integers and then OR them together. Using some logic, one can show that this process returns true if and only if both identifying integers are falsy (Cavity-cavity case), or if the distance check returned true


"Hello world" that creates a different "Hello world" program Create a program, that outputs a hello world string ("Hello world", "Hello, World" etc.), and source code. Output is written to stdout or equivalent. Hello world string is embedded in the source code.

For example, the output for might be

(some source code here)hello world(some source code here)

When the output is compiled or interpreted again, it should create a similar output, but the hello world string must have a different punctuation or capitalization. For example, the previous example could create the following output

(some source code here)hello, wORld(some source code here)

Each "(some source code here)" in these examples can change after each execution, or it can be the same.

Your output must contain a valid hello world string exactly once. It may contain any amount of invalid hello world strings. Source code may contain any amount of comments, and the hello world string may be embedded in comments. The first program can have either zero or one valid hello world strings, but no more.

Following punctuation is valid:

hello, world
hello world
helloworld

Any capitalization is acceptable. For example, these are valid hello world strings:

Hello, world
hellO WORld
HELLoworlD

These strings are not valid:

Hello     world
Hello(newline)world
Hello,world
Hello, Steve

Your program fails as soon as one of the following conditions are met:

It outputs a hello world string that has been output during some earlier execution,
output is no longer valid source code in the same language, or
output does not contain exactly one valid hello world string.

Your program is not valid for this contest unless at least two first executions are successful. This means that the third output is allowed to be invalid. Output of your program may not be random. First execution should always create the same second output, second execution should always create the same third output, etc.

Score is calculated as amount of bytes in the source code of the initial program. Lowest score wins.

Following bonuses do apply (up to -60%):

-5% * (N - 2), where N is the index of the execution after which your program produces invalid output. This bonus caps at -50%. If your program succeeds 12 times or more, you get the max bonus.
-10%, if your outputs (including first source code) include all three valid punctuation alternatives.

Your submission should include the first source code, and it should also contain the outputs of the successful executions. If your program succeeds more than 12 times, add output for 12 executions.

Example

Next line is the first source code. When we execute it, it is the first execution.

hello world(some source code here)

Next line is the output from the first source code code. It is the first output.

hello, world(some source code here)

Next line is the output from the second execution. It is the second output.

helloworld(some source code here)

When we executed the first output, this program became eligible for the -10% bonus. That means we have two outputs, and one original code, which all have different punctuation. Moreover, because the second output was valid, this program is eligible for this contest.

Next line is the output from the third execution. It is the third output.

Helloworld(some source code here)

Next line is the output from the fourth execution. It is the fourth output.

hellworld(some source code here)

This output was invalid. Index of the last valid execution was 4. This program is eligible for -5% * (4 - 2) bonus and -10% bonus from the punctuation. This makes total of -20%. The length of the first source code ("hello world(some source code here)") was 34 bytes, so the final score is 27.2.

Mathematica, 214 194 - 50% = 97 bytes
(a = "helloworld"; b = Apply[StringJoin, Tuples[Thread[Characters[{ToLowerCase[a], ToUpperCase[a]}]]], {1}]; StringReplacePart[ToString[#0, InputForm], b[[FirstPosition[b, a] + 1]], {7, 16}]) &

I decided to optimize for string count here. This runs for 1024 programs without stopping, going through every combination of uppercase and lowercase letters. The execution can be seen here.


Produce the number 2014 from an image In the 2014 challenge, Michael Stern suggests using OCR to parse  to 2014. I'd like to take this challenge in a different direction. Using built-in OCR from the language/standard library of your choice, design the smallest image (in bytes) which is parsed into the ASCII string "2014".

Stern's original image is 7357 bytes, but with a bit of effort it can be losslessly compressed to 980 bytes. No doubt the black-and-white version (181 bytes) works as well with the same code.

Rules: Each answer should give the image, its size in bytes, and the code needed to process it. No custom OCR allowed, for obvious reasons...! Any reasonable languages and image formats are allowed.

Edit: In response to comments, I'll broaden this to include any preexisting library, or even http://www.free-ocr.com/ for those languages where no OCR is available.

Shell (ImageMagick, Tesseract), 18 bytes

file=golf_2014
echo -n UDQKMTMgNQruqCqo6riKiO6I | base64 -d > $file.pbm
convert -border 2x2 -bordercolor white -resize 300% -sharpen 0 -monochrome $file.pbm $file.png
tesseract $file.png $file digits
cat $file.txt
rm $file.pbm $file.png $file.txt

The image is 18 bytes and can be reproduced like this:

echo -n UDQKMTMgNQruqCqo6riKiO6I | base64 -d > 2014.pbm

It looks like this (this is a PNG copy, not the original):

After processing with ImageMagick, it looks like this:

Using ImageMagick version 6.6.9-7, Tesseract version 3.02. The PBM image was created in Gimp and edited with a hex editor.

This version requires jp2a.

file=golf_2014
echo -n UDQKMTMgNQruqCqo6riKiO6I | base64 -d > $file.pbm
convert -border 2x2 -bordercolor white -resize 300% -sharpen 0 -monochrome $file.pbm $file.png
tesseract $file.png $file digits
cat $file.txt
convert -background black -fill white -border 2x2 -bordercolor black -pointsize 100 label:$(cat $file.txt) $file.jpg
jp2a --chars=" $(cat $file.txt) " $file.jpg
rm $file.pbm $file.png $file.txt $file.jpg

It outputs something like this:

    2014444444102         01144444102              214441                 214441
   1             1      24           1            04    4                0     4
  1    410201     0    0    410004    1       2014      4              21      4
 24   42     0    4    4    0     1    0    24          4             04       4
  22222      1    1   0    42     0    4    2   4100    4            1   41    4
            1    42   0    4      2     2   2412   0    4          24   420    4
          04    42    0    1      2     2          0    4         0   40  0    4
       204    42      0    1      2     2          0    4       24   42   0    4
     21     12        0    4      0    42          0    4      2     411114     1112
    04   412          24    0     1    0           0    4      0                   0
  24     1111111110    1    42  21    4            0    4      200011111001    40002
  4               4     04    44     42            0    4                 0    4
 0                4      214       10              0    4                 0    4
  22222222222222222         222222                  22222                  22222


Find all diagonal counts in only one direction If I need to get the number of diagonal squares in all directions:

I do the following formula 2 N − 2 − |x − y| − |x + y − N − 1|

The above example has 13 and that's what the formula gives.

Now, what if you wanted to get the diagonal squares, but only in one direction?

The top right has 4 squares, the top left has 3, the bottom left has 3 and the bottom right has 3.

Assume I have that program to compute all legal diagonals for the Queen, and as I demonstrated above I can get all diagonals by one step using above formula, written like :

int positiveDiagonal = Math.abs(r_q - c_q);
int negativeDiagonal = Math.abs(r_q + c_q - n - 1);
int totalDiagonal = 2 * n - 2 - positiveDiagonal - negativeDiagonal;

So, assume there is a soldier on position (5,5), that's make the Queen can't move to others diagonals in the same direction with total 4 count.

Sample Input - 1:

Board length = 8
Queen on position (4, 4)
There is no soldiers.
Explanation :

Because there is no pieces (soldiers), we just get all diagonals we calculated using our formula.

Output - 1: 13

Sample Input - 2:

Board length = 8
Queen on position (4, 4)
There is a soldiers on point (5, 3)
Explanation :

Because there is a piece or whatever, on point (5, 3), The Queen can't go to (5, 3), (6, 2) and (7, 1).

Output - 2: The total diagonals we got from formula is 13 and by calculating the soldier diagonals [The steps that queen can't go through], the result would be  10.

Sample Input - 3:

Board length = 5
Queen on position (5, 5)
There is a soldiers on point (1, 1)
Explanation :

Because there is a piece (soldier), on point (1, 1), The Queen can't go to that square.

Output - 3: By subtracting this square from total diagonals which equal 4 it's results  3

Sample Input - 4:

Board length = 5
Queen on position (3, 3)
Soldiers on positions (5, 5) , (2, 1), and (4, 4)
Explanation :

Because there is a piece (soldier), on point (5, 5) and (4, 4), The Queen can't go to these squares.

Output - 4 = 6

Jelly, 41 37 bytes

æ.µṬ+ḢṬ$+⁴²x@0¤s⁴µŒD;UŒD$ṣ€1Ẏ=2Ẹ$ƇF¬S

Try it online!

A dyadic link that takes as its left argument the zero-indexed positions of the queen and any soldiers as a list (queen first, any subsequent entries a solider) and as right argument the board size. Returns an integer that represents the number of squares available for moves on the diagonal.

Explanation

æ.                                    | dot product of piece positions with board size, right-padded with 1
  µ                                   | start new chain with this as input
   Ṭ                                  | make a boolean array with 1 at the position of each piece
    +ḢṬ$                              | and add the same again for the Queen so the Queen has a 2
        +⁴²x@0¤                       | expand to the board dimension square with zeroes
               s⁴                     | split into lists the length of the board dimension
                 µ                    | start a new chain
                  ŒD;UŒD$             | concatenate the diagonals and the diagonals of the flipped board
                         ṣ€1          | split at soldiers
                            Ẏ         | tighten (make a single list of lists)
                             =2Ẹ$Ƈ    | filter keeping only those diagonals with the Queen in
                                 F¬S  | count the number of zeroes


Generate an ASCII Padovan Spiral This is the ASCII version of this challenge. The initial post was separated per request by Martin Ender

Introduction

Similar to the Fibonacci Sequence, the Padovan Sequence (OEIS A000931) is a sequence of numbers that is produced by adding previous terms in the sequence. The initial values are defined as:

P(0) = P(1) = P(2) = 1

The 0th, 1st, and 2nd terms are all 1. The recurrence relation is stated below:

P(n) = P(n - 2) + P(n - 3)

Thus, it yields the following sequence:

1, 1, 1, 2, 2, 3, 4, 5, 7, 9, 12, 16, 21, 28, 37, 49, 65, 86, 114, 151, 200, 265, 351, ...

Using these numbers as side lengths of equilateral triangles yields a nice spiral when you place them all together, much like the Fibonacci Spiral:

Image courtesy of Wikipedia

Task

Your task is to write a program that recreates this spiral by ASCII art, with input corresponding to which term. Since a triangle of side length 1 (1 character) is impossible to represent nicely in ASCII, the side lengths have been dilated by a factor of 2. Thus, the triangle of side length 1 is actually represented like so:

 /\
/__\

So, for example, if the input was 5 (the 5th term), the output should be:

   /\
  /  \
 /    \
/______\
\      /\
 \    /__\
  \  /\  /
   \/__\/

The first 5 terms were 1, 1, 1, 2, 2, so the triangle had side lengths 2, 2, 2, 4, 4 due to dilation. Another example for input 8:

     __________
   /\          /\
  /  \        /  \
 /    \      /    \
/______\    /      \
\      /\  /        \
 \    /__\/          \
  \  /\  /            \
   \/__\/______________\
    \                  /
     \                /
      \              /
       \            /
        \          /
         \        /
          \      /
           \    /
            \  /
             \/

Rules

You must print the result, and input must be an integer corresponding to term number
Trailing and leading newlines are allowed, trailing spaces after lines are allowed also
Your submission must be able to handle at least up to the 10th term (9)
Your submission must be a full program or function that takes input and prints the result
Rotations of the output are allowed, in 60 degree multiples, but the size of the triangles must remain the same, along with the representation
Going counter-clockwise is also allowed
Standard loopholes are forbidden

You may assume that input will be >0 and that correct format of input will be given.

Scoring

This is code-golf, so the shortest code in bytes wins. Happy New Years everyone!

Befunge, 871 836 798 bytes

&00p45*:10p20p030p240p050p060p9010gp9110gp1910gp1-91+10gpv
<v-g03+g06*2g041g055_v#!:%6:p06p05+p04g05g06:g04<p*54+292<
->10g:1\g3+:70p110gv >:5- #v_550g:01-\2*40g+1-30g
/\110:\-g03:\1:g055 _v#!-4:<vp01:-1g01-g03-1\-
^1<v07+1:g07< p08p < >:1-#v_550g:01-\40g+60g+1-30g-50g>v
 _0>p80gp:5-|v1\+66\:p\0\9:$<:p02:+1g02-g03+g06-\g04\1:<
0v|-g00:+1$$<>\p907^>p:!7v>3-#v_550g:30g+:30p1\0\-
1>10g+::0\g3-:70p\0^^07<v<>50#<g::30g+:30p-1-01-\
v >\$0gg> :1+10gg1- #v_^>0g10gg*+\:!2*-70g2+10gv>:#->#,"_"$#1_:1#<p
+1+g03$_^#`gg011+3:+3<g07\+*2+*`0:-\gg01+5g07:g<>1#,-#*:#8>#4_$#:^#
>55+,p30g40p10gg10g1>#v_
#v:#p0$#8_:$#<g!#@_0^ >
 >>:180gg`>>#|_:2+80gg:!v
3+^g\0p08:<vgg08+2::+3<$_100p1-v>g,\80gg+\80gp:2+90g:!01p\80gp
!#^_80g:1+^>\180gg`+!#^_20g80g`
5*g10!g09p04-1-\0\+g04:gg08:p09<^3`0:gg08+1:::$$_1#!-#\\:,#\<g

Try it online!

As is often the case with Befunge, the trick is coming up with an algorithm that allows us to render the pattern from top to bottom, since it's just not feasible to render it into memory first with the limited space available.

The way this works is by first building up a simple data structure representing the edges needed to draw the spiral. The second stage then parses that structure from top to bottom, rendering the edge fragments required for each line of output.

Using this technique, we can support up to n=15 in the reference implementation before we start having overflow issue in the 8-bit memory cells. Interpreters with a larger cell size should be able to support up to n=25 before running out of the memory.


Distance between two points on the Moon Given latitude/longitude of two points on the Moon (lat1, lon1) and (lat2, lon2), compute the distance between the two points in kilometers, by using any formula that gives the same result as the haversine formula.
Input

Four integer values lat1, lon1, lat2, lon2 in degree (angle) or
four decimal values ϕ1, λ1, ϕ2, λ2 in radians.

Output
Distance in kilometers between the two points (decimal with any precision or rounded integer).
Haversine formula

where

r is the radius of the sphere (assume that the Moon's radius is 1737 km),
ϕ1 latitude of point 1 in radians
ϕ2 latitude of point 2 in radians
λ1 longitude of point 1 in radians
λ2 longitude of point 2 in radians
d is the circular distance between the two points

(source: https://en.wikipedia.org/wiki/Haversine_formula)
Other possible formulas

d = r * acos(sin ϕ1 sin ϕ2 + cos ϕ1 cos ϕ2 cos(λ2 - λ1)) @miles'  formula.
d = r * acos(cos(ϕ1 - ϕ2) + cos ϕ1 cos ϕ2 (cos(λ2 - λ1) - 1)) @Neil's  formula.

Example where inputs are degrees and output as rounded integer
42, 9, 50, 2  --> 284
50, 2, 42, 9  --> 284
4, -2, -2, 1  --> 203
77, 8, 77, 8  --> 0
10, 2, 88, 9  --> 2365

Rules

The input and output can be given in any convenient format.
Specify in the answer whether the inputs are in degrees or radians.
No need to handle invalid latitude/longitude values
Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
If possible, please include a link to an online testing environment so other people can try out your code!
Standard loopholes are forbidden.
This is code-golf so all usual golfing rules apply, and the shortest code (in bytes) wins.

Wolfram Language (Mathematica), 48 bytes

ArcCos[Sin@#*Sin@#3+Cos[#2-#4]Cos@#*Cos@#3]1737&

Try it online!

Uses the formula d = r * acos( sin ϕ1 sin ϕ2 + cos ϕ1 cos ϕ2 cos(λ2 - λ1) ) where r = 1737


Write a ~ATH Interpreter The popular webcomic Homestuck makes use of a programming language called ~ATH to destroy universes. While this code golf challenge is not to write a program to annihilate our existence, we will be destroying some more tame (albeit less interesting) entities: variables.

~ATH (pronounced "til death," notice how ~ath is "tilde ath") works by creating a variable called THIS, executing a command with EXECUTE, and finishing the program with THIS.DIE(). A wiki page for the language's use in Homestuck can be found here. The goal of this challenge will be to create a ~ATH interpreter.

For the sake of the challenge, I'm going to create some details of ~ATH that don't really exist but make it (somewhat) useful.

The language will only work with integers, which are declared with import <variable name>;. The variable will automatically be set to a value of 0. Only one variable at a time can be imported.
A variable x can be copied by writing bifurcate x[y,z];, which will delete the variable x and replace it with identical variables y and z. Note that it cannot create a variable with the same name as the one deleted. Essentially, a variable is renamed, then a copy of the variable with a different name is created. This seems like a stupid feature, but stupidity is very deeply ingrained in Homestuck.
The syntax for writing a program that executes code on x is ~ATH(x){EXECUTE(<code>)}. If you want to execute code on two variables simultaneously, the code becomes nested, like this: ~ATH(x){~ATH(y){EXECUTE(<code>)}}. All commands in <code> will be executed on both x and y.
Now let's move onto commands. + increments relevant variable(s) by 1 and - decrements them by 1. And... that's it.
The final feature of ~ATH is that it kills whatever it works with. Variables are printed in the format <name>=<value> (followed by a newline) at the command [<name>].DIE();. Afterwards, the program prints the word DIE <name> and a newline a number of times equal to the absolute value of the value of the variable. When variables are killed simultaneously with [<name1>,<name2>].DIE(); (you can have as many variables killed as you want, so long as they exist), the DIE() command is executed on the variables sequentially.

Example programs

Program 1:

import sollux;                  //calls variable "sollux"
import eridan;                  //calls variable "eridan"
~ATH(sollux){EXECUTE(--)}       //sets the value of "sollux" to -2
~ATH(eridan){EXECUTE(+++++)}    //sets the value of "eridan" to 5
[sollux].DIE();                 //kills "sollux", prints "DIE sollux" twice
~ATH(eridan){EXECUTE(+)}        //sets the value of "eridan" to 6
[eridan].DIE();                 //kills "eridan", prints "DIE eridan" 6 times

Output:

sollux=-2
DIE sollux
DIE sollux
eridan=6
DIE eridan
DIE eridan
DIE eridan
DIE eridan
DIE eridan
DIE eridan

Program 2:

import THIS;                    //calls variable "THIS"
~ATH(THIS){EXECUTE(++++)}       //sets the value of "THIS" to 4
bifurcate THIS[THIS1,THIS2];    //deletes "THIS", creates variables "THIS1" and "THIS2" both equal to 4
~ATH(THIS1){EXECUTE(++)}        //sets the value of "THIS1" to 6
[THIS1,THIS2].DIE();            //kills "THIS1" and "THIS2", prints "DIE THIS1" 6 times then "DIE THIS2" 4 times

import THAT;                                         //calls variable "THAT"
bifurcate THAT[THESE,THOSE];                         //deletes "THAT", creates variables "THESE" and "THOSE"
~ATH(THESE){~ATH(THOSE){EXECUTE(+++)}EXECUTE(++)}    //sets the value of "THESE" and "THOSE" to 3, then sets the value of "THESE" to 5
[THESE,THOSE].DIE();                                 //kills "THESE" and "THOSE", prints "DIE THESE" 5 times then "DIE THOSE" 3 times

Output:

THIS1=6
DIE THIS1
DIE THIS1
DIE THIS1
DIE THIS1
DIE THIS1
DIE THIS1
THIS2=4
DIE THIS2
DIE THIS2
DIE THIS2
DIE THIS2
THESE=5
DIE THESE
DIE THESE
DIE THESE
DIE THESE
DIE THESE
THOSE=3
DIE THOSE
DIE THOSE
DIE THOSE

This is code golf, so standard rules apply. Shortest code in bytes wins.

Python 2.7.6, 1244 1308 1265 1253 1073 1072 1071 1065 1064 1063 bytes
Alright, I'm not breaking any records here but this is about the smallest Python will go insofar as reading input all at once from a file rather than sequentially over time. I'll try to one-up this later in a different language (and an interpreter, not just a parser). Until then, enjoy the disgustingly horrid monstrosity.
Note: opens a file called t in the working directory. To make it open a command line argument, add import sys to the top of the file and change 't' to sys.argv[1]

n=s='\n';m=',';X='[';Y=']';c=';';A='~ATH';D='import';b,g,k=[],[],[];r=range;l=len;f=open('t','r').read().split(n)
def d(j,u):
 p=[]
 for e in j:
  if e!=u:p.append(e)
 return''.join(p)
for h in r(l(f)):f[h]=f[h].split('//')[0].split()
while[]in f:f.remove([])
for h in r(l(f)):
 i=f[h]
 if i[0]==D and l(i)==2and i[1][l(i[1])-1]==c and d(i[1],c)not in b:g.append(0);b.append(d(i[1],c))
 elif i[0].startswith(A):
  i=i[0].split('){')
  for e in r(l(i)):
   if i[e].startswith(A):
    i[e]=i[e].split('(')
    if i[0][1]in b:g[b.index(i[0][1])]+=(i[1].count('+')-i[1].count('-'))
 elif i[0].startswith('bifurcate')and l(i)==2and i[1][l(i[1])-1]==c:
  i=i[1].split(X)
  if i[0] in b:
   z=d(d(i[1],c),Y).split(m)
   for e in r(l(z)):g.append(g[b.index(i[0])]);b.append(z[e])
   g.remove(g[b.index(i[0])]);b.remove(i[0])
 elif i[0].startswith(X)and i[0].endswith('.DIE();')and l(i)==1:
  z=d(i[0],X).split(Y)[0].split(m)
  for e in r(l(z)):
   k.append((z[e],g[b.index(z[e])]))
for e in r(l(k)):k0=k[e][0];k1=k[e][1];s+=k0+'='+str(k1)+n+('DIE '+k0+n)*abs(k1)
print s


Evening Commute Solver I recently moved to an apartment overlooking the inner ring-road of town, and every day, a beautiful scene unfolds. The traffic lights are apparently so confusing (mostly because the Dutch are used to complex intersections, and this one is too simple for them to wrap their heads around), that the intersection invariably winds up as something that must have been the inspiration for a certain game which I shall call Evening Commute for copyright reasons which I will undoubtedly have circumvented by my clever renaming...

Please help my fellow confused Dutchmen, and make sure the red car makes it through the maze during Rush Hour!

Explanation of the game

The goal is to have the red car go to the right of a 6x6 grid (all the way off to the right), while only going straight forward or backward in the lengthwise direction of the car (which is 2 grid points long). For simplicity, the red car is always on the 3rd row.

Of course, there are obstacles: other cars and trucks, with length two. They can be placed horizontally and vertically, and can only move in their lengthwise direction. They cannot pass through other cars. All cars move at 1 grid point per move. The game is won when the red car can move off the grid at the right side of the board.

Explanation of the challenge

Input: a valid game board, which is a 6x6 string with dots . for empty tiles, R's for the red (target) car on row 3, hex numbers 0 through B for cars (length 2), and hex numbers C through F for trucks (length 3). You need not worry about invalid boards; we are dealing with a carnage-free intersection.

Example input:

......
11..22
RRC...
..C..3
..C..3
..66..

As can be seen, numbers can be skipped; furthermore, there may be only trucks or only cars.

Output: a sequence of moves. Each move is identified as XY, with X the identifier of the vehicle, and Y the move, which is one of v^<>, or down, up, left and right respectively for those not familiar with a certain programming language. The move Rx means 'move the red car off the board' and will always indicate the end of the sequence (and only appear at the end, of course!). Since the output is fairly unambigious, any easily human readable sequence of moves will do (newlines, leading spaces are allowed; even a single undelimited string will do; however, you are not allowed to use underhanded tricks on the output). A solution to above problem may be, for example, 6<6<CvRx.

In- and output is, if I made the challenge correctly, case-independent, and newlines can be assumed to be convenient to your language (no need for \r\n hell)

Scoring

The number of bytes (code-golf-style) plus the sum of the number of moves it takes you for each of the following test cases (I tried to calibrate the minimum number of moves to be competitive). Your program should be fully capable of solving any other test case I may throw at it, and hard-coding test cases will give you a penalty of 2^64, but if that's favourable, you might want to rethink your strategy.

11...C
D..E.C
DRRE.C
D..E..
2...33
2.FFF.

112.33
442..C
DRR..C
DEEE.C
D..566
77.588

C.1DDD
C.12..
CRR2..
3344.E
.....E
5566.E

C11.2.
C34.2D
C34RRD
EEE5.D
..6577
88699.

...next code-golf, somebody should make me a Rush Hour image recognition system.

Javascript (ES6), 1216 1206 1131 + 180 => 1311 bytes

a=>{a=a.replace(/\s/g,'');b=[];d={};e=[];f=[];g=[];h='.';[].concat.apply([],a.split('.').filter(k=>k).map(k=>k.match(/([^.])(\1*)/g)||k)).forEach(k=>k.length>1?(b.push(k[0]),(k.length<3?g:f).push(k[0])):(!e.includes(k)&&e.push(k),d[k]=d[k]?d[k]+1:1));Object.keys(d).forEach(k=>(d[k]<3?g:f).push(k));j=(l,m,n)=>l.substr(0,m)+n+l.substr(m+n.length);o=(p,q)=>~q.indexOf(p);I=(s,r,c)=>s.charAt(r*6+c)||'@';t=(s,r,c,F,G)=>{k=0;while(I(s,r+k*F,c+k*G)==h)k++;return k};u={};w=[];x={};x=(y,z,A)=>u[y]===[][0]?(u[y]=z,x[y]=A,w.push(y)):0;C=B=>{var z=u[B];return (!z?'':C(z))+x[B]};D=(B,r,c,q,E,F,G,n)=>{r+=E*F;c+=E*G;H=I(B,r,c);if(!o(H,q))return;L=o(H,f)?3:o(H,g)?2:[][0];J=B;for(i=0;i<n;i++){r-=F;c-=G;J=j(J,r*6+c,H);J=j(J,(r+L*F)*6+c+L*G,h);x(J,B,H+(!~F?'v':F?'^':!~G?'>':'<'));B=J}};x(a,null,'');K=!1;while(w.length) {B=w.splice(0,1)[0];if(I(B,2,5)=='R'&&!K){K=!0;break}for(r=0;r<6;r++){for(c=0;c<6;c++){if(I(B,r,c)!=h)continue;nU=t(B,r,c,-1,0);nD=t(B,r,c,1,0);nL=t(B,r,c,0,-1);nR=t(B,r,c,0,1);D(B,r,c,e,nU,-1,0,nU+nD-1);D(B,r,c,e,nD,1,0,nU+nD-1);D(B,r,c,b,nL,0,-1,nL+nR-1);D(B,r,c,b,nR,0,1,nL+nR-1)}}}return C(B).replace(/(R.)+$/,'Rx')}

I followed the algorithm and example from here. Rewriting the algorithm and input in the example to output moves cost a lot of bytes. I'm planning on rewriting the answer using an algorithm specifically designed for outputting moves instead of outputting board states.

Ungolfed:

func = inp => {
    inp = inp.replace(/\s/g, '');

    HORZS = [];
    tVERTS = {};
    VERTS = [];
    LONGS = [];
    SHORTS = [];
    EMPTY = '.';

    [].concat.apply([], inp.split('.').filter(k => k).map(k => k.match(/([^.])(\1*)/g) || k)).forEach(k =>
        k.length > 1 ? (
            HORZS.push(k[0]),
            (k.length < 3 ? SHORTS : LONGS).push(k[0])
        ) : (
            !VERTS.includes(k) && VERTS.push(k),
            tVERTS[k] = tVERTS[k] ? tVERTS[k] + 1 : 1
        )
    );
    Object.keys(tVERTS).forEach(k => (tVERTS[k] < 3 ? SHORTS : LONGS).push(k));

    setCharAt = (str, index, character) => str.substr(0, index) + character + str.substr(index + character.length);

    isType = (entity, type) => ~type.indexOf(entity);

    at = (state, r, c) => state.charAt(r * 6 + c) || '@';

    countSpaces = (state, r, c, dr, dc) => {
        k = 0;
        while (at(state, r + k * dr, c + k * dc) == EMPTY) k++;
        return k;
    };

    pred = {};
    queue = [];
    moves = {};

    propose = (next, prev, move) => pred[next] === [][0] ? (pred[next] = prev, moves[next] = move, queue.push(next)) : 0;

    trace = current => {
        var prev = pred[current];
        return (!prev ? '' : trace(prev)) + moves[current];
    };

    slide = (current, r, c, type, distance, dr, dc, n) => {
        r += distance * dr;
        c += distance * dc;
        car = at(current, r, c);
        if (!isType(car, type)) return;
        L = isType(car, LONGS) ? 3 : isType(car, SHORTS) ? 2 : [][0];
        sb = current;
        for (i = 0; i < n; i++) {
            r -= dr;
            c -= dc;
            sb = setCharAt(sb, r * 6 + c, car);
            sb = setCharAt(sb, (r + L * dr) * 6 + c + L * dc, EMPTY);
            propose(sb, current, car + (!~dr ? 'v' : dr ? '^' : !~dc ? '>' : '<'));
            current = sb;
        }
    };

    propose(inp, null, '');
    solved = !1;
    while (queue.length) {
        current = queue.splice(0, 1)[0];
        if (at(current, 2, 5) == 'R' && !solved) {
            solved = !0;
            break;
        }

        for (r = 0; r < 6; r++) {
            for (c = 0; c < 6; c++) {
                if (at(current, r, c) != EMPTY) continue;
                nU = countSpaces(current, r, c, -1, 0);
                nD = countSpaces(current, r, c, 1,  0);
                nL = countSpaces(current, r, c, 0, -1);
                nR = countSpaces(current, r, c, 0,  1);
                slide(current, r, c, VERTS, nU, -1, 0, nU + nD - 1);
                slide(current, r, c, VERTS, nD, 1,  0, nU + nD - 1);
                slide(current, r, c, HORZS, nL, 0, -1, nL + nR - 1);
                slide(current, r, c, HORZS, nR, 0,  1, nL + nR - 1);
            }
        }
    }

    return trace(current).replace(/(R.)+$/, 'Rx');
}

Example usage and output:

func(`......
11..22
RRC...
..C..3
..C..3
..66..`); // ==> "6<6<CvRx"

func(`11...C
D..E.C
DRRE.C
D..E..
2...33
2.FFF.`); // ==> "1>D^2^Cv3<3<3<CvCvEvF<F<EvRx"

func(`112.33
442..C
DRR..C
DEEE.C
D..566
77.588`); // ==> "3<C^R>R>2vE>E>2v2v2v1>4>D^D^R<R<E<E<E<5^5^5^Cv6<Cv8<Cv3>5^Rx"

func(`C.1DDD
C.12..
CRR2..
3344.E
.....E
5566.E`); // ==> "4>3>CvCvD>2^Rx"

func(`C11.2.
C34.2D
C34RRD
EEE5.D
..6577
88699.`); // ==> "D^9>5vE>E>E>E>Cv1<4^R<3v3vR<5^5^5^5^R>R>E<E<Dv7<Dv9<DvRx"


X Steps Forward, 1 Step Back Here the first 100 numbers of an easy sequence:
0,1,0,2,1,4,3,7,6,11,10,16,15,22,21,29,28,37,36,46,45,56,55,67,66,79,78,92,91,106,105,121,120,137,136,154,153,172,171,191,190,211,210,232,231,254,253,277,276,301,300,326,325,352,351,379,378,407,406,436,435,466,465,497,496,529,528,562,561,596,595,631,630,667,666,704,703,742,741,781,780,821,820,862,861,904,903,947,946,991,990,1036,1035,1082,1081,1129,1128,1177,1176,1226

How does this sequence work?
n: 0 1     2           3     4     5     6     7     8      9       10      11      12

   0,      1-1=0,      2-1=1,      4-1=3,      7-1=6,       11-1=10,        16-1=15,
     0+1=1,      0+2=2,      1+3=4,      3+4=7,      6+5=11,        10+6=16,        15+7=22

a(0) = 0
For every odd n (0-indexed), it's a(n-1) + X (where X=1 and increases by 1 every time it's accessed)
For every even n (0-indexed), it's a(n-1) - 1

Challenge:
One of:

Given an input integer n, output the n'th number in the sequence.
Given an input integer n, output the first n numbers of the sequence.
Output the sequence indefinitely without taking an input (or taking an empty unused input).

Challenge rules:

Input n can be both 0- or 1-indexed.
If you output (part of) the sequence, you can use a list/array, print to STDOUT with any delimiter (space, comma, newline, etc.). Your call.
Please state which of the three options you've used in your answer.
You'll have to support at least the first 10,000 numbers (10,000th number is 12,497,501).

General rules:

This is code-golf, so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
Standard rules apply for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
Default Loopholes are forbidden.
If possible, please add a link with a test for your code.
Also, please add an explanation if possible.

Test cases:
Pastebin with the first 10,001 numbers in the sequence. Feel free to pick any you'd like.
Some higher numbers:
n (0-indexed)    Output:

68,690           589,772,340
100,000          1,249,975,000
162,207          3,288,888,857
453,271          25,681,824,931
888,888          98,765,012,346
1,000,000        124,999,750,000

Python 2, 32 28 25 bytes

lambda n:(~-n|1)**2/8+n%2

Try it online!

Returns the n-th number (0-indexed)


How to weight loss easily? In this question, we will only focus on losing weight by doing exercise, although there are still many ways to lose weight.

Different sports burn different amount of calories.

For example, playing billiards for an hour can burn 102 calories[1], while playing basketball for 15 minutes can already burn 119 calories [1], which make weight loss by playing basketball easier, at least from some perspectives.

The exact way to weigh the easiness is by dividing the amount of calories burnt by the time needed, which gives us the easiness index (EI).

For example, fencing for 15 minutes can burn 85 calories, which gets an EI of 85/15.

You will be given a list in this format:

[["fencing",15,85],["billiards",60,102],["basketball",15,119]]

or other format that you want.

Then, you will output the sports which have the highest EI.

TL;DR

Given a list of tuples [name,value1,value2] output the name where value2/value1 is the highest.

Constraints

You may not produce any real number that is not integer in the process.
You may not use any fraction built-in.

Specifications (Specs)

If there is more than one name that satisfy the result, you may output any non-empty subset of them or any element of them.
The name will match the regex /^[a-z]+$/, meaning that it will only consist of lowercase Latin standard alphabet.
The list will not be empty.

Testcase

Input:

[["fencing",15,85],["billiards",60,102],["basketball",15,119]]

Output:

basketball

References

http://calorielab.com/burned/

Python 2, 51 bytes

lambda l:max((10**len(`l`)*a/b,s)for s,b,a in l)[1]

Does the obvious thing of finding the entry with the biggest ratio, but sidesteps the prohibition against floats by first multiplying the numerator by a huge input-dependent power of 10 before floor-dividing.
I'll prove this coefficient is big enough to make floor-division act the same difference as non-floor division.
Claim: If a1/b1 > a2/b2, then floor(Na1/b1) > floor(Na2/b2) for any N≥b1b2.
Proof: Note that a1/b1 - a2/b2 is a multiple of 1/b1b2, so a1/b1 - a2/b2 > 0 implies that

a1/b1 - a2/b2
≥ 1/b1b2

Then, multiplying both sides by N,

Na1/b1 - Na2/b2
≥ N/b1b2 ≥ 1

So, since Na1/b1 and Na2/b2 differ by at least 1, their respective floors are distinct. ∎
Now, note that the product b1b2 has digit length at most their total digit length, which is less than the string length of the input. Since the input is in base 10, its suffices to use 10 to the power of its length N=10**len(`l`) to produce a number with more digits than it, guaranteeing the condition.


Sharing Inherited Land You and your brother have inherited a rectanglar block of land. This block of land's corners are read in from stdio as TLX,TLY,TRX,TRY,BLX,BLY,BRX,BRY (all decimal numbers without units, T=Top, L=Left, B=Bottom, R=Right)

Unfortunately the city has seen fit to appropriate a small rectanglar section from inside your you newly aquired land. This appropriated land can be at any angle and in any position on your land. Its corners are read in from stdio as TLX,TLY,TRX,TRY,BLX,BLY,BRX,BRY (all decimal numbers without units).

You need to split this land evenly with your brother by building a fence. The fencing contractors can only build a single straight line fence. You need to supply them with the start and end co-ordinates which sit along the parameter of your property. These are written to stdio as SX,SY,EX,EY (all decimal numbers without units, S=Start, E=End)

The city has graciously agreed to allowed you to freely build the fence across their bit of appropriated property.

Provide a solution which can accept the 2 rectangle co-ordinates and return a correct solution which divides the property area equally for you and your brother.

visualized samples of potential input (white = your land, grey = city land):

{I'll insert the credit here after people have answered}

C

#include <stdio.h>
#include <stdlib.h>
#include <memory.h>

enum mode
{
    CORD_MODE_CONST = 1,
    CORD_MODE_SLOPE = 2,
};
typedef struct point {
    float x;
    float y;
} CORD;

typedef struct l {
    int mode;
    float m;
    float b;
}LINE;

typedef struct r {

    CORD topL;
    CORD botL;

    CORD topR;
    CORD botR;

    CORD midRight;
    CORD midBot;
    CORD midLeft;
    CORD midTop;

    CORD center;
    LINE vertLine;
    LINE horLine;

} RECTANGLE;

void findBorderIntersection(RECTANGLE * pR, LINE * p);
int isPointContained(RECTANGLE * pR, CORD * pC1);
float dotProduct(float y1, float y2, float x1, float x2);
void findCenterOfRetangle(RECTANGLE * pR);
void findIntersection(LINE * pL1, LINE * pL2, CORD *pInt);
void findMidPointOfLine(CORD * pC1, CORD * pC2, CORD * pMid);
void getLine(CORD * pC1, CORD * pC2, LINE * pLine );

void dumpCord(char * pS, CORD * pC)
{
    printf(" %s y:%f x:%f\n",pS,pC->y,pC->x);
}

int main()
{
    RECTANGLE yourLand;
    RECTANGLE cityLand;
    LINE  lineThroughCenter;

    memset(&yourLand,0x0, sizeof(RECTANGLE));
    memset(&cityLand,0x0, sizeof(RECTANGLE));

    scanf("%f%f%f%f%f%f%f%f",&(yourLand.topL.x),
                             &(yourLand.topL.y),
                             &(yourLand.topR.x),
                             &(yourLand.topR.y),
                             &(yourLand.botL.x),
                             &(yourLand.botL.y),
                             &(yourLand.botR.x),
                             &(yourLand.botR.y));

    scanf("%f%f%f%f%f%f%f%f",&(cityLand.topL.x),
                             &(cityLand.topL.y),
                             &(cityLand.topR.x),
                             &(cityLand.topR.y),
                             &(cityLand.botL.x),
                             &(cityLand.botL.y),
                             &(cityLand.botR.x),
                             &(cityLand.botR.y));

    /* Find center of your land */
    findCenterOfRetangle(&yourLand);

    /* Find center of city land */
    findCenterOfRetangle(&cityLand);

    /* Handle the case where the centers are right on top of each other */
    if((yourLand.center.x == cityLand.center.x) &&
     (yourLand.center.y == cityLand.center.y))
    {
        /* Find the line through center and the top border */
        getLine(&(yourLand.midTop),&(cityLand.center),&lineThroughCenter);
    }
    else
    {
        /* Find the line through center of both lands */
        getLine(&(yourLand.center),&(cityLand.center),&lineThroughCenter);
    }

    /* Find the border cords */
    findBorderIntersection(&(yourLand),&lineThroughCenter);

    return 0;
}
void findBorderIntersection(RECTANGLE * pR, LINE * p)
{
    LINE line;
    CORD c1;
    CORD c2;

    int bTop = 0;

    getLine(&(pR->topL), &(pR->topR),&line);

    /* Figure out if the the line goes through the top/bottom or right/left */
    if( p->m != line.m)
    {
          findIntersection(p,&line, &c1);
          bTop = isPointContained(pR,&c1);
    }

    if(bTop)
    {
        getLine(&(pR->botL), &(pR->botR),&line);
        findIntersection(p,&line, &c2);
    }
    else
    {
        getLine(&(pR->topL), &(pR->botL),&line);
        findIntersection(p,&line, &c1);

        getLine(&(pR->topR), &(pR->botR),&line);
        findIntersection(p,&line, &c2);
    }

    dumpCord("Border Cord1:",&c1);
    dumpCord("Border Cord2:",&c2);

}

int isPointContained(RECTANGLE * pR, CORD * pC1)
{
    float pointProduct1;
    float vectorProduct1;
    float pointProduct2;
    float vectorProduct2;

    vectorProduct1 = dotProduct((pR->topL.y - pR->botL.y),
                               (pR->topL.y - pR->botL.y),
                               (pR->topL.x - pR->botL.x),
                               (pR->topL.x - pR->botL.x));

    pointProduct1 = dotProduct((pC1->y - pR->botL.y),
                              (pR->topL.y - pR->botL.y),
                              (pC1->x - pR->botL.x),
                              (pR->topL.x - pR->botL.x));

    vectorProduct2 = dotProduct((pR->botR.y - pR->botL.y),
                               (pR->botR.y - pR->botL.y),
                               (pR->botR.x - pR->botL.x),
                               (pR->botR.x - pR->botL.x));

    pointProduct2 = dotProduct((pC1->y - pR->botL.y),
                              (pR->botR.y - pR->botL.y),
                              (pC1->x - pR->botL.x),
                              (pR->botR.x - pR->botL.x));

    if( (pointProduct1 <= vectorProduct1) &&
        (pointProduct1 >= 0) &&
        (pointProduct2 <= vectorProduct2) &&
        (pointProduct2 >= 0))
    {
        return 1;
    }

    return 0;

}
float dotProduct(float y1, float y2, float x1, float x2)
{
    return y1*y2 + x1*x2;
}

void findCenterOfRetangle(RECTANGLE * pR)
{
     /* Find the mid point of the left side */
    findMidPointOfLine(&(pR->topL), &(pR->botL), &(pR->midLeft));

     /* Find the mid point of the right side */
    findMidPointOfLine(&(pR->topR), &(pR->botR), &(pR->midRight));

    /* Get the line */
    getLine(&(pR->midLeft), &(pR->midRight), &(pR->horLine));

     /* Find the mid point of the top side */
    findMidPointOfLine(&(pR->topL), &(pR->topR), &(pR->midTop));

     /* Find the mid point of the bottom side */
    findMidPointOfLine(&(pR->botL), &(pR->botR), &(pR->midBot));

    /* Get the line */
    getLine(&(pR->midTop), &(pR->midBot), &(pR->vertLine));

    /* Find the center of the first rectangle */
    findIntersection(&(pR->horLine), &(pR->vertLine),&(pR->center));

}
void findIntersection(LINE * pL1, LINE * pL2, CORD *pInt)
{

    if(pL1->mode == CORD_MODE_CONST)
    {
        pInt->x = pL1->m;
        pInt->y = ((pL2->m * pInt->x) + pL2->b);
    }
    else if(pL2->mode == CORD_MODE_CONST)
    {
        pInt->x = pL2->m;
        pInt->y = ((pL1->m * pInt->x) + pL1->b);
    }
    else
    {
        pInt->x = (pL2->b - pL1->b) / (pL1->m - pL2->m);
        pInt->y = ((pL2->m * pInt->x) + pL2->b);
    }
}

void findMidPointOfLine(CORD * pC1, CORD * pC2, CORD * pMid)
{
    pMid->y = (pC1->y + pC2->y) / 2;
    pMid->x = (pC2->x + pC1->x) / 2;
}
void getLine(CORD * pC1, CORD * pC2, LINE * pLine )
{

    /* Find slope */
    if((pC1->x - pC2->x) == 0)
    {
        pLine->mode = CORD_MODE_CONST;
        pLine->m = pC1->x;
        pLine->b = 0;
    }
    else
    {
        pLine->mode = CORD_MODE_SLOPE;
        pLine->m = ((pC1->y - pC2->y) / (pC1->x - pC2->x));

        /* Find y inter. */
        pLine->b = pC1->y - (pLine->m * pC1->x);
    }
}


Find the nth Fibohexaprime The challenge this time is to find the nth Fibohexaprime. The definition of a Fibohexaprime is as following:

We first observe a list with Fibonacci numbers:

N  | Fibonacci number
1  | 1
2  | 1
3  | 2
4  | 3
5  | 5
6  | 8
7  | 13
8  | 21
9  | 34
10 | 55
11 | 89
12 | 144
13 | 233
14 | 377
15 | 610
16 | 987
17 | 1597

After that, we convert the numbers to hexadecimal:

N  | Fib  | Hex
1  | 1    | 1
2  | 1    | 1
3  | 2    | 2
4  | 3    | 3
5  | 5    | 5
6  | 8    | 8
7  | 13   | D
8  | 21   | 15
9  | 34   | 22
10 | 55   | 37
11 | 89   | 59
12 | 144  | 90
13 | 233  | E9
14 | 377  | 179
15 | 610  | 262
16 | 987  | 3DB
17 | 1597 | 63D

From the hexadecimal numbers, we filter out the letters. All we are left with are numbers. We need to check if these numbers are prime:

hex |  filtered |  is prime? |  N =
1   >  1        >  false
1   >  1        >  false
2   >  2        >  true         1
3   >  3        >  true         2
5   >  5        >  true         3
8   >  8        >  false
D   >  0        >  false
15  >  15       >  false
22  >  22       >  false
37  >  37       >  true         4
59  >  59       >  true         5
90  >  90       >  false
E9  >  9        >  false
179 >  179      >  true         6
262 >  262      >  false
3DB >  3        >  true         7
63D >  63       >  false

If the filtered number is a prime, we call this a Fibohexaprime. You can see that for N = 7, the related fibonacci number is 987.

The task is simple, when given an input using STDIN or an acceptable alternative, write a program or a function which outputs the nth Fibohexaprime using STDOUT or an acceptable alternative.

Test cases

Input - Output
1     - 2
2     - 3
3     - 5
4     - 55
5     - 89
6     - 377
7     - 987
8     - 28657
9     - 75025
10    - 121393
11    - 317811
12    - 5702887
13    - 9227465
14    - 39088169
15    - 102334155
16    - 32951280099
17    - 4052739537881
18    - 806515533049393
19    - 7540113804746346429

The rules:

Given an integer between 1 and 19 (the values above 20 exceed the max value for a 64-bit signed integer), output the corresponding value.
You may write a function or a program.
This is code-golf, so the submission with the least amount of bytes wins!

MATL, 28 bytes

This uses MATL version 1.0.0, which was published in Esolangs on December 12, earlier than this challenge.

1Hi:"`tb+t16YAt58<)YtZp~]]1$

Example

>> matl 1Hi:"`tb+t16YAt58<)YtZp~]]1$
> 10
121393

Explanation

The code is similar to that in Martin Büttner's answer.

1           % number literal
H           % paste from clipboard H. Initial contents: 2
i:          % vector of equally spaced values from 1 to input value
"           % for
  `         % do...while
    t       % duplicate
    b       % bubble up element in stack
    +       % addition
    t       % duplicate
    16YA    % convert integer to string representation in base 16
    t       % duplicate
    58      % number literal: first ASCII code after '9'
    <       % is less than? (element-wise)
    )       % reference () indexing with logical index from previous comparison
    Yt      % convert string to number
    Zp      % true for prime numbers
    ~       % logical 'not'
  ]         % end
]           % end
1$          % input specification for final implicit display function


Classify State's Senators United States senators are sorted into three classes, based on what year their six-year term starts. Since each state has two senators, each state has a senator in two of the three classes.
Given a full state name and a class number (1, 2, or 3), output truthy if that state has a senator of that class, and falsey if that state does not have a senator of that class.
States with Class 1 senators:

Arizona, California, Connecticut, Delaware, Florida, Hawaii, Indiana, Maine, Maryland, Massachusetts, Michigan, Minnesota, Mississippi, Missouri, Montana, Nebraska, Nevada, New Jersey, New Mexico, New York, North Dakota, Ohio, Pennsylvania, Rhode Island, Tennessee, Texas, Utah, Vermont, Virginia, Washington, West Virginia, Wisconsin, Wyoming

States with Class 2 senators:

Alabama, Alaska, Arkansas, Colorado, Delaware, Georgia, Idaho, Illinois, Iowa, Kansas, Kentucky, Louisiana, Maine, Massachusetts, Michigan, Minnesota, Mississippi, Montana, Nebraska, New Hampshire, New Jersey, New Mexico, North Carolina, Oklahoma, Oregon, Rhode Island, South Carolina, South Dakota, Tennessee, Texas, Virginia, West Virginia, Wyoming

States with Class 3 senators:

Alabama, Alaska, Arizona, Arkansas, California, Colorado, Connecticut, Florida, Georgia, Hawaii, Idaho, Illinois, Indiana, Iowa, Kansas, Kentucky, Louisiana, Maryland, Missouri, Nevada, New Hampshire, New York, North Carolina, North Dakota, Ohio, Oklahoma, Oregon, Pennsylvania, South Carolina, South Dakota, Utah, Vermont, Washington, Wisconsin

Test Cases
"Rhode Island", 1 -> true
"Rhode Island", 2 -> true
"Rhode Island", 3 -> false
"California", 1 -> true
"California", 2 -> false
"California", 3 -> true
"South Dakota", 1 -> false
"South Dakota", 2 -> true
"South Dakota", 3 -> true

Python 2, 67 63 bytes

lambda s,l:0x764d5443a33628366/3**(hash(s)%4560%1502%43)%3+1!=l

Try it online!

The states can be sorted into three disjoint categories, based on what class of senators they don't have. hash(s)%4560%1502%43 generates a number \$0 \le k \le 42 \$ without mixing up the categories. This number is then used to get a single base-3 digit out of 0x764d5443a33628366.