27
\$\begingroup\$

This question is inspired by, and is the inverse of this one.

Dennis (E), Doorknob (D), Martin (M) and Chris (C) have ordered a pizza. The rectangular pizza is divided into square pieces, each marked with their intended eater.

Write a program or function that given a rectangular pizza consisting of 0 or more of each letter determines whether:

  1. Each slice for each person is path-connected. This means that all letters that are the same should be directly adjacent to eachother (no diagonal connections).

  2. The number of slices per person is the same for all.

You must output a truthy/falsy value with an optional trailing newline that indicates whether or not the given pizza is fair.

Valid testcases:

DDDDDDDDDDDDMCCCCCCCCCCC
DEEEEEEEEEEDMMMMMMMCCCCC
DEEEEEEEEEEDMMMCCCCCCCCC
DEEEEEEEEEEDMMMMMMMMCCCC
DDDDDDDDDDDDMMMMMMMMMMMC
DEMC
DD
EE
MC
MC
EEDDMMMCCC
EEEDDDMMCC

Invalid testcases:

EDM
EDMCCMDE
DDDDDDDDDDDDMCCCCCCCCCCC
DEEEEEEEEEEDMMMMMMMCCCCC
DEEEEEEEEEEMDMMCCCCCCCCC
DEEEEEEEEEEDMMMMMMMMCCCC
DDDDDDDDDDDDMMMMMMMMMMMC
DDMMEECC
DMMEECCC

Shortest code in bytes wins.

\$\endgroup\$
  • \$\begingroup\$ 1. What forms of input are acceptable to a function? string with newlines? array with one string for each line? 2D array of characters? All of the above? 2. I understand that output is truthy for fair, falsy for unfair, or can they be reversed? \$\endgroup\$ – Level River St Aug 30 '15 at 14:41
  • 52
    \$\begingroup\$ Valid test cases: DDDDDDDDDDDDD <-- a fair pizza \$\endgroup\$ – Doorknob Aug 30 '15 at 14:57
  • \$\begingroup\$ @steveverrill For this challenge only a string with newlines is acceptable input. You must return truthy for fair, and falsy for unfair. \$\endgroup\$ – orlp Aug 30 '15 at 14:59
  • \$\begingroup\$ Beside newlines, only CDEM in input? \$\endgroup\$ – edc65 Aug 30 '15 at 15:15
  • \$\begingroup\$ @edc65 Correct. \$\endgroup\$ – orlp Aug 30 '15 at 15:15
5
\$\begingroup\$

Pyth, 53 bytes

!f-lJs.z*4lu&G{smfqT@JY@UJ+Ld[Z1_1Klh.z_K)G]xJT)"CDEM

Demonstration

This is essentially a flood fill for each letter, followed by a check that all of the resulting sets are of the appropriate size.

To flood-fill, it starts with the upper-left-most occurence of each letter, then generates all neighbors of locations found so far, filters for locations with the right letter, and repeats until the set stops changing.

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

Snails, 129

Prints 1 for a fair pizza and 0 for an unfair pizza.

