Showing posts with label 2014. Show all posts
Showing posts with label 2014. Show all posts

Thursday, April 24, 2014

Minesweeper Master (Google Code Jam Qualification Round: Problem C) : My attempt

Problem

Minesweeper is a computer game that became popular in the 1980s, and is still included in some versions of the Microsoft Windows operating system. This problem has a similar idea, but it does not assume you have played Minesweeper.
In this problem, you are playing a game on a grid of identical cells. The content of each cell is initially hidden. There are M mines hidden in M different cells of the grid. No other cells contain mines. You may click on any cell to reveal it. If the revealed cell contains a mine, then the game is over, and you lose. Otherwise, the revealed cell will contain a digit between 0 and 8, inclusive, which corresponds to the number of neighboring cells that contain mines. Two cells are neighbors if they share a corner or an edge. Additionally, if the revealed cell contains a 0, then all of the neighbors of the revealed cell are automatically revealed as well, recursively. When all the cells that don't contain mines have been revealed, the game ends, and you win.
For example, an initial configuration of the board may look like this ('*' denotes a mine, and 'c' is the first clicked cell):
*..*...**.
....*.....
..c..*....
........*.
..........
There are no mines adjacent to the clicked cell, so when it is revealed, it becomes a 0, and its 8 adjacent cells are revealed as well. This process continues, resulting in the following board:
*..*...**.
1112*.....
00012*....
00001111*.
00000001..
At this point, there are still un-revealed cells that do not contain mines (denoted by '.' characters), so the player has to click again in order to continue the game.
You want to win the game as quickly as possible. There is nothing quicker than winning in one click. Given the size of the board (R x C) and the number of hidden mines M, is it possible (however unlikely) to win in one click? You may choose where you click. If it is possible, then print any valid mine configuration and the coordinates of your click, following the specifications in the Output section. Otherwise, print "Impossible".

Input

The first line of the input gives the number of test cases, TT lines follow. Each line contains three space-separated integers: RC, and M.

Output

For each test case, output a line containing "Case #x:", where x is the test case number (starting from 1). On the following R lines, output the board configuration with C characters per line, using '.' to represent an empty cell, '*' to represent a cell that contains a mine, and 'c' to represent the clicked cell.
If there is no possible configuration, then instead of the grid, output a line with"Impossible" instead. If there are multiple possible configurations, output any one of them.

Limits

0 ≤ M < R * C.

Small dataset

1 ≤ T ≤ 230.
1 ≤ RC ≤ 5.

Large dataset

1 ≤ T ≤ 140.
1 ≤ RC ≤ 50.


Sample


Input

Output
5
5 5 23
3 1 1
2 2 1
4 7 3
10 10 82

Case #1:
Impossible
Case #2:
c
.
*
Case #3:
Impossible
Case #4:
......*
.c....*
.......
..*....
Case #5:
**********
**********
**********
****....**
***.....**
***.c...**
***....***
**********
**********
**********




So here's the code that I wrote: (Algorithm applied: http://stackoverflow.com/questions/23039471/minesweeper-master-from-google-code-jam2014-qualification-round )

Algorithm

Let's first define N, the number of non-mine cells:
N = R * C - M
A simple solution is to fill an area of N non-mine cells line-by-line from top to bottom. Example for R=5C=5M=12:
c....
.....
...**
*****
*****
That is:
  • Always start in the top-left corner.
  • Fill N / C rows with non-mines from top to bottom.
  • Fill the next line with N % C non-mines from left to right.
  • Fill the rest with mines.
There are only a few special cases you have to care about.

Single non-mine

If N=1, any configuration is a correct solution.

Single row or single column

If R=1, simply fill in the N non-mines from left-to-right. If C=1, fill N rows with a (single) non-mine.

Too few non-mines

If N is even, it must be >= 4.
If N is odd, it must be >= 9. Also, R and C must be >= 3.
Otherwise there's no solution.

Can't fill first two rows

