Showing posts with label arrays. Show all posts
Showing posts with label arrays. Show all posts

Implementing the Josephus Problem in Java

Problem:

This problem is based upon a report by the historian Joseph ben Matthias (Josephus) on the
outcome of a suicide pact that he had made between himself and 40 soldiers as they were
besieged by superior Roman forces in 67 A.D. Josephus proposed that each man slay his neighbor.
This scheme necessarily leaves one to kill himself. Josephus cleverly contrived to be that
one, thus surviving to tell the tale.

Output:

[A, B, C, D, E, F, G, H, I, J, K]
A killed B
C killed D
E killed F
G killed H
I killed J
K killed A
C killed E
G killed I
K killed C
G killed K
The lone survivor is G

Solution:

public class Josephus {
public static final int SOLDIERS = 8;
public static final String ALPHA = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
public static void main(String[] args) {
Ring<String> ring = new Ring<String>();
for (int i=0; i<SOLDIERS; i++) {
ring.add(ALPHA.substring(i, i+1));
}
System.out.println(ring);
Iterator<String> it = ring.iterator();
String killer = it.next();
while (ring.size() > 1) {
String victim = it.next();
System.out.println(killer + " killed " + victim);
it.remove();
killer = it.next();
}
System.out.println("The lone survivor is " + it.next());
}
}
Read More

Using the sublist() Method as a Range-View Operation

Problem:

Use the sublist() in a java program as Method as a Range-View Operation

Output:

[A, B, C, D, E, F, G, H, I, J]
list.subList(3,8): [D, E, F, G, H]
list.subList(3,8).get(2): F
list.subList(3,8).set(2,"B"):
[A, B, C, D, E, B, G, H, I, J]
list.indexOf("B"): 1
list.subList(3,8).indexOf("B"): 2
[A, B, C, D, E, B, G, H, I, J]
Collections.reverse(list.subList(3,8)):
[A, B, C, H, G, B, E, D, I, J]
Collections.rotate(list.subList(3,8), 2):
[A, B, C, E, D, H, G, B, I, J]
Collections.fill(list.subList(3,8), "X"):
[A, B, C, X, X, X, X, X, I, J]
[A, B, C, I, J]

Solution:

public class TestSubList {
public static void main(String[] args) {
List list = new ArrayList();
Collections.addAll(list, "A","B","C","D","E","F","G","H","I","J");
System.out.println(list);
System.out.println("list.subList(3,8): " + list.subList(3,8));
System.out.println("list.subList(3,8).get(2): "
+ list.subList(3,8).get(2));
System.out.println("list.subList(3,8).set(2,\"B\"):");
list.subList(3,8).set(2, "B");
System.out.println(list);
System.out.println("list.indexOf(\"B\"): " + list.indexOf("B"));
System.out.println("list.subList(3,8).indexOf(\"B\"): "
+ list.subList(3,8).indexOf("B"));
System.out.println(list);
System.out.println("Collections.reverse(list.subList(3,8)):");
Collections.reverse(list.subList(3,8));
System.out.println(list);
1System.out.println("Collections.rotate(list.subList(3,8), 2):");
Collections.rotate(list.subList(3,8), 2);
System.out.println(list);
System.out.println("Collections.fill(list.subList(3,8), \"X\"):");
Collections.fill(list.subList(3,8), "X");
System.out.println(list);
list.subList(3,8).clear();
System.out.println(list);
}
}
Read More

Testing a List Class in Java

Problem:

Write a program that implements an LinkedQueue in java.

Output:

[GB, DE, FR, ES]
[GB, DE, FR, DE, ES]
list.get(3): DE
list.indexOf("DE"): 1
list.indexOf("IE"): -1
list.subList(1, 5): [DE, FR, DE, ES]
[GB, FR, DE, ES]

Solution:

public class TestStringList {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
Collections.addAll(list, "GB", "DE", "FR", "ES");
System.out.println(list);
list.add(3, "DE");
System.out.println(list);
System.out.println("list.get(3): " + list.get(3));
System.out.println("list.indexOf(\"DE\"): " + list.indexOf("DE"));
System.out.println("list.indexOf(\"IE\"): " + list.indexOf("IE"));
System.out.println("list.subList(1, 5): " + list.subList(1, 5));
list.remove("DE");
System.out.println(list);
}
}
Read More

Implementing an LinkedQueue class in java

Problem:

Write a program that implements an LinkedQueue in java.

Output:

Not available.

Solution:

public class LinkedQueue<E> implements Queue<E> {
private Node<E> head = new Node<E>(); // dummy node
private int size;

public void add(E element) {
head.prev = head.prev.next = new Node<E>(element, head.prev, head);
++size;
}

public E element() {
if (size == 0) {
throw new java.util.EmptyStackException();
}
return head.next.element; // front of queue // next <--> prev
}
public boolean isEmpty() {
return (size == 0);
}

public E remove() {
if (size == 0) {
throw new java.util.EmptyStackException();
}
E element = head.next.element; // next <--> prev
head.next = head.next.next; // next <--> prev
head.next.prev = head; // next <--> prev
--size;
return element;
}
public int size() {
return size;
}
private static class Node<E> {
E element;
Node<E> prev;
Node<E> next;
Node() {
this.prev = this.next = this;
}
Node(E element, Node<E> prev, Node<E> next) {
this.element = element;
this.prev = prev;
this.next = next;
}
}
}
Read More

