Tuesday, July 15, 2014

Random Number Diamond

2.12 Lab
Write a program that prints the following diamond.
      1
   2 3 4
1 2 5 7 4
   2 3 5
      4
The printed numbers are random digits between 0 and 9. In Java, Math.random() returns
a random double that is greater than or equal to 0 and smaller than 1. The method is
defined in the library java.math.* (use import java.math.*) . Multiply this number by
something to get a digit between 0 and 9. Use int i = (int) d; to convert a double to
an int.

I had to think about how to go about doing this logically.  I can easily change the size of the diamond with one variable change.

import java.math.*;
public class Diamond{
public static void main(String[] args) {
boolean ascending = true;
int spacers = 2;//spacers per row needed
int numbers = 1;//numbers per row needed
while (numbers > 0) {//while numbers are needed
for (int i = 0; i < spacers; i++) {//loop as many times as spaces are needed
System.out.print("  ");// print spacers
}
for (int i = 0; i < numbers; i++) {//loop as many times as numbers are needed
System.out.print(" " + ((int) (Math.random() * 10)));// print random number 0-9
}
if (numbers == 5)//if reached middle
ascending = false;//stop getting wider
if (ascending) {// if ascending 
spacers--;//subtract spacers in next row
numbers=numbers+2;//add numbers in next row
} else// if descending 
{
spacers++;//add spacers in next row
numbers=numbers-2;//subtract numbers in next row
}
System.out.println();//go to next line
}}}


No comments:

Post a Comment