If N is even and you can't fill at least two rows with non-mines, then fill the first two rows with N / 2non-mines.
If N is odd and you can't fill at least two rows with non-mines and a third row with 3 non-mines, then fill the first two rows with (N - 3) / 2 non-mines and the third row with 3 non-mines.

Single non-mine in the last row

If N % C = 1, move the final non-mine from the last full row to the next row.
Example for R=5C=5M=9:
c....
.....
....*
..***
*****

Here's the code that I wrote in C++:
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

ifstream input;
ofstream output;
int **board;
int index=0;

void display(int r, int c)
{
 cout<<"Case #"<<index+1<<": \n";
 output<<"Case #"<<index+1<<": \n";
 for(int i=0;i<r;++i)
  {
   for(int j=0;j<c;++j)
   {
    if(board[i][j]==0)
    {
     cout<<"c";
     output<<"c";
    }
    if(board[i][j]==1)
    {
     cout<<"*";
     output<<"*";
    }
    if(board[i][j]==2)
    {
     cout<<".";
     output<<".";
    }
   }
   output<<endl;
   cout<<endl;
  }
}

int main()
{
 input.open("d:\\C-large-practice.in");
 output.open("d:\\out.txt");

 int nCases=0;
 input>>nCases;

 for(;index<nCases;++index)
 {
  output.flush();
  int r, c, m, n;
  input>>r>>c>>m;

  n = r*c-m;

  board = new int *[r];
  for(int j=0;j<r;++j)
  {
   board[j] = new int[c];
  }

  if(n==1)
  {
   //output<<"Case 1\n";
   for(int i = 0;i<r;++i)
   {
    for(int j=0;j<c;++j)
    {
     board[i][j]=1; //mine
    }
   }
   board[0][0]=0; //click
   display(r, c);
   continue;
  }

  if(r==1)
  {
   //output<<"Case 2\n";
   int tNM = n; //temporary non mine counter
   for(int i =0;i<c;++i)
   {
    if(tNM==0)
    {
     board[0][i]=1; //mine
    }
    else
    {
    board[0][i]=2;
    tNM--;    //non-mine
    }
   }
   board[0][0]=0;   //click
   display(r, c);
   continue;
  }
  if(c==1)
  {
   //output<<"Case 3\n";
   int tNM = n; //temporary non mine counter
   for(int i =0;i<r;++i)
   {
    if(tNM==0)
    {
     board[i][0]=1; //mine
    }
    else
    {
    board[i][0]=2;
    tNM--;    //non-mine
    }
   }
   board[0][0]=0;   //click
   display(r, c);
   continue;
  }

  if((n%2==0 && n<4) || (n%2==1 && ((r<3||c<3)||n<9)))
  {
   cout<<"Case #"<<index+1<<": \nImpossible\n";
   output<<"Case #"<<index+1<<": \nImpossible\n";
   output.flush();
   continue;
  }

  if(n%2==0 && ((n/c)<2))
  {
   //output<<"Case 4\n";
   for(int i = 0;i<2;++i)
   {
    for(int j =0; j<n/2;++j)
    {
     board[i][j]=2;
    }
   }

   //rest are mines
   for(int i=0;i<r;++i)
   {
    for(int j =0;j<c;++j)
    {
     if(board[i][j]!=2)
      board[i][j]=1;
    }
   }
   board[0][0]=0; //click
   display(r, c);
   continue;
  }

  if(n%2==1 && ((n/c<2) ||((n-2*c)<3)))
  {
   //output<<"Case 5\n";
   int tNM = n;
   for(int i = 0;i<2;++i)
   {
    for(int j =0; j<(n-3)/2;++j)
    {
     board[i][j]=2;
    }
   }

   board[2][0] = 2;
   board[2][1] = 2;
   board[2][2] = 2; //the three non mines

   //rest are mines
   for(int i=0;i<r;++i)
   {
    for(int j =0;j<c;++j)
    {
     if(board[i][j]!=2)
      board[i][j]=1;
    }
   }
   board[0][0]=0; //click
   display(r, c);
   continue;
  }

  //else the last case:
  int tNM = n;
  for(int i =0;i<r;++i)
  {
   //output<<"Case 6\n";
   for(int j =0;j<c;++j)
   {
    if(tNM!=0)
    {
    board[i][j]=2;
    tNM--;
    }
    else
     board[i][j]=1;
   }
  }
   if(n%c==1)
   {
    board[n/c-1][c-1] = 1;
    board[n/c][1] = 2;
   }
   board[0][0] = 0; 
  display(r, c);
 }
}
It looks a lot like "write-only" code but it does work.

