Showing posts with label games. Show all posts
Showing posts with label games. Show all posts

Creating a Guessing Game in Java

Problem:

Write a class GuessingGame that simulates a simple guessing game. Initially, your program should generate a random integer between 1 and 1000 and print the following: "Guess the number between 1 and 1000" (without the quotes). Then, the user is asked to guess the number generated. If the user is correct, the program prints:
"Congratulations" (without the quotes).
Otherwise, if the number entered by the user is less than the generated number you print "Too cold" and when the number is above you print "Too hot". The game does not stop until the user has made a correct guess. Sample program output:

Output:

Guess the number between 1 and 1000

500

Too Cold

750

Too Hot
600
Congratulations

Solution:

import java.util.*;
public class Problem1
{
    public static void main (String args[])
    {
 Random random = new Random();
 int a = random.nextInt(1000) + 1;
 Scanner scan = new Scanner(System.in);
 int guess = 0;
 while (a != guess)
 {
            System.out.println("Guess the number between 1 and 1000:");
            guess = scan.nextInt();
            if (guess < a)
  System.out.println("Too cold!");
            else
  System.out.println("Too hot!");
 }
 if (a == guess)
            System.out.println("Congratulations!");
   
    }
}
Read More

Generating Phone Number in Java

Problem:

Write an application that creates and prints a random phone number of the form xxx-xxx-xxxx. Include the dashed in the output. Do not let the first three digits contain an 8 or 9. And make sure that the second set of three digits is not greater than 742 (i.e. ≤ 742). Hint: Think through the easiest way to construct he phone number. Each digit does not have to be determined separately.

Output:

016-326-5981

Solution:

import java.util.Random;
public class Problem4 {

   public static void main(String args[])
   {
     Random generator = new Random();


     // Generate 3 random numbers between 0 & 7 for the first part of the phone number
  int one = generator.nextInt(8);
  int two = generator.nextInt(8);
  int three = generator.nextInt(8);
  int fourtosix = generator.nextInt(743);
  int seventoten = generator.nextInt(10000);
  String sOne = "" + (one);
  String sTwo = "" + (two);
  String sThree = "" + (three);
  String sFourtosix = "";
  String sSeventoten = "";
  if (fourtosix >= 0 && fourtosix < 10)
   sFourtosix = "00" + (fourtosix);
   else
    if(fourtosix < 100)
     sFourtosix = "0" + (fourtosix);
    else
     sFourtosix = "" + (fourtosix);
     
  if (seventoten >= 0 && seventoten < 10)
   sSeventoten = "000" + (seventoten);
   else
    if(seventoten < 100)
     sSeventoten = "00" + (seventoten);
    else
     if(seventoten < 1000)
      sSeventoten = "0" + (seventoten);
      else
       sSeventoten = "" + (seventoten);  
 

  //Print the phonenumber with this format xxx-xxx-xxxx
  System.out.printf(sOne + sTwo + sThree +"-" +sFourtosix + "-" + sSeventoten);
   }


}
Read More

Rolling Dices through Random Class in Java

Problem:

Nour and Jad start-out the game with a cumulative score of zero. Then each player rolls three dices and a random number appears for each dice. The summation of each number is added in each player’s score. The winner is the player that has the highest score in x turns based on what the players initially decided. Note: If Jad’s score and Nour’s score are equal, let the program prints: Jad and Nour have equal scores, else let the program print who is the winner.

The output should be as follows:

Output:

Please enter the number of turns:
3
Jad's score is: 26
Nour's score is: 27
Nour is the winner

Solution:

import java.util.Random;
import java.util.Scanner;
/**
 *
 * @author George Chalhoub
 */
public class Problem3 {
    public static void main(String args[]){
        Scanner input = new Scanner(System.in);
        Random randomdice = new Random();
     
        int sumjad = 0;
        int sumnour = 0;
   
        int jadDice1 = randomdice.nextInt(7);
        int jadDice2 = randomdice.nextInt(7);
        int jadDice3 = randomdice.nextInt(7);
        int nourDice1 = randomdice.nextInt(7);
        int nourDice2 = randomdice.nextInt(7);
        int nourDice3 = randomdice.nextInt(7);
        sumjad = sumjad + jadDice1 + jadDice2 + jadDice3;
        sumnour = sumnour + nourDice1 + nourDice2 + nourDice3;
     
        System.out.println("Jad's score is: " + sumjad);
        System.out.println("Nour's score is: " + sumnour);
        if (sumjad == sumnour)
                System.out.println("Jad and Nour have the same scores");
        else
            if (sumjad > sumnour)
                System.out.println("Jad is the winner");
                else
                    System.out.println("Nour is the winner");
    }
    
}

    
Read More

