Code Golf: Mix the nuts so that none of the same kind are touching

16

1

Input:

Input is a randomized array of nuts (in your language), the possible nuts follow. Your program must have a way of representing each kind of nut, such as an integer code. Program must be able to handle any size array of any configuration of nuts.

Possible Nuts:

Kola nut
Macadamia
Mamoncillo
Maya nut
Mongongo
Oak acorns
Ogbono nut
Paradise nut
Pili nut
Pistachio
Walnut

Output:

Output must be the array sorted in such a fashion that there are no adjacent nuts of the same kind. If this is impossible, the output should be an empty array.

Example Input (simplified):

["walnut", "walnut", "pistachio"]

Example Output:

["walnut", "pistachio", "walnut"]

Solutions may not simply shuffle the array until it becomes unique by chance. The sort employed must be a deterministic one

Mixed nuts? I see two almonds touching!

Thomas Dignan

Posted 2012-06-28T04:46:14.657

Reputation: 381

4"Your program must have a way of representing each kind of nut, such as an integer code" why is that? — "may not simply shuffle the array until it becomes unique by chance. The sort employed must be a deterministic one" a shuffle can still be deterministic. Do you just mean to impose a limit on the program's time complexity? – ceased to turn counterclockwis – 2012-06-28T07:50:37.913

1I have to agree with @leftaroundabout forbidding a particular algorithm is silly without a very good reason. One of the most rewarding things about code games like this is exactly the variety of methods that get employed. – dmckee --- ex-moderator kitten – 2012-06-28T14:37:26.230

@dmckee, I think the requirement that the algorithm be deterministic is reasonable -- if the RNG is faulty or the input fairly long, a nondeterministic solution may fail to terminate. – boothby – 2012-06-28T20:27:45.570

@boothby. Meh. I'm a particle physicist. Monte Carlo is a important tool in its own right. Moreover, If I choose a fixed PRNG and a fixed seed it is deterministic. – dmckee --- ex-moderator kitten – 2012-06-28T20:32:38.573

@dmckee, forgive me, but I'm a mathematician, so we may never see eye to eye here. With a fixed PRNG, it isn't an algorithm because valid inputs result in a nonterminating condition. – boothby – 2012-06-28T20:37:49.770

@TomDignan, is it OK to have the internal representation of the nut be those strings you passed in? That portion of the question is quite unclear. – boothby – 2012-06-28T20:39:10.457

@boothby yes -- represent the nut any way as long as you have the same number of unique nuts – Thomas Dignan – 2012-06-29T00:10:32.070

@leftaroundabout -- I may have been overly verbose, as boothby notes, the strings are a fine representation (for any language I can think of) but due to the fact that they take up so many characters, and this is code golf, the use of integer codes is permitted to save chars – Thomas Dignan – 2012-06-29T00:11:59.683

1I think I found an example that has several solutions, but may cause some answers to fail to find any of them. Can I add it? (5,4,4,3,3,2) perl6 -e 'my @a="aaaaabbbbccccdddee".comb;my @b = @a.pick(*) while @b.squish !== @a;say [~] @b' baedcbdacdecbabaca (3,3,2) may cause them to fail also. – Brad Gilbert b2gills – 2015-11-19T22:18:17.357

@BradGilbertb2gills makes me want to try perl6 – Thomas Dignan – 2015-11-27T02:05:40.850

I really wanted to know if it was alright if I added an example that followed that pattern. – Brad Gilbert b2gills – 2015-11-28T01:29:30.750

An algorithm that finds all permutations without repeating is possible and deterministic. Add checking for success on each and it is still deterministic. And, a PRING plus a test that terminates—do you (@dmckee) also call that nondeterministic? For me, a predictable sequence is deterministic even if infinitely long. – WGroleau – 2018-05-14T08:13:01.353

@WGroleau I think you directed that at the wrong person. – dmckee --- ex-moderator kitten – 2018-05-14T16:30:57.980

You say a PRNG is not deterministic because it doesn't terminate. I ask whether you say one that does terminate is deterministic. (I say both are deterministic in that both have repeatable and predictable sequences.) – WGroleau – 2018-05-14T19:57:58.693

@WGroleau You've misreading the history. I'm not the one who said that. – dmckee --- ex-moderator kitten – 2018-05-16T17:31:25.553

oops, looked at the wrong end of the comment. It was actually @boothby Mea culpa. – WGroleau – 2018-05-16T22:10:32.627

Answers

8