Thursday, April 17, 2014

Magic Trick [Google Code Jam 2014: (Qualification Round Problem)]

Problem

Recently you went to a magic show. You were very impressed by one of the tricks, so you decided to try to figure out the secret behind it!
The magician starts by arranging 16 cards in a square grid: 4 rows of cards, with 4 cards in each row. Each card has a different number from 1 to 16 written on the side that is showing. Next, the magician asks a volunteer to choose a card, and to tell him which row that card is in.
Finally, the magician arranges the 16 cards in a square grid again, possibly in a different order. Once again, he asks the volunteer which row her card is in. With only the answers to these two questions, the magician then correctly determines which card the volunteer chose. Amazing, right?
You decide to write a program to help you understand the magician's technique. The program will be given the two arrangements of the cards, and the volunteer's answers to the two questions: the row number of the selected card in the first arrangement, and the row number of the selected card in the second arrangement. The rows are numbered 1 to 4 from top to bottom.
Your program should determine which card the volunteer chose; or if there is more than one card the volunteer might have chosen (the magician did a bad job); or if there's no card consistent with the volunteer's answers (the volunteer cheated).

Solving this problem

Usually, Google Code Jam problems have 1 Small input and 1 Large input. This problem has only 1 Small input. Once you have solved the Small input, you have finished solving this problem.

Input

The first line of the input gives the number of test cases, TT test cases follow. Each test case starts with a line containing an integer: the answer to the first question. The next 4 lines represent the first arrangement of the cards: each contains 4 integers, separated by a single space. The next line contains the answer to the second question, and the following four lines contain the second arrangement in the same format.

Output

For each test case, output one line containing "Case #x: y", where x is the test case number (starting from 1).
If there is a single card the volunteer could have chosen, y should be the number on the card. If there are multiple cards the volunteer could have chosen, y should be "Bad magician!", without the quotes. If there are no cards consistent with the volunteer's answers, y should be "Volunteer cheated!", without the quotes. The text needs to be exactly right, so consider copying/pasting it from here.

Limits

1 ≤ T ≤ 100.
1 ≤ both answers ≤ 4.
Each number from 1 to 16 will appear exactly once in each arrangement.

Sample

InputOutput

3
2
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
3
1 2 5 4
3 11 6 15
9 10 7 12
13 14 8 16
2
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
2
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
2
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
3
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16

Case #1: 7
Case #2: Bad magician!
Case #3: Volunteer cheated!


Here is what I wrote (gives correct output): 

