fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.concurrent.ThreadLocalRandom;
  4.  
  5. /* Name of the class has to be "Main" only if the class is public. */
  6. class Ideone
  7. {
  8. static char board[][];
  9. static boolean tryPlaceWithBorder(int x,int y,int width,int height) {
  10. for(int i=0;i<height;i++)
  11. for(int j=0;j<width;j++)
  12. if(board[y+i][x+j]!='.')
  13. return false; // ship can not be placed
  14. // if we reach here, ship can be placed
  15. for(int i=1;i<height-1;i++)
  16. for(int j=1;j<width-1;j++)
  17. board[y+i][x+j]='#';
  18. return true; // ship placed successfully
  19. }
  20.  
  21. public static void main (String[] args) throws java.lang.Exception
  22. {
  23. ThreadLocalRandom random=ThreadLocalRandom.current();
  24. board=new char[12][12];
  25. for(int i=0;i<12;i++)
  26. for(int j=0;j<12;j++)
  27. board[i][j]='.';
  28.  
  29. int size=3;
  30. int amount=2;
  31. while(amount>0) {
  32. if(random.nextBoolean()) {
  33. // horizontal
  34. if(tryPlaceWithBorder(random.nextInt(12-size-1),random.nextInt(10),size+2,3))
  35. amount--; // one placed
  36. } else {
  37. // vertical
  38. if(tryPlaceWithBorder(random.nextInt(10),random.nextInt(12-size-1),3,size+2)){
  39. amount--; // one placed
  40. }
  41. }
  42. }
  43.  
  44. // and a 4x2 mothership
  45. while(!(random.nextBoolean()
  46. ?tryPlaceWithBorder(random.nextInt(7),random.nextInt(9),6,4)
  47. :tryPlaceWithBorder(random.nextInt(9),random.nextInt(7),4,6)
  48. ));
  49.  
  50. for(int i=1;i<11;i++)
  51. System.out.println(String.valueOf(board[i],1,10));
  52. }
  53. }
  54.  
Success #stdin #stdout 0.1s 32620KB
stdin
Standard input is empty
stdout
..........
..........
..........
..####....
..####.###
..........
..........
.###......
..........
..........