Showing posts with label 2D Array. Show all posts
Showing posts with label 2D Array. Show all posts

Manipulating a 2D array from a file in Java

Problem:

Using a scanner, you should read a 2D array from a file called "numbers.txt". The first line in the file will have two integers which are the number of rows and columns respectively. After reading the two integers, you should create a 2D array in your code that has the same number of rows and columns read. Then, you continue reading the 2D array from the file.

After reading the 2D array, you need to add the value of the previous column on the current row to the current column on the current row. (Hint: ADM] += A[i][j-1])

Finally, save your array to a file called "newNumbers.txt" using a formatter.

Output:

43
123
234
456
678

136
259
4915
61321

Solution:

import java.io.File;
import java.util.Formatter;
import java.util.Scanner;

public class ProblemC {

 public static void main(String args[]) {
  try {
   Scanner scan = new Scanner(new File("numbers.txt"));
   Formatter formatter = new Formatter(new File("newNumbers.txt"));
   
   int rows = scan.nextInt();
   int cols = scan.nextInt();
   
   int A[][] = new int[rows][cols];
   
   for (int i = 0; i < rows; i++)
    for (int j = 0; j < cols; j++)
     A[i][j] = scan.nextInt();
   
   for (int i = 0; i < rows; i++)
    for (int j = 1; j < cols; j++)
     A[i][j] += A[i][j-1];
   
   for (int i = 0; i < rows; i++) {
    for (int j = 0; j < cols; j++)
     formatter.format("%d ", A[i][j], true);
    
    formatter.format("\n", "", true);
   }
   
   scan.close();
   formatter.close();
   
  } catch (Exception e) {
   System.err.println("File error");
  }
 }
}
Read More

Creating a Multiplication Table in Java

Problem:

Write an application called MultiplicationTable that asks the user to input a number N then creates a 2 dimensional array of size N X N and stores inside it the table of multiplication up to N.

Output:

Enter N: 4
Outputs:
1 2 3 4
2 4 12 8
3 6 9 12
4 8 12 16

Solution:

import java.util.Scanner;
public class Problem1 {
 public static void main(String[] args)
 {
  Scanner scan = new Scanner(System.in);
  int num = scan.nextInt();
  
  int[][] table = new int[num][num];
  
  for(int i=0; i<num; i++)
  {
   for(int j=0; j<num; j++)
   {
    table[i][j] = (i+1)*(j+1);
   }
  }
  
  for(int i=0; i<num; i++)
  {
   for(int j=0; j<num; j++)
   {
    System.out.print(table[i][j] + "\t");
   }
   System.out.println();
  }
  
 }
}
Read More

Sorting a Two-dimensional Array in Java

Problem:

In a simple java problem, create a two-dimensional array, and fill it with random numbers. Then sort it.


Solution:


import java.util.Scanner;
public class TwoDimensional
{
  public static void main (String[] args)
  {
    int[][] nums = { {6,4,8,1},

                      {64,76,1,7},

                      {43,87,23,45},

                      {100,56,233,5}};
    int temp =0;//For later use
    int j=0,k =0;
    for (int i =0;i<nums.length*nums[0].length;i++)
    {
      for (j =0;j<nums.length;j++)
      {
        for (k =0;k<nums[j].length-1;k++)
        {
          if (nums[j][k] > nums[j][k+1])
          {
            temp = nums[j][k];
            nums[j][k] = nums[j][k+1];
            nums[j][k+1] = temp;
          }
        }
        if (j != nums.length-1 && nums[j][k] > nums[j+1][0])
        {
          temp = nums[j][k];
          nums[j][k] = nums[j+1][0];
          nums[j+1][0] = temp;
        }
      }
    }
    for (int i = 0;i<nums.length;i++)
    {
      for (j =0;j<nums[i].length;j++)
      {
        System.out.print(nums[i][j] +" ");
      }
      System.out.println();
    }
  }
}
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

Sorting two-dimensional array in java

This exercise can be found in the book "Introduction to Java Programming - 8th edition" by Y. Daniel Liang. No copyright infringement intended.


