McNuggets problem: Difference between revisions

m
→‎{{header|R}}: Syntax highlighting.
m (→‎{{header|Phix}}: added syntax colouring the hard way)
m (→‎{{header|R}}: Syntax highlighting.)
Line 1,677:
 
There are two natural approaches. The first is to generate all valid x, y, and z and then apply the function:
<lang rrsplus>allInputs<-expand.grid(x=0:(100%/%6),y=0:(100%/%9),z=0:(100%/%20))
mcNuggets<-do.call(function(x,y,z) 6*x + 9*y + 20*z, allInputs)</lang>
The second is to find all of the valid 6x, 9y, and 20z, and then sum them:
<lang rrsplus>mcNuggets2<-rowSums(expand.grid(seq(0,100,6),seq(0,100,9),seq(0,100,20)))</lang>
Either way, we get identical results, as checked by:
<lang rrsplus>all(mcNuggets==mcNuggets2)</lang>
For our final answer, note that our choice to remove values from the vector 0:100 means our outputs will already be sorted, unique, and no greater than 100.
<lang rrsplus>results<-setdiff(0:100,mcNuggets)
cat("The non-McNuggets numbers that are no greater than 100 are:",results,"\nThe largest is",max(results),"\n")</lang>
Ultimately, this can be done in one line:
<lang rrsplus>max(setdiff(0:100,rowSums(expand.grid(seq(0,100,6),seq(0,100,9),seq(0,100,20)))))</lang>
{{output}}
<pre>> all(mcNuggets==mcNuggets2)
331

edits