&
={(t\Dt\Et\Ct\M),!(t.}{(o\D)+l^D,=~u{^D=(r^D,~},~|o\E`+l^E,=~u{^E=(r^E,~},~|o\C`+l^C,=~u{^C=(r^C,~},~|o\M`+l^M,=~u{^M=(r^M,~},~

Expanded version:

&
={ (t\Dt\Et\Ct\M), !(t.)}   {
(o\D)+ l^D,=~ u{^D=(r^D,~)}, ~ |
(o\E)+ l^E,=~ u{^E=(r^E,~)}, ~ |
(o\C)+ l^C,=~ u{^C=(r^C,~)}, ~ |
(o\M)+ l^M,=~ u{^M=(r^M,~)}, ~

& means that the pattern must match at all locations on the grid. The first line checks for an equal number of each of E, D, M, C. it uses the teleport instruction t, which is a great way to make programs with factorial complexity. If an input has unequally sized slices with several units for each of the 4 mods, the program will more or less hang forever. After that, there is a check for a contiguous path to the top-left instance of whichever letter the pattern started on.

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

CJam, 93

qN/_z,:W;s:A,,:B_{{{_B=_@-}g}%$}:F;{a+_Af=)#{F~B\@t:B}|;}:U;W>{_W-U}/{W%},{_(U}/BFe`0f=_1<4*=

Try it online

This is ridiculously long because CJam doesn't (yet) have built-in flood-fill or union-find. I implemented union-find in the program.

Explanation:

qN/_         read input, split into lines and duplicate
z,:W;        transpose, get length (original width) and store in W
s:A          convert to string (without newlines) and store in A
,,           make an array [0..n-1] (n = pizza size)
:B_          store in B (initial structure) and duplicate (will be used in 2 loops)
{…}:F;       define function F ("Find" for multiple indices and sort)
  {…}%       for each value (x)
    {…}g     do…while
      _B=    duplicate x and get B[x]
      _@-    leave a B[x] on the stack and calculate B[x] - x
              if non-zero, repeat the loop with B[x]
  $          sort the results
{…}:U;       define function U ("Union" for 2 indices)
  a+         make an array of the 2 indices
  _Af=       get the corresponding letters from A
  )#         check if the letters are different
  {…}|       if not, execute…
    F~       call F on the array and dump the 2 results on the stack
    B\@t     join the sets - B[bigger index] = smaller index
    :B       store back in B
  ;          pop the last value (either array if indices or B)
W>           remove the first row of indices
{…}/         for each index
  _W-        duplicate and subtract W ("go up")
  U          call U to join sets if they match
{W%},        remove the first column of indices
{…}/         for each index
  _(         duplicate and decrement ("go left")
  U          call U to join sets if they match
BF           call F on B, to get the final sets and sort
e`           RLE encoding
0f=          keep only the repetition counts
_1<4*=       check if it's the first value (if any) repeated 4 times
\$\endgroup\$
4
\$\begingroup\$

JavaScript (ES6), 153 166

Using template strings, there is a newline that is significant and counted

Test running the snippet in FireFox.

f=z=>![...'CDEM'].some(c=>((l=p=>z[p]==c&&[-1,1,w,-w].map(o=>l(p+o),z[p]='',++k))(z.indexOf(c),h=k,k=0),~h&&h-k),w=~z.search`
`,z=[...z],k=-1)&z.join``-1

// Ungolfed
U=z=>{
  w = ~z.search`\n`
  z = [...z]
  fill = p=>(
    c = z[p],
    z[p] = '',
    [-1,1,w,-w].forEach(o=>z[o+=p] == c && fill(o)),
    ++k
  )
  h = -1
  r = ['C','D','E','M'].every( c =>(
    k = 0,
    y = z.indexOf(c),
    y >= 0 && fill(y),
    v = h >= 0 ? h == k : true,
    h = k,
    v
  ))
  return r & 1-z.join``
}  

// Test
out=x=>O.innerHTML+=x+'\n';

// Valid test cases
valid=[`DDDDDDDDDDDDMCCCCCCCCCCC
DEEEEEEEEEEDMMMMMMMCCCCC
DEEEEEEEEEEDMMMCCCCCCCCC
DEEEEEEEEEEDMMMMMMMMCCCC
DDDDDDDDDDDDMMMMMMMMMMMC`,
`DEMC`,
`DD
EE
MC
MC`,
`EEDDMMMCCC
EEEDDDMMCC`];
out('Valid')
valid.forEach(t=>out(t+'\n'+f(t)+'\n'));
invalid=[`EDM`,
`EDMCCMDE`,
`DDDDDDDDDDDDDD`,         
`DDDDDDDDDDDDMCCCCCCCCCCC
DEEEEEEEEEEDMMMMMMMCCCCC
DEEEEEEEEEEMDMMCCCCCCCCC
DEEEEEEEEEEDMMMMMMMMCCCC
DDDDDDDDDDDDMMMMMMMMMMMC`,
`DDMMEECC
DMMEECCC`
];
out('Invalid')
invalid.forEach(t=>out(t+'\n'+f(t)+'\n'))
<pre id=O></pre>

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

Javascript ES6, 360

Checks for equal numbers of C, D, E, M, then flood fills and checks for any orphaned letters. Not a winner, but I had to try.

i=>(I=i.split`
`.map(e=>e.split``),c=(i[m='match'](/C/g)||[])[l='length'],a=(x,y,z)=>{if(I[x][y]!=z)return;I[x][y]=0;x>0&&a(x-1,y,z);x<I[l]-1&&a(x+1,y,z);y>0&&a(x,y-1,z);y<I[0][l]-1&&a(x,y+1,z)},![...'CDEM'].some(k=>{if((i[m](eval(`/${k}/g`))||[])[l]!=c)return 1;I.some((w,x)=>(g=-1<(y=w.indexOf(k)),g&&a(x,y,k),g));})&&!I.map(e=>e.join``).join``[m](/[CDEM]/))

Fiddle

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

JavaScript ES6, 328 318 316 269 178

l=>(d=[0,0,0,0],s=[...l.split`
`.join``].map(i=>(d["EDMC".search(i)]++,i)),!l||d.every(i=>i==d[0])&&(s.every((r,i)=>[1,-1,X=l.split`
`[0].length,-X].some(o=>s[o+i]==r))||d[0]<2))

Explanation:

l => (
  d = [0,0,0,0],          // array containing each letter count
  s = [...l.split`                    
`.join``]                 // removes newlines from input and converts it into array
  .map(i => (             // loops through the array
    d["EDMC".search(i)]++ // increases letter count
    ,i)),                 // returns unchanged value in order to preserve original array
  !l                      // input is empty
  || d.every(i=>i==d[0])  // each letter count is equal
  && (
    s.every((r, i) =>     // there is no orphaned letters 
      [1,-1,X=l.split`
`[0].length,-X]           // letters on respectively: right, left, bottom, top
      .some               // at least one of them
        (o=>s[o+i]==r))   // equals original letter
    || d[0] < 2           // count of each letter equals 1
  )
)
\$\endgroup\$
  • 1
    \$\begingroup\$ Interesting code (you beat mine!) Suggestion: use es6 arrow functions (as in my answer) to save a few bytes. Afaik you don't need to assign it to a variable, using a plain function declaration eg l=>{...} is fine. \$\endgroup\$ – DankMemes Aug 31 '15 at 0:48
  • 2
    \$\begingroup\$ Also remove the parentheses on k=(o)=> to save 2 more bytes. Single parameter arrow functions don't need parentheses. \$\endgroup\$ – DankMemes Aug 31 '15 at 0:56

Your Answer

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

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