GolfScript, 42 41 37 38 characters

~.`{\`{=}+%1-,}+$.,)2//zip[]*.2<..&=*p

The code expects input on STDIN and prints result to STDOUT, e.g.:

> ["walnut" "walnut" "walnut" "macadamia" "pistachio"]
["walnut" "macadamia" "walnut" "pistachio" "walnut"]

> ["walnut" "walnut" "walnut" "macadamia" "walnut"]
[]

The script became longer than expected but I suppose there is room for improvement.

Edit: The case of a list with a single item costs me 1 character (the best comparison I could come up with is the same as Peter's).

Howard

Posted 2012-06-28T04:46:14.657

Reputation: 23 109

1I hadn't sat down to implement this yet, but $.,)2//zip is exactly what I had in mind. My interpretation of the spec was that it could take input on the stack and leave it on the stack, so maybe we should push for clarification. – Peter Taylor – 2012-06-28T18:03:47.433

@PeterTaylor, cool. Works for me. – boothby – 2012-06-29T07:39:33.167

This crashes on input ["walnut"] in the compare-the-first-two section. – Peter Taylor – 2012-06-29T21:21:27.993

@PeterTaylor You're right. I'll have to work on that corner case. – Howard – 2012-06-30T05:04:10.440

6

Brachylog v2, 10 bytes

p.¬{s₂=}∨Ė

Try it online!

Brute-force solution. (This is a function, allowed because the challenge does not say "full program".) It's also mostly a direct translation of the spec (the only real subtlety is that I managed to arrange things so that all the implicit constraints arrived in exactly the right places, thus not needing any extra characters to disambiguate them).

Note that this is a generic algorithm for rearranging any sort of list so that it does not have two touching elements; it can handle string representations of the elements, and it can handle integer codes just as well. So it doesn't really matter how the "Your program must have a way of representing each kind of nut, such as an integer code." requirement from the question is interpreted.

Explanation

p.¬{s₂=}∨Ė
p            Find a permutation of {the input}
  ¬{   }     which does not have the following property:
    s₂         it contains a pair of adjacent elements
      =        that are equal
        ∨    {no constraint on what value the equal elements can have}
 .           If you find such a permutation, output it.
        ∨    If no permutation is found, ignore the input and
         Ė     {output} an empty list

ais523

Posted 2012-06-28T04:46:14.657

Reputation: 11

6

GolfScript, 32 chars

~:x{]x\-,}$.,)2//zip[]*.2<..&=*`

Same input and output format as Howard's solution.

Peter Taylor

Posted 2012-06-28T04:46:14.657

Reputation: 41 901

I had the same idea on the sort part but didn't code it up yet :-) Good work! – Howard – 2012-06-30T05:00:30.443

1

J, 80 characters

]`_:@.(0<2&([:+/=/\))({.~-:@#),((],.|.)~>.@-:@#)<"1;(\:#&.>)(</.])[;.1' ',1!:1[1

Not really in the same league as Golfscript on this one. I suspect there are gains to be made, but the 14 characters needed just to get the list into the program [;.1' ',1!:1[1 is a major handicap.

Basically the program takes in the list, groups similar items together, sorts by number of items in each group descending, and alternates the output between the first half and the second half of the list. The rest if the code gets rid of extraneous items and decides if the list is valid output (outputting infinity _ if it isn't).

Example:

macadamia walnut walnut pistachio walnut

group (</.]):

macadamia walnut walnut walnut pistachio

sort (\:#&.>):

walnut walnut walnut macadamia pistachio

ravel ((],.|.)~>.@-:@#):

walnut macadamia walnut pistachio walnut

Gareth

Posted 2012-06-28T04:46:14.657

Reputation: 11 678

0

Jelly, 14 bytes

Ġz0UẎḟ0ịµẋ⁻ƝẠ$

Try it online!

The last 6 bytes can be removed if we can have undefined behavior for invalid inputs.

Erik the Outgolfer

Posted 2012-06-28T04:46:14.657

Reputation: 38 134

0

Stax, 10 bytes

│éÿ∞å[zàL⌂

Run and debug it

Here's the same program unpacked, ungolfed, and commented.

|T      get all permutations
{       block to filter by
  :g_=  after dropping repeated elements, it's still equal
f       execute filter
|c      terminate and pop if falsy (no match)
hJ      take the first permutation, and join with spaces

Run this one

recursive

Posted 2012-06-28T04:46:14.657

Reputation: 8 616