Implementing an ArrayQueue in java

Problem:

Write a program that implements an ArrayQueue in java.

Output:

Not available.

Solution:

public class ArrayQueue<E> implements Queue<E> {
private E[] elements;
private int front;
private int back;
private static final int INITIAL_CAPACITY = 4;

public ArrayQueue() {
elements = (E[]) new Object[INITIAL_CAPACITY];
}

public ArrayQueue(int capacity) {
elements = (E[]) new Object[capacity];
}

public void add(E element) {
if (size() == elements.length - 1) {
resize();
}
elements[back] = element;
if (back < elements.length - 1) {
++back;
} else {
back = 0; //wrap
}
}

public E element() {
if (size() == 0) {
throw new java.util.NoSuchElementException();
}
return elements[front];
}

public boolean isEmpty() {
return (size() == 0);
}

public E remove() {
if (size() == 0) {
throw new java.util.NoSuchElementException();
}
E element = elements[front];
elements[front] = null;
++front;
if (front == back) { // queue is empty
front = back = 0;
}
Read More

Implementing the sequential search algorithm in java

Problem:

The sequential search (also called the linear search) is the simplest search algorithm. It is also
the least efficient. It simply examines each element sequentially, starting with the first element,
until it finds the key element or it reaches the end of the array.
If you were looking for someone on a moving passenger train, you would use a sequential
search.
Here is the sequential search algorithm:
(Postcondition: either the index i is returned where si
= x, or 1 is returned.)
1. Repeat steps 2 3, for i = 0 to n 1.
2. (Invariant: none of the elements in the subsequence {s0...si–1} is equal to x.)
3. If si = x, return i.
4. Return 1.
Implement the sequential search algorithm

Output:

{22, 33, 44, 55, 66, 77, 88, 99}
search(a, 44): 2
search(a, 50): -1
search(a, 77): 5
search(a, 100): -1

Solution:

public class TestBinarySearch {
public static void main(String[] args) {
int[] a = {22, 33, 44, 55, 66, 77, 88, 99};
ch02.ex02.DuplicatingArrays.print(a);
System.out.println("search(a, 44): " + search(a, 44));
System.out.println("search(a, 50): " + search(a, 50));
System.out.println("search(a, 77): " + search(a, 77));
System.out.println("search(a, 100): " + search(a, 100));
}
public static int search(int[] a, int x) {
// POSTCONDITIONS: returns an integer i; 
// if i >= 0, then a[i] == x; otherwise x is not in a[];
for (int i=0; i<a.length; i++) { // step 1
// INVARIANT: x is not among a[0]...a[i-1] // step 2
if (a[i] == x) { // step 3
return i;
}
}
return -1; // step 4
}
}
Read More

Duplicating an array in Java

Problem:

Write a problem that duplicates arrays by invoking the Object.clone() method.

Output:

{22, 44, 66, 88}
{22, 44, 66, 88}
{AB, CD, EF}
{AB, CD, EF}
{AB, XYZ, EF}
{AB, CD, EF}

Solution:

public class DuplicatingArrays {
public static void main(String[] args) {
int[] a = {22, 44, 66, 88};
print(a);
int[] b = (int[])a.clone(); // duplicate a[] in b[]
print(b);
String[] c = {"AB", "CD", "EF"};
print(c);
String[] d = (String[])c.clone(); // duplicate c[] in d[]
print(d);
c[1] = "XYZ"; // change c[], but not d[]
print(c);
print(d);
}

public static void print(int[] a) {
System.out.printf("{%d", a[0]);
for (int i = 1; i < a.length; i++) {
System.out.printf(", %d", a[i]);
}
System.out.println("}");
}
public static void print(Object[] a) {
System.out.printf("{%s", a[0]);
for (int i = 1; i < a.length; i++) {
System.out.printf(", %s", a[i]);
}
System.out.println("}");
}
}
Read More

20 Properties of Arrays in Java

Problem:

List the 20 properties of java arrays.

Output:

Not applicable.

Solution:

Here are the main properties of arrays in Java:
1. Arrays are objects.
2. Arrays are created dynamically (at run time).
3. Arrays may be assigned to variables of type Object.
4. Any method of the Object class may be invoked on an array.
5. An array object contains a sequence of variables.
6. The variables are called the components or elements of the array.
7. If the component type is T, then the array itself has type T[].
8. An array type variable holds a reference to the array object.
9. The component type may itself be an array type.
10. An array element is a component whose type is not an array type.
11. An element’s type may be either primitive or reference.
12. The length of an array is its number of components.
13. An array’s length is set when the array is created, and it cannot be changed.
14. An array’s length can be accessed as a public final instance variable.
15. Array index values must be integers in the range 0...length 1.
16. An ArrayIndexOutOfBoundsException is thrown if Property 15 is violated.
17. Variables of type short, byte, or char can be used as indexes.
18. Arrays can be duplicated with the Object.clone() method.
19. Arrays can be tested for equality with the Arrays.equals() method.
20. Array objects implement Cloneable and java.io.Serializable.
Read More

Reversing and sorting an array in Java

Problem:

Write a program that reads 10 values of integers from the user store them in an array of integers.
a. Then print the reverse of this array.
Example:

1 6 3 4 2 9 8 10 5 7

Reverse: 7 5 10 8 9 2 4 3 6 1
b.The program writes the array in increasing order. (Using for loops).

Increasing order: 1 2 3 4 5 6 7 8 9 10

Output:

Not applicable.

Solution:

import java.util.Scanner;

public class Prob2
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Please enter " + 10 + " numbers: ");
int[] list = new int[10];

for(int i=0; i<10; i++)
{
list[i] = scan.nextInt();
}

System.out.println("The array in reverse is: ");
for(int i=9; i>=0; i--)
{
System.out.print(list[i] + " ");
}

System.out.println();
System.out.println("The array in increassing order is: ");
for(int i=0;i<list.length;i++)
{
int temp = 0;
for(int j=0;j<list.length-1;j++)
{
if(list[j]>list[j+1])
{
temp = list[j];
list[j] = list[j+1];
list[j+1] = temp;
}
}
}
for(int i=0; i<list.length; i++)
{
System.out.print(list[i] + " ");
}


}



}
Read More

