fork(1) 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 tryPlace(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. }
  15. }
  16. }
  17. // if we reach here, ship can be placed
  18. for(int i=0;i<height;i++) {
  19. for(int j=0;j<width;j++) {
  20. board[y+i][x+j]='#';
  21. }
  22. }
  23. return true; // ship placed successfully
  24. }
  25.  
  26. public static void main (String[] args) throws java.lang.Exception
  27. {
  28. ThreadLocalRandom random=ThreadLocalRandom.current();
  29. board=new char[10][10];
  30. for(int i=0;i<10;i++)
  31. for(int j=0;j<10;j++)
  32. board[i][j]='.';
  33.  
  34. int size=3;
  35. int amount=2;
  36. while(amount>0) {
  37. if(random.nextBoolean()) {
  38. // horizontal
  39. if(tryPlace(random.nextInt(10-size+1),random.nextInt(10),size,1)){
  40. amount--; // one placed
  41. }
  42. } else {
  43. // vertical
  44. if(tryPlace(random.nextInt(10),random.nextInt(10-size+1),1,size)){
  45. amount--; // one placed
  46. }
  47. }
  48. }
  49.  
  50. // and a 4x2 mothership
  51. while(!(random.nextBoolean()
  52. ?tryPlace(random.nextInt(7),random.nextInt(9),4,2)
  53. :tryPlace(random.nextInt(9),random.nextInt(7),2,4)
  54. ));
  55.  
  56. for(int i=0;i<10;i++)
  57. System.out.println(board[i]); // char[] has special overload for print/ln()
  58. }
  59. }
  60.  
Success #stdin #stdout 0.06s 32468KB
stdin
Standard input is empty
stdout
.....###..
..........
..........
......#...
......#...
......#...
........##
........##
........##
........##