import java.util.*;
import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class magic {
    public static void main(String[] args) throws Exception{
        BufferedReader br = new BufferedReader(new FileReader("d:\\A-small-attempt0.in"));
        BufferedWriter bw = new BufferedWriter(new FileWriter("d:\\result.txt"));
        
        int ncases = Integer.parseInt(br.readLine());
        
        int index = 1;
        while(index<=ncases){
            int nrow1 = Integer.parseInt(br.readLine());
            
            int[][] row1 = new int[4][4];
            int[][] row2 = new int[4][4];
            
            Pattern p = Pattern.compile("-?\\d+");
            Matcher m = null;
            for(int i= 0;i<4;++i){
                m =  p.matcher(br.readLine());
                for(int j = 0;j<4;++j){
                    if(m.find())
                    row1[i][j] = Integer.parseInt(m.group());
                }
            }
            
            int nrow2 = Integer.parseInt(br.readLine());
            for(int i= 0;i<4;++i){
                m =  p.matcher(br.readLine());
                for(int j = 0;j<4;++j){
                    if(m.find())
                    row2[i][j] = Integer.parseInt(m.group());
                }
            }
            
            Vector<Integer> vec1 = new Vector<Integer>();
            Vector<Integer> vec2 = new Vector<Integer>();
            
            for(int i = 0;i<4;++i){
                vec1.add(row1[nrow1-1][i]);
            }
            for(int i = 0;i<4;++i){
                vec2.add(row2[nrow2-1][i]);
            }
            
            Vector<Integer> number = new Vector<Integer>();
            for(int i = 0;i<vec1.size();++i){
                for(int j = 0;j<vec2.size();++j){
                    if(vec1.elementAt(i)==vec2.elementAt(j)){
                        number.add(vec1.elementAt(i));
                    }
                }
            }
            if(number.size()==0){
                bw.write("Case #"+index+++": Volunteer cheated!");
                //System.out.println("Case #"+index+++": Volunteer cheated!");
            }
            if(number.size()==1){
                bw.write("Case #"+index+++": "+number.elementAt(0));
                //System.out.println("Case #"+index+++": "+number.elementAt(0));
            }
            if(number.size()>1){
                bw.write("Case #"+index+++": Bad magician!");
                //System.out.println("Case #"+index+++": Bad magician!");
            }
            bw.newLine();
            bw.flush();
        }
    }
}


Cookie Clicker Alpha [Google Code Jam 2014 Qualification Round] (With Solution : Good + Bad Attempts)

Introduction

Cookie Clicker is a Javascript game by Orteil, where players click on a picture of a giant cookie. Clicking on the giant cookie gives them cookies. They can spend those cookies to buy buildings. Those buildings help them get even more cookies. Like this problem, the game is very cookie-focused. This problem has a similar idea, but it does not assume you have played Cookie Clicker. Please don't go play it now: it might be a long time before you come back.

Problem

In this problem, you start with 0 cookies. You gain cookies at a rate of 2 cookies per second, by clicking on a giant cookie. Any time you have at least C cookies, you can buy a cookie farm. Every time you buy a cookie farm, it costs you C cookies and gives you an extra F cookies per second.
Once you have X cookies that you haven't spent on farms, you win! Figure out how long it will take you to win if you use the best possible strategy.

Example

Suppose C=500.0, F=4.0 and X=2000.0. Here's how the best possible strategy plays out:
  1. You start with 0 cookies, but producing 2 cookies per second.
  2. After 250 seconds, you will have C=500 cookies and can buy a farm that producesF=4 cookies per second.
  3. After buying the farm, you have 0 cookies, and your total cookie production is 6 cookies per second.
  4. The next farm will cost 500 cookies, which you can buy after about 83.3333333seconds.
  5. After buying your second farm, you have 0 cookies, and your total cookie production is 10 cookies per second.
  6. Another farm will cost 500 cookies, which you can buy after 50 seconds.
  7. After buying your third farm, you have 0 cookies, and your total cookie production is 14 cookies per second.
  8. Another farm would cost 500 cookies, but it actually makes sense not to buy it: instead you can just wait until you have X=2000 cookies, which takes about142.8571429 seconds.
Total time: 250 + 83.3333333 + 50 + 142.8571429 = 526.1904762 seconds.
Notice that you get cookies continuously: so 0.1 seconds after the game starts you'll have 0.2 cookies, and π seconds after the game starts you'll have 2π cookies.

Input

The first line of the input gives the number of test cases, TT lines follow. Each line contains three space-separated real-valued numbers: CF and X, whose meanings are described earlier in the problem statement.
CF and X will each consist of at least 1 digit followed by 1 decimal point followed by from 1 to 5 digits. There will be no leading zeroes.

Output

For each test case, output one line containing "Case #x: y", where x is the test case number (starting from 1) and y is the minimum number of seconds it takes before you can have X delicious cookies.
We recommend outputting y to 7 decimal places, but it is not required. y will be considered correct if it is close enough to the correct number: within an absolute or relative error of 10-6. See the FAQ for an explanation of what that means, and what formats of real numbers we accept.

Limits

1 ≤ T ≤ 100.

Small dataset