Creating a Connect-Four Game in Java

Problem:

Connect four is a two-player board game in which the players alternately drop colored disks into a seven-column, six-row vertically suspended grid, as shown below.
                                                 
The objective of the game is to connect four same-colored disks in a row, a column, or a diagonal before your opponent can do likewise. The program prompts two players to drop a RED or YELLOW disk alternately. Whenever a disk is dropped, the program re-displays the board on the console and determines the status of the game (win, draw, or continue).


Output:

| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
---------------
Drop a red disk at column (0–6): 
0
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
|R| | | | | | |
---------------
Drop a yellow disk at column (0–6): 
1
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
|R|Y| | | | | |
---------------
Drop a red disk at column (0–6): 
2
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
|R|Y|R| | | | |
---------------
Drop a yellow disk at column (0–6): 
3
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
|R|Y|R|Y| | | |
---------------
Drop a red disk at column (0–6): 
4
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
|R|Y|R|Y|R| | |
---------------
Drop a yellow disk at column (0–6): 
3
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | |Y| | | |
|R|Y|R|Y|R| | |
---------------
Drop a red disk at column (0–6): 
2
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | |R|Y| | | |
|R|Y|R|Y|R| | |
---------------
Drop a yellow disk at column (0–6): 
1
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
| |Y|R|Y| | | |
|R|Y|R|Y|R| | |
---------------
Drop a red disk at column (0–6): 
2
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | |R| | | | |
| |Y|R|Y| | | |
|R|Y|R|Y|R| | |
---------------
Drop a yellow disk at column (0–6): 
1
| | | | | | | |
| | | | | | | |
| | | | | | | |
| |Y|R| | | | |
| |Y|R|Y| | | |
|R|Y|R|Y|R| | |
---------------
Drop a red disk at column (0–6): 

1
| | | | | | | |
| | | | | | | |
| |R| | | | | |
| |Y|R| | | | |
| |Y|R|Y| | | |
|R|Y|R|Y|R| | |
---------------
Drop a yellow disk at column (0–6): 
2
| | | | | | | |
| | | | | | | |
| |R|Y| | | | |
| |Y|R| | | | |
| |Y|R|Y| | | |
|R|Y|R|Y|R| | |
---------------
Drop a red disk at column (0–6): 
4
| | | | | | | |
| | | | | | | |
| |R|Y| | | | |
| |Y|R| | | | |
| |Y|R|Y|R| | |
|R|Y|R|Y|R| | |
---------------
Drop a yellow disk at column (0–6): 
3
| | | | | | | |
| | | | | | | |
| |R|Y| | | | |
| |Y|R|Y| | | |
| |Y|R|Y|R| | |
|R|Y|R|Y|R| | |
---------------
Drop a red disk at column (0–6): 
4
| | | | | | | |
| | | | | | | |
| |R|Y| | | | |
| |Y|R|Y|R| | |
| |Y|R|Y|R| | |
|R|Y|R|Y|R| | |
---------------
Drop a yellow disk at column (0–6): 
3
| | | | | | | |
| | | | | | | |
| |R|Y|Y| | | |
| |Y|R|Y|R| | |
| |Y|R|Y|R| | |
|R|Y|R|Y|R| | |
---------------
The yello player won.

Solution:
 import java.util.Scanner;
  
//This will be.. a huge code so we will have to make
//lots of methods for each aspect of the game
public class ConnectFour
{
  //We need to first create the basic visual pattern 
  public static String[][] createPattern()
  {
    //Although the game is more like a table of 6
    //columns and 6 rows, we're going to have to make
    //a 2D array of 7 rows and 15 columns because graphically
    //there's an extra row to show the ___ at the bottom
    //and you have double the columns that show | | | 
    //between each number 
     String[][] f = new String[7][15];
    
    //Time to loop over each row from up to down
    for (int i =0;i<f.length;i++)
    {
      
       //Time to loop over each column from left to right
       for (int j =0;j<f[i].length;j++)
      {
        //Note how it is always the even column
        //that has the border and the odd column
        //between them that will be either empty or
        //have a number 
        if (j% 2 == 0) f[i][j] ="|";
        else f[i][j] = " ";
        
        //Time to make our lowest row
        if (i==6) f[i][j]= "-";
      }
      
    }
    return f;
  }
  