Manipulating an Array in Java (For beginners)

Problem:

Write a program where:
a) The user input the length of an array N. Then create an array of size N.
b) Fill the array with N integers that are the grades of a class of students.
c) Calculate the average of the class using a method called average()
d) Print all the values of the array, the maximum, the minimum, and the average

Output:

Not applicable

Solution:

import java.util.Scanner;

public class Prob1 {
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.print("Please enter the number of the grades you will enter: ");
int num = scan.nextInt();
int[] grades = new int[num];

for(int i=0; i<num; i++)
{
System.out.print("Enter the grade #" + (i+1) + ": ");
grades[i] = scan.nextInt();
}

PrintArray(grades);
System.out.println("Maximum is " + CalcMax(grades));
System.out.println("Minimum is " + CalcMin(grades));
System.out.println("The average is " + CalcAverage(grades));
}

public static double CalcAverage(int grades[])
{

double output = 0;
for(int grade: grades)
{
output += grade;
}

return output/grades.length;
}

public static int CalcMax(int grades[])
{
int max = grades[0];

for(int grade: grades)
{
if (grade > max)
max = grade;
}

return max;
}

public static int CalcMin(int grades[])
{

int min = grades[0];

for(int grade: grades)
{
if (grade < min)
min = grade;
}

return min;
}

public static void PrintArray(int[] grades)
{
int k = 1;
System.out.println();

for(int grade: grades)
{
System.out.println("Garde #" + k + ": " + grade);
k++;
}
}
}
Read More

Calculating Gross Sales in Java

Problem:

Use a one-dimensional array to solve the following problem: A company pays its salespeople on a commission basis. The salespeople receive a $200 per week plus 9% of their gross sales for that week. For example, a salespeople who grosses 5000$ in sales in a week receives 200$ plus 9% of 5000$, or a total of 650$. Write an application (using an array of counters) that determines how many of the salespeople earned salaries in each of the following ranges(assume that each salesperson's salary is truncated to an integer amount):
Earned salaries:
$200-$299
$300-$399
$400-$499
$500-$599
$600-$699
$700-$799
$800-$899
$900-$999
$1000 and over
Summarize the results in tabular format


Output:

Earned salaries:        Gross sales:
$200-$299               $218-$226
$300-$399               $227-$235
$400-$499               $236-$244
$500-$599               $245-$253
$600-$699               $254-$262
$700-$799               $263-$271
$800-$899               $272-$280
$900-$999               $281-$289
$1000 and over          $290 and over


Solution:

public class Problem
{
  public static void main (String[] args)
  {
    int[] nums = new int[18];
    System.out.println("Earned salaries: " + "\t" +"Gross sales: ");
    int a = 200;
    for (int i =0; i <18; i+=2)
    {
      nums[i] = a; nums[i+1] = a+99;
      a+=100;
    }
    
    for (int i =0; i <18; i+=2)
    {
      if ( i == 16)
      System.out.println("$"+nums[i] +"" +" and over" +
                        "\t\t" +"$" + (int)(nums[i]*0.09 +200)+" "+"and over");
      else
      System.out.println("$"+nums[i] +"-" +"$" + nums[i+1]
                      +"\t\t" +"$" + (int)(nums[i]*0.09 +200)+"-"+"$" +
                                                    (int)(nums[i+1]*0.09 +200));

    }
  }
}
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

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

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