1 ≤ C ≤ 500.
1 ≤ F ≤ 4.
1 ≤ X ≤ 2000.

Large dataset

1 ≤ C ≤ 10000.
1 ≤ F ≤ 100.
1 ≤ X ≤ 100000.

Sample


Input

Output
4
30.0 1.0 2.0
30.0 2.0 100.0
30.50000 3.14159 1999.19990
500.0 4.0 2000.0

Case #1: 1.0000000
Case #2: 39.1666667
Case #3: 63.9680013
Case #4: 526.1904762

Solutions:
So I first solved it through a recursive function. (I still don't know why I did this stupid s***). So small-input file gave correct results but the program terminated during large-input evaluation (stack overflow error). :O

Here is the code (recursive): 


import java.io.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class cookie {
    static int i = 0;
    static Vector<Double> vec;
    static double target=0;
    static double fRate = 0;
    static double fCost = 0;
    
    public static double fun(double prevFarmBuyTimes, double rate){
        if(i==0){
            vec.add(target/rate);
        }
        double farmTime = prevFarmBuyTimes+fCost/rate;
        rate+=fRate;
        double WaitingTime = target/rate;
        double projection = farmTime+WaitingTime;
        vec.add(projection);
        i++;
        if(vec.elementAt(i-1)>vec.elementAt(i)){
            return fun(farmTime, rate);
        }
        else
        {
            return vec.elementAt(i-1);
        }
    }
    
    public static void main(String[] args) throws Exception{
        BufferedReader br = new BufferedReader(new FileReader("d:\\B-large-practice.in"));
        BufferedWriter bw = new BufferedWriter(new FileWriter("d:\\result.txt"));
        
        int ncases = Integer.parseInt(br.readLine());
        int index = 1;
        while(index<=ncases){
            
            Pattern p = Pattern.compile("\\d+.\\d+");
            Matcher m = p.matcher(br.readLine());
            
            if (m.find())
            fCost = Double.parseDouble(m.group());
            
            if (m.find())
            fRate = Double.parseDouble(m.group());
            
            if (m.find())
            target = Double.parseDouble(m.group());
            
            
            //LOGIC STARTS HERE
             vec = new Vector<Double>();
             i=0;
             double time = fun(0,2);
             
             bw.write("Case #"+index+": "+time);
             bw.newLine();
             bw.flush();
             System.out.println(time);
             index++;
        }    
    }    
}


And here is the improved version without recursion.(Gives correct results for large-inputs): 


import java.io.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class cookie {
    
    public static void main(String[] args) throws Exception{
        BufferedReader br = new BufferedReader(new FileReader("d:\\B-large-practice.in"));
        BufferedWriter bw = new BufferedWriter(new FileWriter("d:\\result.txt"));
        
         int ncases = Integer.parseInt(br.readLine());
         int index = 1;
         int i = 0;
         Vector<Double> vec;
         double target=0;
         double fRate = 0;
         double fCost = 0;
    
        while(index<=ncases){
            
            Pattern p = Pattern.compile("\\d+.\\d+");
            Matcher m = p.matcher(br.readLine());
            
            if (m.find())
            fCost = Double.parseDouble(m.group());
            
            if (m.find())
            fRate = Double.parseDouble(m.group());
            
            if (m.find())
            target = Double.parseDouble(m.group());
            
             vec = new Vector<Double>();
             i=0;
        
             double rate =2;
             vec.add(target/rate);
             
             double result = 0;
             double prevFarmBuyTimes=0;
             
             while(true){
             
             double farmTime = prevFarmBuyTimes+fCost/rate;
             prevFarmBuyTimes=farmTime;
             rate+=fRate;
             double WaitingTime = target/rate;
             double projection = farmTime+WaitingTime;
             i++;
             vec.add(projection);
             if(vec.elementAt(i-1)<vec.elementAt(i)){
                    result =  vec.elementAt(i-1);
                    break;
                }
             }
             
             System.out.println(result);
             bw.write("Case #"+index+": "+result);
             bw.newLine();
             bw.flush();
             index++;
        }    
    }    
}