  //Yes, we even need to make a new method for visually
  //printing our game, but at least it's not hard to do
  public static void printPattern(String[][] f)
  {
    for (int i =0;i<f.length;i++)
    {
      for (int j=0;j<f[i].length;j++)
      {
        System.out.print(f[i][j]);
      }
      System.out.println();
    }
  }
  
  //Here's are basic move, making the lowest empty row
  //of a specific column have a Red
  public static void dropRedPattern(String[][] f)
  {
    //We need to have the user tell us what column he wants
    //to drop a red into
    //Note: the user isn't supposed to know that we have 15 columns
    //starting at index 0 till 14 but just 6 nice ones
    System.out.println("Drop a red disk at column (0–6): ");
    Scanner scan = new Scanner (System.in);
    
    //Thankfully, there's a simple formula for converting a 1-2-3-4-5-6 
    //user column number into a 1-3-5-7-9-11-13
    int c = 2*scan.nextInt()+1;
   
    //Now that we know our column, we have to loop
    //over each row from the bottom to the top
    //till we find the first  empty space, drop, and
    //then finish (i.e., break) the move
    //Note: although as coders we're used to starting from 
    //0 to the end, here that wouldn't work so well because
    //it would involve multiple if statements, but try it out
    //on your own if you want to
    for (int i =5;i>=0;i--)
    {
      if (f[i][c] == " ")
      {
        f[i][c] = "R";
        break;
      }
      
    }
  }
  
  //Same as the above step, just yellow
  public static void dropYellowPattern(String[][] f)
  {
    System.out.println("Drop a yellow disk at column (0–6): ");
    Scanner scan = new Scanner (System.in);
    int c = 2*scan.nextInt()+1;
    for (int i =5;i>=0;i--)
    {
      if (f[i][c] == " ")
      {
        f[i][c] = "Y";
        break;
      }
      
    }
  }
  

