Question

maze-type of puzzle

Asked by: davidlars99

Hi,

I came across one puzzle, which I can't seem to find the right solution to start... could anyone give a suggestion please? I want to create a c# program to do that.




Strawberries are growing in a rectangular field of length and width at most 50. You want to build greenhouses to enclose the strawberries. Greenhouses are rectangular, axis-aligned with the field (i.e., not diagonal), and may not overlap. The cost of each greenhouse is $10 plus $1 per unit of area covered.

Write a program that chooses the best number of greenhouses to build, and their locations, so as to enclose all the strawberries as cheaply as possible. Heuristic solutions that may not always produce the lowest possible cost will be accepted: seek a reasonable tradeoff of efficiency and optimality.

Your program must read a small integer 1 ≤ N ≤ 10 representing the maximum number of greenhouses to consider, and a matrix representation of the field, in which the '@' symbol represents a strawberry. Output must be a copy of the original matrix with letters used to represent greenhouses, preceded by the covering's cost. Here is an example input-output pair:
Input       Output

4
..@@@@@...............
..@@@@@@........@@@...
.....@@@@@......@@@...
.......@@@@@@@@@@@@...
.........@@@@@........
.........@@@@@........

      

90
..AAAAAAAA............
..AAAAAAAA....CCCCC...
..AAAAAAAA....CCCCC...
.......BBBBBBBCCCCC...
.......BBBBBBB........
.......BBBBBBB........

In this example, the solution cost of $90 is computed as (10+8*3) + (10+7*3) + (10+5*3).

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2006-05-25 at 07:49:50ID21863744
Tags

maze

,

puzzle

Topics

Math & Science

,

Adobe Type Manager

Participating Experts
7
Points
500
Comments
12

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. puzzle??
    Hi, a small puzzle for poor coders like us who still havent gone thru Bruce Eckel. This is taken straight off Thinking in C++ : Volume 1 and jogs the mind a little. Those who have read the book, don't spoil the fun. Puzzle : Describe what the following declarations mea...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: snoyes_jwPosted on 2006-05-25 at 08:06:34ID: 16761403

Is it a requirement that every strawberry be covered?

 

by: davidlars99Posted on 2006-05-25 at 08:16:06ID: 16761478

yes, and only in a rectangular greenhouse which doesn't overlap...

 

by: mrichmonPosted on 2006-05-25 at 09:38:40ID: 16762173

Is this for a course?

 

by: NovaDenizenPosted on 2006-05-25 at 09:49:05ID: 16762263

First thing you need to do is create a function that evaluates a greenhouse scheme and tells you its cost, using the prescribed cost function (10 + width * height).  Include a parameter 'c' for the added cost of each strawberry that is not covered.

Create another function that adds a random greenhouse to a greenhouse scheme.  It has to make sure the greenhouse doesn't overlap other greenhouses, and make sure you don't add any beyond the maximum allowed number.

Create another function that deletes a random greenhouse from a greenhouse scheme.  If the scheme is already empty, don't worry about it.

Create another function that tweaks a random greenhouse, moving one of its edges by one unit.  If it would cause an invalid greenhouse (zero area) or an overlapping greenhouse, then just don't do it.

Now you're ready to do a simple nondeterministic greedy method to find a decent solution.

 

by: davidlars99Posted on 2006-05-25 at 11:45:50ID: 16763193

thanks Nova, I'll try as you say...

mrichmon, we have a new team lead developer joining our team and our IT manager gave him this puzzle, so I was wondering myself...

 

by: ozoPosted on 2006-05-25 at 12:03:11ID: 16763355

If every strawberry must be covered, the contribution of the  $1 per unit of area covered is fixed,
and only the $10 cost of each greenhouse can change, so the best number of greenhouses to build is the minimum possible.
You can start trying to cover everything with 1 rectangle, then with 2 rectangles, etc. stopping as soon as you succeed.
To determine whether it is possible to cover everything with n rectangles without overlap,
it suffices to check every combination of upper left corners and lower right corners.
Some speedups to this may occur to you too.

 

by: NovaDenizenPosted on 2006-05-25 at 12:36:47ID: 16763682

The greedy algorithm would be pretty simple.  You start with an empty greenhouse scheme, make a copy, apply 1 to a few random mutations to the copy, then compare the cost of the copy to the original.  If the solution has improved, replace the original with the mutated copy.  Loop until satisfied.

Those functions I outlined would also be a good foundation for a genetic algorithm implementation.  That would be similar to the greedy algorithm, except you keep many originals instead of just one, and probabilistically weed out the higher-cost schemes.

I'm also thinking that it would make sense to slowly ramp up the cost-per-missed-strawberry cost parameter.  If it is too big at the beginning, then it will just pick one huge greenhouse to cover up the whole field.  If it is too small at the end, then the greenhouses will not be covering all the strawberries.  So, start with a small cost (15 per missed strawberry or so), then slowly ramp it up (linearly? exponentially?  I don't know...) until it gets to be 10000 or so at the end, to make any incomplete solutions unlikely to survive.

 

by: grg99Posted on 2006-05-25 at 14:05:37ID: 16764507