(Sorting two-dimensional array) Write a method to sort a two-dimensional array using following header:
public static void sort(int m[][])
The method performs a primary sort on rows and a secondary sort on columns


  import java.util.Scanner;

public class SortingTwoDimensionalArray
{
  public static int[][] sort(int[][] m)
  {
    for (int i =0;i<m.length;i++)
    {
      for (int j =0;j<m.length-1;j++)
      {
      if (m[j][0] >m[j+1][0])
      {
        int temp = m[j][0];
        int temp1 = m[j][1];
        m[j][0]= m[j+1][0];
        m[j][1]= m[j+1][1];
        m[j+1][0] = temp;
        m[j+1][1] = temp1;
      }
      
      if (m[j][0] == m[j+1][0])
      {
        if(m[j][1] >m[j+1][1])
        {
          int temp3 = m[j][1];
          m[j][1] = m[j+1][1];
          m[j+1][1] = temp3;
        }
      }

      }
    }
    return m;
  }
  //Just a test
  public static void main (String[] args)
  {
    int[][] m = { {4,2},{1,7},{4,5},{1,2},{1,1},{4,1}};
    sort(m);
    for (int i =0;i<m.length;i++)
    {
      for (int j =0;j<m[i].length;j++)
      {
        System.out.print(m[i][j] + " ");  
      }
      System.out.println();
    }
  }
}
Read More

Check if Two Points are on the Same Line in Java

Problem:

Suppose a set of points are given. Write a program to check whether all the points are on the same line. Use the following sets to test your program:

double[][] set1 = {{1, 1}, {2, 2}, {3, 3}, {4, 4}};

double[][] set2 = {{0, 1}, {1, 2}, {4, 5}, {5, 6}};

double[][] set3 = {{0, 1}, {1, 2}, {4, 5}, {4.5, 4}};


Output:

How many points do you want to check? 5
Enter point 1 coordinates: 0 1
Enter point 2 coordinates: 1 2
Enter point 3 coordinates: 4 5

Enter point 4 coordinates: 4.5 4
Enter point 5 coordinates: 0 1
Numbers are not on the same line


Solution:

import java.util.Scanner;
public class SameLine
{
  public static boolean sameLine(double[][] sum)
  {
    double slope = (sum[1][1] - sum[0][1]) / (sum[1][0] - sum[0][0]);
    for (int i = 0;i<sum.length;i++)
    {
      for (int j =0;j<sum.length-1;j++)
      {
      if ((sum[j+1][1] - sum[j][1]) /
          (sum[j+1][0] - sum[j][0]) != slope )
        return false;
      }
    }
    return true;
  }
  public static void main (String[] args)
  {
    Scanner scan = new Scanner(System.in);
    System.out.print("How many points do you want to check? ");
    double[][] points = new double[scan.nextInt()][2];
    for (int i =0;i<points.length;i++)
    {
      System.out.print("Enter point " + (i+1) 
                + " coordinates: ");
      points[i][0] = scan.nextDouble();
      points[i][1] = scan.nextDouble();
    }
    if (sameLine(points)) System.out.println("Points are on the same line");
    else
      System.out.println("Numbers are not on the same line");
    
    
  }
}
Read More

Exploring Matricies in Java

Problem:

Write a program that prompts the user to enter the length of a square matrix, randomly fills in 0s and 1s into the matrix, prints the matrix, and finds the rows, columns, and diagonals with all 0s or 1s.


Output:

Enter the size for the matrix: 4
1000
0111
0101
0100
No same numbers on a column
No same numbers on a row
No same numbers on the major diagonal
No same numbers on the sub-diagonal


Solution:

import java.util.Scanner;
public class ExploringMatrix
{
  public static void main (String[] args)
  {
    Scanner scan = new Scanner(System.in);
    System.out.print("Enter the size for the matrix: ");
    int size = scan.nextInt();
    int[][] m = new int[size][size];
    
    for (int i =0;i<size;i++)
    {
      for (int j =0;j<size;j++)
      {
        m[i][j] = (int) (Math.random()*2);
        System.out.print(m[i][j]);
      }
      System.out.println();
    }
    boolean letitbe;
    //Row
    int j =0;
    
    boolean row=false, column=false, major =false, sub = false;
    for(int i=0; i<size;i++)
    {
      letitbe = true;
      for (j =0;j<size-1;j++)
      {
        if (m[i][j] != m[i][j+1]) letitbe = false;
      }
      if (letitbe)
      {
        System.out.println("All " + m[i][j] + "s on row " + i);
        row = true;
      }
    }
    //Column
    for(int i=0; i<size;i++)
    {
      letitbe = true;
      for (j =0;j<size-1;j++)
      {
        if (m[j][i] != m[j+1][i]) letitbe = false;
      }
      if (letitbe)
      {
        System.out.println("All " + m[j][i] + "s on column " + i);
        column = true;
      }
      
    }
    //Major diagonal, there is only one eh?
    letitbe = true;
    for (int  i=0;i<size-1;i++)
    {
      if (m[i][i]!= m[i+1][i+1]) letitbe = false;
    }
    if (letitbe)
    {
      System.out.println("All " + m[0][0] + "s on major diagonal");
      major = true;
    }
    
    letitbe = true;
    for (int  i=0;i<size-1;i++)
    {
      if (m[i][size-i-1]!= m[i+1][size-i-1-1]) letitbe = false;
    }
    if (letitbe)
    {
      System.out.println("All " + m[0][size-1] + "s on sub-diagonal");
      sub = true;
    }
  
    if ( column == false) System.out.println("No same numbers on a column");
    if ( row == false) System.out.println("No same numbers on a row");
    if ( major == false) System.out.println("No same numbers on the major diagonal");
    if ( sub == false) System.out.println("No same numbers on the sub-diagonal");
  }
}
Read More

Returning the Largest Element of a Two-Dimensional Array in java

Problem:

Write the following method that returns the location of the largest element in a two-dimensional array.

public static int[] locateLargest(double[][] a)

The return value is a one-dimensional array that contains two elements. These two elements indicate the row and column indices of the largest element in the two dimensional array. Write a test program that prompts the user to enter a two-dimensional array and displays the location of the largest element in the array.


Output:

23.5 35 2 10
4.5 3 45 3.5
35 44 5.5 9.6

The location of the largest element is at (1, 2)


Solution:

  import java.util.Scanner;
  
public class LargestElement
{
  public static int[] locateLargest(double[][] a) 
  {
    double max = a[0][0];
    int i1 =0,j1=0;
    for (int i= 0;i <a.length;i++)
    {
      for (int j =0; j<a[i].length;j++)
      {
        if (a[i][j] > max)
        {
          max = a[i][j];
          i1 =i;
          j1 =j;
        }
      }
    }
    int[] bla = {i1,j1};
    return bla;
  }
  
  public static void main (String[] args)
  {
    Scanner scan = new Scanner (System.in);
    System.out.print("Enter the number of rows " +
                               "and columns of the array: ");
    double[][] nums = new double[scan.nextInt()][scan.nextInt()];
    System.out.println("Enter the array:");
    for (int i =0;i<nums.length;i++)
    {
      for (int j =0;j<nums[i].length;j++)
      {
        nums[i][j] = scan.nextDouble();
      }
    }
    int[] zizi = locateLargest(nums);
    System.out.println("The location of the largest element " +
        "is at (" + zizi[0] +", " +zizi[1] +")");
  }
}
Read More

Computing Taxes in Java

Problem:

Rewrite a program that compute taxes using arrays. For each filing status, there are six tax rates. Each rate is applied to a certain amount of taxable income. For example, from the taxable income of $400,000 for a single filer, $8,350 is taxed at 10%, (33,950 – 8,350) at 15%, (82,250 – 33,950) at 25%, (171,550 – 82,550) at 28%, (372,550 – 82,250) at 33%, and (400,000 – 372,950) at 36%. The six rates are the same for all filing statuses, which can be represented in the following array:

double[] rates = {0.10, 0.15, 0.25, 0.28, 0.33, 0.35};

The brackets for each rate for all the filing statuses can be represented in a two dimensional array as follows:

int[][] brackets = {
{8350, 33950, 82250, 171550, 372950}, // Single filer
{16700, 67900, 137050, 20885, 372950}, // Married jointly
{8350, 33950, 68525, 104425, 186475}, // Married separately
{11950, 45500, 117450, 190200, 372950} // Head of household
};

Suppose the taxable income is $400,000 for single filers. The tax can be computed
as follows:
tax = brackets[0][0] * rates[0] +
(brackets[0][1] – brackets[0][0]) * rates[1] +
(brackets[0][2] – brackets[0][1]) * rates[2] +
(brackets[0][3] – brackets[0][2]) * rates[3] +
(brackets[0][4] – brackets[0][3]) * rates[4] +
(400000 – brackets[0][4]) * rates[5]


Output:

How much money do you make? 10000
Enter 0 if you are single filder,
1 if you are married jointly,
2 if you are married seperately,
and 3 if you are head of household.
0
Taxes are 1082.5


Solution:

import java.util.Scanner;

public class ComputingTax
{
  public static void main (String[] args)
  {
    Scanner scan = new Scanner (System.in);
    System.out.print("How much money do you make? ");
    int salary = scan.nextInt();
    System.out.println("Enter 0 if you are single filder,");
    System.out.println("1 if you are  married jointly,");
    System.out.println("2 if you are married seperately,");
    System.out.println("and 3 if you are head of household.");
    int i = scan.nextInt();
    double tax = 0;
    int[][] brackets = {
        {8350, 33950, 82250, 171550, 372950}, // Single filer
        {16700, 67900, 137050, 20885, 372950}, // Married jointly
        {8350, 33950, 68525, 104425, 186475}, // Married separately
        {11950, 45500, 117450, 190200, 372950} // Head of household
        };
    
    double[] rates = {0.10, 0.15, 0.25, 0.28, 0.33, 0.35};
    if (salary > brackets[i][4])
    tax =   ((brackets[i][0] - 000000000000000) * rates[0]) + 
        ((brackets[i][1] - brackets[i][0]) * rates[1]) + 
        ((brackets[i][2] - brackets[i][1]) * rates[2]) + 
        ((brackets[i][3] - brackets[i][2]) * rates[3]) + 
        ((brackets[i][4] - brackets[i][3]) * rates[4])+ 
        ((salary - brackets[i][4]) * rates[5]);
    
    else if (salary > brackets[i][3])
      tax =   ((brackets[i][0] - 000000000000000) * rates[0]) + 
      ((brackets[i][1] - brackets[i][0]) * rates[1]) + 
      ((brackets[i][2] - brackets[i][1]) * rates[2]) + 
      ((brackets[i][3] - brackets[i][2]) * rates[3]) + 
      ((salary - brackets[i][3]) * rates[4]);
    
    else if (salary > brackets[i][2])
      tax =   ((brackets[i][0] - 000000000000000) * rates[0]) + 
      ((brackets[i][1] - brackets[i][0]) * rates[1]) + 
      ((brackets[i][2] - brackets[i][1]) * rates[2]) + 
      ((salary - brackets[i][2]) * rates[3]);
    
    else if (salary > brackets[i][1])
      tax =   ((brackets[i][0] - 000000000000000) * rates[0]) + 
      ((brackets[i][1] - brackets[i][0]) * rates[1]) +
      ((salary - brackets[i][1]) * rates[2]);
    
    else if (salary > brackets[i][0])
      tax =   ((brackets[i][0] - 000000000000000) * rates[0]) + 
      ((salary - brackets[i][0]) * rates[1]);

    System.out.println("Taxes are " + tax);
  }
}
Read More

Finding Heads and Tails of a Number in Java

Problem:

Nine coins are placed in a 3-by-3 matrix with some face up and some face down. You can represent the state of the coins using a 3-by-3 matrix with values 0 (head) and 1 (tail). Here are some examples:

0 0 0       1 0 1       1 1 0        1 0 1        1 0 0
0 1 0       0 0 1       1 0 0        1 1 0        1 1 1
0 0 0       1 0 0       0 0 1        1 0 0        1 1 0