  //Here's where it gets hard.
  //That's because there are basically four patterns
  //of Reds or Yellows that can win the game
  //One pattern is a horizontal line of four Rs or Ys,
  //another is a vertical line, another is a left-up to right-down
  //diagonal line, and the last is left-down to right-up diagonal,
  //We thus need to code for each type of line
  //and the various places where the line can be
  public static String checkWinner(String[][] f)
  {
    
    //Time to look for the first type of winning line,
    //a horizontal line
    //This line can be on any row, so let's loop over 
    //each row starting from 0 to 5 (since 6 is just ___)
    for (int i =0;i<6;i++)
    {
      //On every row, the four-dotted line can look like
      //----_ _,  _----_, or _ _----
      //Here, _ can be an empty space or one of the colors 
      //and - is not empty space  AND every - has the same
      // color (R or Y)
      //Note: since our R/Y/Empty's can only be in odd places,
      //because of how we created the pattern in the first
      //method, then our count has to be incremented by 2 
      //and will start from 0 (which will be 1, ----_ _) 
      //and stop at 6 (which will be 7, _ _----)
      for (int j=0;j<7;j+=2)
      {
        if ((f[i][j+1] != " ")
        && (f[i][j+3] != " ")
        && (f[i][j+5] != " ")
        && (f[i][j+7] != " ")
        && ((f[i][j+1] == f[i][j+3])
        && (f[i][j+3] == f[i][j+5])
        && (f[i][j+5] == f[i][j+7])))

        //If we found a same-colored pattern, we'll return 
        //the color so that we will know who won
          return f[i][j+1];  
      }
    }
    
    //For a vertical line, let's first loop over each
    //odd-numbered column by incrementing with 2
    //and check for consecutive boxes in the same column
    //that are the same color
    //Note: make sure you understand the horizontal line's
    //codes first or else everything below this point will 
    //make no sense to you
    for (int i=1;i<15;i+=2)
    {
      //Of course, our lines will look like ----__ but reversed
      //and there is need to our rows by 2 but just one
      //and we have to start at the vertical version of ----__ and 
      //and stop at _ _ ---- so it's from 0 to 2
      for (int j =0;j<3;j++)
      {
            if((f[j][i] != " ")
            && (f[j+1][i] != " ")
            && (f[j+2][i] != " ")
            && (f[j+3][i] != " ")
            && ((f[j][i] == f[j+1][i])
            && (f[j+1][i] == f[j+2][i])
            && (f[j+2][i] == f[j+3][i])))
              return f[j][i];  
      }  
    }
    
    //For the left-up to right-down diagonal line
    //We'll have to loop over the 3 uppermost
    //rows and then go from left to right column-wise
    for (int i=0;i<3;i++)
    {
      
      //As expected, our uppermost box will start from 1
      //and increase by 2 until it becomes 7 (the 3rd box
      //on a row)
      //Note how we used 1 instead 0 for the count here
      //There's no real reason to use 1 instead of 0 or 
      //vice versa, since we're still using an odd index
      //for the columns and incrementing by 2
      for (int j=1;j<9;j+=2)
      {
            if((f[i][j] != " ")
            && (f[i+1][j+2] != " ")
            && (f[i+2][j+4] != " ")
            && (f[i+3][j+6] != " ")
            && ((f[i][j] == f[i+1][j+2])
            && (f[i+1][j+2] == f[i+2][j+4])
            && (f[i+2][j+4] == f[i+3][j+6])))
              return f[i][j];  
      }  
    }
    
    //Similar to the method above, but we're just reversing our
    //trajectory, i.e. we're starting from the rightmost column
    //instead of the leftmost like we did above
    for (int i=0;i<3;i++)
    {
      for (int j=7;j<15;j+=2)
      {
            if((f[i][j] != " ")
            && (f[i+1][j-2] != " ")
            && (f[i+2][j-4] != " ")
            && (f[i+3][j-6] != " ")
            && ((f[i][j] == f[i+1][j-2])
            && (f[i+1][j-2] == f[i+2][j-4])
            && (f[i+2][j-4] == f[i+3][j-6])))
              return f[i][j];  
      }  
    }
    
    //If after going over the table and we find no
    //same colored lines, then we have to return something
    //that says that we didn't find a winning color :P
    return null;
  }
  
  //The easy part: using these methods
  public static void main (String[] args)
  {
    //Time to make a pattern
    String[][] f = createPattern();
    //Time to make a condition for our game to keep on
    //playing
    boolean loop = true;
    //We need something to keep track of whose turn it is
    int count = 0;
    printPattern(f);
    while(loop)
    {
       //Let's say that Red gets the first turn and thus
       //every other turn 
       if (count % 2 == 0) dropRedPattern(f);
       else dropYellowPattern(f);
       count++;//We need to keep track of the turns
       printPattern(f);
       //Let's say we want to check for a winner during every
       //turn made and say who it is
       if (checkWinner(f) != null)
       {
          if (checkWinner(f) == "R")
             System.out.println("The red player won.");
          else if (checkWinner(f)== "Y")
            System.out.println("The yello player won.");
         //Well, if someone one, then the game has to end
         loop = false;
    }
  }
}
}
Read More

Creating a TicTacToe game in Java

Problem:

In a game of TicTacToe, two players take turns marking an available cell in a 3 3 grid with their respective tokens (either X or O). When one player has placed three tokens in a horizontal, vertical, or diagonal row on the grid, the game is over and that player has won. A draw (no winner) occurs when all the cells on the grid have been filled with tokens and neither player has achieved a win. Create a program for playing TicTacToe. The program prompts two players to enter X token and O token alternately. Whenever a token is entered, the program redisplays the board on the console and determines the status of the game (win, draw, or continue).


Output:

-------------
|   |   |   |
-------------
|   |   |   |
-------------
|   |   |   |
-------------
Enter a row (1, 2, or 3) for player X: 2
Enter a column (1, 2, or 3) for player X: 2
-------------
|   |   |   |
-------------
|   | X |   |
-------------
|   |   |   |
-------------
Enter a row (1, 2, or 3) for player O: 1
Enter a column (1, 2, or 3) for player O: 1
-------------
| O |   |   |
-------------
|   | X |   |
-------------
|   |   |   |
-------------
Enter a row (1, 2, or 3) for player X: 1
Enter a column (1, 2, or 3) for player X: 3
-------------
| O |   | X |
-------------
|   | X |   |
-------------
|   |   |   |
-------------
Enter a row (1, 2, or 3) for player O: 3
Enter a column (1, 2, or 3) for player O: 1
-------------
| O |   | X |
-------------
|   | X |   |
-------------
| O |   |   |
-------------
Enter a row (1, 2, or 3) for player X: 2
Enter a column (1, 2, or 3) for player X: 1
-------------
| O |   | X |
-------------
| X | X |   |
-------------
| O |   |   |
-------------
Enter a row (1, 2, or 3) for player O: 2
Enter a column (1, 2, or 3) for player O: 3
-------------
| O |   | X |
-------------
| X | X | O |
-------------
| O |   |   |
-------------
Enter a row (1, 2, or 3) for player X: 1
Enter a column (1, 2, or 3) for player X: 2
-------------
| O | X | X |
-------------
| X | X | O |
-------------
| O |   |   |
-------------
Enter a row (1, 2, or 3) for player O: 3
Enter a column (1, 2, or 3) for player O: 2
-------------
| O | X | X |
-------------
| X | X | O |
-------------
| O | O |   |
-------------
Enter a row (1, 2, or 3) for player X: 3
Enter a column (1, 2, or 3) for player X: 3
-------------
| O | X | X |
-------------
| X | X | O |
-------------
| O | O | X |
-------------
No one has won!

Solution:

import java.util.Scanner;

public class TicTacToe
{  
  /** Before you begin with reading the solution, note this is
   how the tic tac toe
   board is going to look:
  -------------
  |   |   |   |
  -------------
  |   |   |   |
  -------------
  |   |   |   |
  -------------   */
  public static String[][] fillEmptyArray()
  {
    String[][] str = new String[7][13];
    //Why 13? Because count the characters between 
    //the parentheses, you'll get 13: ("|   |   |   |")
    for (int i = 0; i< str.length; i++)
    {
      for (int j =0; j <str[i].length;j++)
      {
        if (i % 2 == 0) str[i][j]= "-";
        else if (i % 2 != 0 && (j==0 || j == 4 || j == 8 || j ==12))
            //The indexes of "|" in the array are: 0,4,8 and 12
          str[i][j]="|";
        else
          str[i][j]=" ";
        
      }
    }
    return str;
  }

  public static String[][] playGameX (String[][] str)
  {
    String[][] str1 = str;
    Scanner scan =  new Scanner (System.in);
    boolean doItAgain = true;
    while (doItAgain)
    {
    System.out.print("Enter a row (1, 2, or 3) for player X: ");
    //We add -1 to deal with the index of the two-dimensional array
    int row = 2*(scan.nextInt() - 1) +1 ;
    //Don't freak out! We used 2n + 1, and we'll tell why:
    //1, 3 and 5 are the real row indexes of where X will be placed,
    //they are distinct from the user input, reason of adding formula.
    //If the user enters 1: 2(1-1) + 1 = 1  
    //If the user enters 2: 2(2-1) + 1 = 3
    //If the user enters 3: 2(3-1) + 1 = 5
    //The program we make will insert the number of 
    //column in the corresponding
    //array, this is why we used the formula.
    System.out.print("Enter a column (1, 2, or 3) for player X: ");
    int column = ( 4*(scan.nextInt()-1) + 2 );
    //Again! Don't freak out! We used 4n + 2, and we'll tell why:
    //("| 2 | 6 | 10 |"), those are the column indexes of where
    // X will be placed
    //If the user enters 1: 4(1-1) + 2 = 2 
    //If the user enters 2: 4(2-1) + 2 = 6
    //If the user enters 2: 4(3-1) + 2 = 10
    //The program we make will insert the number of column 
    //in the corresponding
    //array, this is why we used the formula.
    if ( str1[row][column] == " ")
    {
    str1[row][column] = "X";
    doItAgain = false;
    }
    else
      System.out.println("An X/O is already there, try again!");
    }
    return str1;
  }
  //playGameO is 100% identical to playGameX, instead replace X with O;
  public static String[][] playGameO (String[][] str)
  {
    String[][] str1 = str;
    Scanner scan =  new Scanner (System.in);
    System.out.print("Enter a row (1, 2, or 3) for player O: ");
    //We add -1 to deal with the index of the two-dimensional array
    int row = 2*(scan.nextInt() - 1) +1 ;
    //Don't freak out! We used 2n + 1, and we'll tell why:
    //1, 3 and 5 are the real row indexes of where O will be placed,
    //they are distinct from the user input, this is why we add 
    //the formula
    //If the user enters 1: 2(1-1) + 1 = 1  
    //If the user enters 2: 2(2-1) + 1 = 3
    //If the user enters 3: 2(3-1) + 1 = 5
    //The program we make will insert the number of column in the 
    //corresponding array, this is why we used the formula.
    System.out.print("Enter a column (1, 2, or 3) for player O: ");
    int column = ( 4*(scan.nextInt()-1) + 2 );
    //Again! Don't freak out! We used 4n + 2, and we'll tell why:
    //("| 2 | 6 | 10 |"), those are the column indexes of O:
    //If the user enters 1: 4(1-1) + 2 = 2 
    //If the user enters 2: 4(2-1) + 2 = 6
    //If the user enters 2: 4(3-1) + 2 = 10
    //The program we make will insert the number of column in the
    //array, this is why we used the formula.
    if ( str1[row][column] == " ")
    str1[row][column] = "O";
    else
      System.out.println("Invalid input! An X/O is already there.");
    return str1;
  }
  