As ozo said, you want to minimize the number of greenhouses.  That implies you want to make as many large greenhouses as possible.

One idea might be to first se what the largest greenhouse is that you can make, then repeat that again and again.

One way to find the largest greenhouse is to try starting at every x,y where these is a strawberry, see if you can stretch as far as you can to the right and down while still enclosing all strawberrys.  Note the size and go to the next x,y.  When you've scanned them all, choose the largest greenhouse and mark all those spots.  Repeat the whole deal until all the strawberrys are covered.

There may be a better way, or flaws in this method, but that's the best I can dream up right now.

 

by: davidlars99Posted on 2006-05-25 at 14:15:21ID: 16764629

thank you all!

I started with a little parsing mechanism and index pointer function (Replace(...)) to find and replace character at the specified location in an char array, which works fine... All I have left is to implement a deterministic function to build the actual greenhouses.

any other suggestions?


using System;
using System.IO;
using System.Text.RegularExpressions;

namespace StrawberryFields
{
      class GreenHouse
      {
            char[] main_buffer = null;
            char[] work_buffer = null;
            char[] alpha = null;
            Dimension dim;

            private enum Direction
            {
                  RIGHT,
                  LEFT,
                  UP,
                  DOWN
            }

            struct Dimension
            {
                  public int Width;
                  public int Height;
            }

            internal GreenHouse(string src)
            {            
                  dim = new Dimension();
                  //FileInfo f = new FileInfo(src);
                  using (StreamReader fs = new StreamReader(src))
                  {                        
                        Regex rx = new Regex(@"\s+", RegexOptions.Multiline | RegexOptions.Compiled);
                        
                        this.main_buffer = rx.Replace(fs.ReadToEnd().Trim(), "\n").ToCharArray();      
                        this.work_buffer = new char[this.main_buffer.Length];
                        
                        this.dim.Width=0;
                        this.dim.Height=1;

                        for (int i=0; i<this.main_buffer.Length; i++)
                        {
                              if(this.main_buffer[i]=='\n')                                          
                                    this.dim.Height++;
                              else
                                    this.dim.Width++;
                              this.work_buffer[i]=this.main_buffer[i];
                        }                        

                        this.alpha = new char[15] {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O'};
                        this.dim.Width=this.main_buffer.Length/this.dim.Height;
                        this.Build();
                  }                  
            }

            void Build()
            {
                  Console.WriteLine("{0}Width={1}, Height={2}, Total={3} {4}", "\n", this.dim.Width, this.dim.Height, (this.dim.Width*this.dim.Height), "\n");
                  this.Replace(1,0,this.alpha[0]);
                  Console.WriteLine(this.main_buffer);
            }

            void Replace(int rowIndex, int colIndex, char chr)
            {
                  try
                  {
                        this.main_buffer[rowIndex*this.dim.Width+colIndex+rowIndex]=chr;
                  }
                  catch (IndexOutOfRangeException ex)
                  {
                        Console.WriteLine("Error: " + ex.Message);
                  }
            }
      }
}

 

by: Adam314Posted on 2006-06-02 at 09:31:34ID: 16818106

It could be cheaper to cover a non-strawberry than to only cover straberries
In this example:  (@=straberry, .=blank)
@.@
. @.
@.@

1 greenhouse covering the whole thing is cheapest, even though it covers non-strawberries.

 

by: Aramis11Posted on 2006-06-14 at 13:11:39ID: 16906262

That 'C' greenhouse in the example does not look right according to the conditions stated. Are the walls allowed to warp? The Adam solution of one to cover the whole thing sounds best, except it should only extend to the strawberry edge limits. Of course if just one plant would hang outside to provoke an excessive extension, it may need some tweaks. It should have a routine to crunch the difference between one and two structures in a field like this:

@@@@@@@@@@@@@@
@@@@@@@@@@@@@@
@@@@@@@@@@@@@@
@@@@@@@@@@@@@@
         @

 

by: Adam314Posted on 2006-06-15 at 09:03:07ID: 16912744

What I would do is check every possible combination of greenhouses, and then select the cheapest one that covers all straberries.  This might not be very fast, but would work.  

Probably use a recursive function.  In a loop, it would try to place a greenhouse in every space, of every size, and recursively call itself to repeat.  

place_greenhouse (Map as greenhouse_map) {
   
    #If all strawberries are covered, save this map
    if(success(Map)) {
        push good_maps, Map;
        return;
    }
    for(start_column=1;start_column<=width;start_column++) {
        for(start_row=1;start_row<=height;start_row++) {
            for(greenhousewidth=1;greenhousewidth<=width-start_row+1;greenhousewidth++) {
                for(greenhouseheight=1;greenhouseheight<=height-start_column+1;greenhouseheight++) {
                    #Skip if this greenhouse overlaps existing greenhouses
                    next if overlap(Map, start_column, start_row, greenhousewidth, greenhouseheight);
                   
                    thismap=make_map(Map, start_column, start_row, greenhousewidth, greenhouseheight);
                    place_greenhouse(thismap);
                }
            }
        }
    }
}

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...