Each state can also be represented using a binary number. For example, the preceding matrices correspond to the numbers:

000010000 101001100 110100001 101110100 100111110

There are a total of 512 possibilities. So, you can use decimal numbers 0, 1, 2, 3,
and 511 to represent all states of the matrix. Write a program that prompts the
user to enter a number between 0 and 511 and displays the corresponding matrix
with characters H and T.


Output:

Enter a number between 0 and 511
458


T T T
H H T
H T H


Solution:

  import java.util.Scanner;
public class HeadsAndTails
{
  public static int[] decimalToBinary(int decimal)
  {
  int[] nums = new int[9];
  for (int i = nums.length-1;i>=0 && decimal >0;i--)
  {
    if ( decimal% 2 == 0)
      nums[i] = 0;
    else 
      nums[i] = 1;
    decimal /= 2;
  }
  return nums;
  }

  public static void printHeadsAndTails(int[] nums)
  {
    for (int i =0; i<9;i++)
    {
      if (nums[i] == 0) System.out.print("H ");
      else  System.out.print("T ");
      if ((i+1) % 3 == 0) System.out.println();
      
    }
  }
  public static void main (String[] args)
  {
    Scanner scan = new Scanner (System.in);
    System.out.println("Enter a number between 0 and 511");
    int number = scan.nextInt();
    int[] nums = decimalToBinary(number);
    printHeadsAndTails(nums);
  }
}
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

Multiplying Two Matrices in Java

Problem:

Write a program to multiply two matrices.


Output:

Enter matrix1: 5 3 9 0 6 5 2 3 5
Enter matrix2: 0 4 2 9 5 3 1 0 5
5.0 3.0 9.0     0.0 4.0 2.0     36.0 35.0 64.0
0.0 6.0 5.0  x  9.0 5.0 3.0  =  59.0 30.0 43.0
2.0 3.0 5.0     1.0 0.0 5.0     32.0 23.0 38.0


Solution:

 import java.util.Scanner;

public class MultiplyMatricies
{
  public static double[][] multiplyMatrix(double[][] a, double[][] b)
  {
    double[][] c = new double[3][3];
    for (int i =0;i<c.length;i++)
    {
      for (int j =0;j<c[i].length;j++)
      {
        c[i][j] = a[i][0]*b[0][j] + 
              a[i][1]*b[1][j] + 
              a[i][2]*b[2][j];
      }
    }
    return c;
  }
  public static double[][] scanA()
  {
  System.out.print("Enter matrix1: ");
  Scanner scan = new Scanner (System.in);
  double[][] a = new double[3][3];
  for (int i =0;i<a.length;i++)
  {
    for (int j =0;j<a[i].length;j++)
    {
      a[i][j]= scan.nextInt();
    }
  }
    return a;
  }
  
  public static double[][] scanB()
  {
    System.out.print("Enter matrix2: ");
  Scanner scan = new Scanner (System.in);
  double[][] b = new double[3][3];
  for (int i =0;i<b.length;i++)
  {
    for (int j =0;j<b[i].length;j++)
    {
      b[i][j]= scan.nextInt();
    }
  }
    return b;
  }
  
  public static void printMatrix(double[][] a,double[][] b, double[][] c)
  {
    for (int i =0; i< a.length;i++)
    {
      for (int j =0;j< a[i].length;j++)
      {
        System.out.print(a[i][j] + " ");
      }
      if ( i ==1)
      System.out.print("  x  ");
      else 
      System.out.print("     ");
      for (int j =0;j< b[i].length;j++)
      {
        System.out.print(b[i][j] + " ");
      }
      if ( i ==1)
      System.out.print("  =  ");
      else 
      System.out.print("     ");
      for (int j =0;j< c[i].length;j++)
      {
        System.out.print(c[i][j] + " ");
      }
      
      System.out.println();
    }
  }
  
  public static void main (String[] args)
  {
    
    double[][] a= scanA();
    double[][] b= scanB();
    double[][] c = multiplyMatrix(a,b);
    printMatrix(a,b,c);
  }
}
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