  public static String checkForWinner(String[][] str)
  {
    for (int i =1;i<str.length; i+= 2)
    {
      if ( ( str[i][2] == str[i][6]) && ( str[i][6] == str[i][10]) 
       && str[i][2] != " " && str[i][6] != " " && str[i][10] != " ")
          return str[i][2];
    }
    
    for (int j =2;j<str[1].length; j+=4)
    {
      if ( ( str[1][j] == str[3][j]) && ( str[3][j] == str[5][j]) && 
           str[1][j] != " " && str[3][j] != " " && str[5][j] != " ")
        return str[1][j];
    }
    
    if (  (str[1][2] == str[3][6]) && (str[3][6] == str[5][10])   && 
          str[1][2] != " " && str[3][6] != " " && str[5][10] != " "  )
      return str[1][2];
    
    if (   (str[1][10] == str[3][6]) && (str[3][6] == str[5][2])  &&
          str[1][10] != " " && str[3][6] != " " && str[5][2] != " " )
      return str[1][10];
    
    return "zero";
  }
  
  public static void printArray(String[][] str)
  {
    //I guess this is the easiest method
    for (int i =0;i < str.length;i++)
    {
      for (int j =0;j < str[i].length;j++)
      {
        System.out.print(str[i][j]);
      }
      System.out.println();
    }
  }
  public static void main (String[] args)
  {
    boolean play = true;
    String[][] original = fillEmptyArray();
    printArray(original);
    int XorY = 0;
    String[][] updated;
    while (play)
    {
    if (XorY % 2 == 0)
      updated = playGameX(original);
    else
      updated = playGameO(original);
    XorY++;
    printArray(updated);
    if (checkForWinner(updated) != "zero")
    {
      System.out.print(checkForWinner(updated) + " have won");
      play = false;
    }
    if (XorY > 8 )
    {
      play = false;
      System.out.println("No one has won!");
    }

  }
}
}
Read More

Financial Tsunami Banks Problem in Java

Problem:

Banks lend money to each other. In tough economic times, if a bank goes bankrupt, it may not be able to pay back the loan. A bank’s total assets are its current balance plus its loans to other banks. The figure below is a diagram that shows five banks. The banks’ current balances are 25, 125, 175, 75, and 181 million dollars, respectively. The directed edge from node 1 to node 2 indicates that bank 1 lends 40 million dollars to bank 2. Here's a descriptive picture:




If a bank’s total assets are under a certain limit, the bank is unsafe. The money it borrowed cannot be returned to the lender, and the lender cannot count the loan in its total assets. Consequently, the lender may also be unsafe, if its total assets are under the limit. Write a program to find all unsafe banks. Your program reads the input as follows. It first reads two integers n and limit, where n indicates the number of banks and limit is the minimum total assets for keeping a bank safe. It then reads n lines that describe the information for n banks with id from 0 to n-1. The first number in the line is the bank’s balance, the second number indicates the number of banks that borrowed money from the bank, and the rest are pairs of two numbers. Each pair describes a borrower. The first number in the pair is the borrower’s id and the second is the amount borrowed. For example, the input for the five banks in Figure 7.8 is as follows (note that the limit is 201):

5 201
25 2 1 100.5 4 320.5
125 2 2 40 3 85
175 2 0 125 3 75
75 1 0 125
181 1 2 125

The total assets of bank 3 are (75 + 125), which is under 201. So bank 3 is unsafe. After bank 3 becomes unsafe, the total assets of bank 1 fall below (125 + 40). So, bank 1 is also unsafe. The output of the program should be: Unsafe banks are 3 1 (Hint: Use a two-dimensional array borrowers to represent loans.
borrowers[i][j] indicates the loan that bank i loans to bank j. Once bank j becomes unsafe, borrowers[i][j] should be set to 0.)


Solution:

import java.util.Scanner;

public class Tsunami
{
  public static void main (String[] args)
  {
    Scanner scan = new Scanner (System.in);
    int banks = scan.nextInt();
    double[] b = new double[banks];
    double[][] borrowsers = new double[5][5];
    int limit = scan.nextInt();
    for (int i =0;i<b.length;i++)
    {
      b[i] = scan.nextDouble();
      int howmany = scan.nextInt();
      for (int j =0;j<howmany;j++)
      {
        borrowsers[i][scan.nextInt()] = scan.nextDouble();
      }
    }
    
  for (int j =0;j<banks;j++)
  {
    for (int k =0; k<banks;k++)
    {
      int total =0;
      //Calculating total number of loans given by k
      for (int l =0;l<banks;l++)
      {
        total +=borrowsers[k][l];
      }
      if (total + b[k] < limit)
      {
        for (int m =0;m<banks;m++)
        {
          borrowsers[m][k] = 0;
        }
      }
    }
  }
  
  System.out.print("Unsafe banks are ");
  for (int k =0; k<banks;k++)
  {
    int total =0;
    //Calculating total number of loans made by k
    for (int l =0;l<banks;l++)
    {
      total +=borrowsers[k][l];
    }
    if (total + b[k] < limit)
    {
      System.out.print(k + " ");
    }
  }
}
}
Read More

Randomly Filling a TicTacToe board in Java

Problem:

Write a program that randomly fills in 0s and 1s into a TicTacToe board, prints the board, and finds the rows, columns, or diagonals with all 0s or 1s. Use a two-dimensional array to represent a TicTacToe board.


Output:

101
111
110
All 1s on column 0
All 1s on row 1
All 1s on diagonal 1

Solution:

public class TicTacToe2
{
  public static int[][] randomFill()
  {
    int[][] tictactoe = new int[3][3];
    for (int i =0;i<tictactoe.length;i++)
    {
      for (int j =0; j< tictactoe[i].length;j++)
      {
        tictactoe[i][j] = (int) (Math.random()*2);
        System.out.print(tictactoe[i][j]);
      }
      System.out.println();
    }
    return tictactoe;
  }
  
  public static void checkUp(int[][] tictactoe)
  {
    for (int i =0;i<3;i++)
    {
        if ( tictactoe[i][0] == tictactoe[i][1] && tictactoe[i][1] == tictactoe[i][2])
          System.out.println("All " + tictactoe[i][0] + "s on row " + i);
        
        if ( tictactoe[0][i] == tictactoe[1][i] && tictactoe[1][i] == tictactoe[2][i])
          System.out.println("All " + tictactoe[0][i] + "s on column " + i);
        
    }
    if ( tictactoe[0][0] == tictactoe[1][1] && tictactoe[1][1] == tictactoe[2][2])
      System.out.println("All " + tictactoe[0][0] + "s on diagonal " + 0);
    
    if ( tictactoe[1][2] == tictactoe[1][1] && tictactoe[1][1] == tictactoe[2][1])
      System.out.println("All " + tictactoe[0][0] + "s on diagonal " + 1);
  }
  public static void main (String[] args)
  {
    int[][] tictactoe = randomFill();
    checkUp(tictactoe);
  }
}
Read More

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact