Printing an array in a table format - java

I have an array filled with 50 numbers and cannot figure how to output the array into a table like format.
Currently when I print my array it is being outputted into one long line of numbers, and what I am aiming for is 10 lines, each consisting of 5 numbers.
Furthermore I would prefer each value to be a 3 digit value. So 1 would be represented as 001, to improve readability and presentation.
import java.util.*;
public class Random50 {
public static void main (String[] args)
{
final int MAX_SIZE = 50;
int[] r50 = new int[MAX_SIZE];
Random rand = new Random();
for (int i=0; i<r50.length; i++)
{
r50[i] = rand.nextInt(1000);
for (int j=0;j<i;j++)
{
if (j!=i && r50[i] == r50[j])
{
System.out.println("Duplicate: " + r50[i]);
r50[i] = rand.nextInt(1000);
}
}
}
System.out.printf(Arrays.toString(r50));
}
}

You really should only ask 1 question per post so I'll answer your first question - it makes it so other users can find relevant information in the future (not trying to be mean).
If you want to start printing on a new line every fifth number you could make use of the modulus operator %.
for(int i = 0; i < 50; i++){
if(i % 5 == 0){ // True every fifth value
System.out.print("\n"); // Print a new line
}
... // Your other code goes here
}

Related

What is this method doing? (Arrays and random numbers)

My textbook gave me this code to help count the amount of times a certain number shows up in an array of integers. I tried to apply the code my textbook gave me to my assignment but it doesn't seem to be working. Basically, I have to generate 30 random integers in an array, with the upper bound being 15 and lower bond being -5.
I want to find out how many times a number in the array is equal to 0, 1, 2... all the way until 10. The first code is the one my textbook gave me. They also used a random number generator but instead of finding how many elements is equal to 0, 1, etc, they want to find how many times each number appears. (The scores array is simply the random number generator, and their upper bound is 100). The second code is mine.
int[] counts = new int [100];
for (int i = 0; i < scores.length; i++) {
int index = scores[i];
counts[index]++;
}
//This is my code
public static void main(String[] args) {
int []a = arrayHist ();
printArray (a);
}
public static int randomInt (int low, int high) {
int range = (high - low) +1;
return (int) (Math.random() * range) + low;
}
public static int[] randomIntArray (int x) {
int[] random = new int[x];
for (int i = 0; i< x; i++) {
random [i] = randomInt (-5, 15);
}
return random;
}
public static int[] arrayHist () {
int[] counts = new int [30];
int[] hist = randomIntArray (30);
for (int i = 0; i < 10 && i >= 0; i++) {
int index = hist[i];
counts[index]++;
}
return hist;
}
public static void printArray (int[] a) {
for (int i = 0; i < a.length; i++) {
System.out.println (a[i]);
}
}
I'm supposed to be getting only 11 elements, but instead I get 30 random numbers again. Why is that?
I'll put some comments in your code, and see if you can spot where it goes wrong:
//take a histogram of the array. We're only going to count values between 0 and 10
//so 25th to 75 centiles, ignoring values that are lower than 0 or higher than 10
public static int[] arrayHist () {
//need to make an array of 11 numbers for the counts
int[] counts = new int [30];
//get an array of 30 random numbers
int[] hist = randomIntArray (30);
//loop over the whole array of 30 numbers
for (int i = 0; i < 10 && i >= 0; i++) {
//retrieve the random number into a variable temporarily
int index = hist[i];
//if the value is too low or too high, skip it
//else, store it in the counts array - the value from the random array
//serves as the index position in the counts array
counts[index]++;
}
//return the counts array
return hist;
}
What I've done with my comments is equivalent to designing the algorithm using the language you think in (English) and then you can translate it into the language you're learning (java). Very few developers think in the programming language they write. As a student I recommend you should ALWAYS write comments to explain your algorithm to yourself before you write code underneath the comments. You get points for writing comments (usually) so if you write them first then a) it helps you write the code and b) you don't have the tedious job of writing comments after you get the code working
Please please, for your own good/learning, try working out what is wrong from the above before looking at the spoilers(answers) below. Roll the mouse over the box to display the spoilers
//loop over the whole array of 30 numbers - YOU ONLY LOOP 10
for (int i = 0; i < 10 && i >= 0; i++) {
//if the value is too low or too high, skip it - YOU DIDN'T DO THIS CHECK
...
}
//return the counts array - YOU RETURNED THE WRONG ARRAY
return hist;
Edits in response to comments:
Checking a range
You'll have to check two limits, and hence it will need to be of one of the following forms:
if(x < 0 || x > 10) then don't do the count
if(!(x >= 0 && x <= 10)) then don't do the count
if(x >= 0 && x <= 10) then do the count
if(!(x < 0 || x > 10)) then do the count
Tests that use NOT - the exclamation mark ! - are typically a bit harder to read and understand, so try to avoid them is possible. Tests that are "positive minded" - i.e. they return a positive result rather than a negative that needs to be negated - are easier to read and understand.
A helpful tip for loops and methods, in terms of error checking, is to test for bad values that meet certain conditions, and if a bad value is encountered, then skip processing the rest of the loop (using the continue) keyword, or skip the rest of the method (by returning from it)
Doing this means that your if body (the bit between { and } ) doesnt get massive. Compare:
for(...){
if(test for bad values)
continue;
//50 lines long loop body
}
Is neater than doing:
for(...){
if(test for goodvalues){
//50 lines long loop body
}
}
If you use the bottom pattern, you can end up after several IFs in a real indented mess, with { and } all over the place and your code is way over to the right hand side of the screen:
for(...){
//code
if(...){
//code
if(...){
//code
if(...){
//code
if(...){
//code
if(...){
//code
if(...){
//code
}
//code
}
//code
}
//code
}
//code
}
//code
}
//code
}
Keeping indent levels to a minimum helps make your code more readable
Hence, I recommend in your case, that rather than test for the value being inside the range 0 to 10 and doing something with it, you adopt the form "if value is OUTSIDE" the range 0 to 10, skip doing the rest of the loop
Your arrayHist() method just returns the array with the random numbers. It should be more like this:
public static int[] arrayHist() {
// generate array with random numbers
int[] hist = randomIntArray(30);
// initialize the array for counting
int[] counts = new int[11];
// step through the random numbers array and increase corresponding counter if the number's values is between 0 and 10
for (int j = 0; j < hist.length; j++) {
int number = hist[j];
if (number > -1 && number < 11) {
counts[number]++;
}
}
return counts;
}

Moving Average Using User-Input Array

I need to write a program that calculates a moving average by a user inputted array. The first element of the array is the window size, and the input is terminated by a 0. The output values are printed with two digits after the decimal point.
Example input: 3 2 4 7 7 8 11 12 0
Corresponding Output: 4.33 6.00 7.33 8.67 10.33
(4.33 is average of 2,4,7 and 6 is average of 4,7,7 etc.)
Here's my code so far:
package movingaverage;
import java.util.Scanner;
public class MovingAverage {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] arr = new int[n];
int sum = 0;
for (int i = 0; i < n; i++) {
sum += arr[i];
}
avg[0] = sum / 5;
int j = 1;
for (int i = 5; i < arr.length; i++) {
sum = sum + arr[i] - arr[i - 5];
avg[j++] = sum / 5;
}
}
}
I think I have the loop right, but I'm not sure how to get the array to end at 0.
This is a possible solution.
public class Test
{
private static final Scanner SCANNER;
static {
SCANNER = new Scanner(System.in);
}
public static final void main(final String... args) {
final String[] numbers = SCANNER.nextLine().trim().split(" ");
final int consideredElements = Integer.parseInt(numbers[0]);
float sum = 0;
int value = 0;
for (int i = 1; i < numbers.length; i++) {
sum = 0;
for (int k = 0; k < consideredElements; k++) {
value = Integer.parseInt(numbers[i + k]);
if (value == 0) {
return;
}
sum += value;
}
System.out.println(new BigDecimal(sum / consideredElements).setScale(2, RoundingMode.HALF_EVEN));
}
}
}
First, you are using 5 in a couple of places in your program, I see no justification for that. Could it be that your expectation of user input lead you to put 5 where the number you really should use, depends on user input? Maybe you should use the window size instead? I’m guessing a bit here.
Next, as #lppEdd pointed out, you are not reading the numbers from your input — only the window size.
Next, you are declaring your array of size n, which I believe was your window size, not your array size. I believe the real solution to this problem is using better and more explanatory variable names.
Your code does not compile since you have not declared the array avg that you try to store your moving average into.
Fifth, when you want your average as a double, you need to convert to double before dividing (this is a classic pitfall that has already generated many questions on Stack Overflow).
I hope this gets you a couple of steps further.

Generation of 4 non repeating random numbers using arrays in java

I have this array
int [] marc = new int[4];
i need to insert a set of non repeating random numbers in the range of 1-10 to it
i'm using this for loop to set random numbers
for (he = 0; he < 4; he++) {
marc[he] = rn.nextInt(10 - 1 + 1) + 1;
marc[he]++;
}
it gives me random numbers but repeated ones inside the array
i'm also using
java.util.Random;
Well, yes, numbers can be repeated while being random. You need to do your own logic to validate if they're already on the array, this can be done with the following code:
In the code I used an array of 10 elements to observe there aren't repeated numbers even on that situation.
import java.util.Random;
public class RandomNumbersNoRepeating {
public static void main(String[] args) {
int array[] = new int[10];
Random random = new Random();
//Fills the array
for (int i = 0; i < array.length; i++) {
boolean found = false;
int r = 0;
do {
found = false;
r = random.nextInt(10) + 1;
//Here we check if the number is not on the array yet
for (int j = 0; j < array.length; j++) {
if (array[j] == r) {
found = true;
break;
}
}
} while (found);
array[i] = r;
}
//Prints the array
for (int i = 0; i < array.length; i++) {
System.out.println(array[i]);
}
}
}
Another possible solution, as given in a comment could be to shuffle an array from 1-10, and get the first four numbers
Using java.util.Random; will generate repetitive numbers more often when your range is small, which in your case is only 10. There is no condition in your code that checks whether the generated random number already exists in your array or not.
Before inserting a generated number in to the array, you first need to check whether that number already exists in your array. If it does not, you insert that number in the array, otherwise you generate a next random number.

Why is my java program printing zero every time?

I am required to take an array of size x (which contains numbers starting at x and then descending down to 1), and then, with a new array of size y (which may or may not be the same size as x), print out random numbers from array x into array y. I wrote the program and it runs fine, but for some reason in the list of random numbers outputted, the number 0 will show up. Does anybody know why this is happening? Here is my code:
import java.util.Random;
public class Prog1A
{
public static void main(String[] args)
{
System.out.println("Program 1A, Christopher Moussa, masc1574");
Random randGen = new Random();
int[] arr_1 = new int[8];
for (int i = arr_1.length - 1; i >= 0; i--)
{
arr_1[i] = arr_1[i];
}
int[] arr_2 = new int[6];
for (int i = 1; i <= arr_2.length; i++)
{
System.out.print(randGen.nextInt(arr_1.length) + " ");
}
}
}
Any feedback will be greatly appreciated, thank you.
Well you aren't doing anything with this loop. You're essentially assigning a variable to itself right throughout the array. Also, I dislike the way you wrote your loop condition, but my preference isn't the issue here.
for (int i = arr_1.length - 1; i >= 0; i--)
{
arr_1[i] = arr_1[i]; //This code does nothing
}
Then you create arr_2[] but you never assign anything to the variables.
I went ahead and edited your code, and I'll explain a few things.
import java.util.Random;
public class Prog1A
{
public static void main(String[] args)
{
Random randGen = new Random();
int[] arr_1 = new int[8];
int[] arr_2 = new int[6];
System.out.println("Program 1A, Christopher Moussa, masc1574");
//Assigns a random number to each member of arr_1
for (int i = 0; i < arr_1.length; ++i)
{
arr_1[i] = randGen.nextInt(arr_1.length);
}
//Copies arr_1 values to arr_2
for (int i = 0; i < arr_2.length; ++i) //Counting up [0 to 5]
{
arr_2[i] = arr_1[i];
}
for (int i = 0; i < arr_2.length; ++i)
{
System.out.print(arr_2[i] + " ");
}
}
}
Always (if possible) declare all variables at the start of a function/class/program. It keeps code a lot cleaner and helps you to identify possible errors that may occur.
Keep your loop parameters consistent. Start from 0 and go up always, or start from the last value and go down. It eliminates the possibility of an error again. I prefer starting from 0 always but it is up to you, as long as it is clean and it works.
Unless you initialize an array, it is going to be empty. If you try to print from it you'll most likely see zeros.
Just add one to your result, The length of your array is 8. With your current code your are returning a random number between 0 and 7. The nextInt method will never return the upper limit of the integer value supplied. You can test this out yourself by exchanging the arr_1.length for a different number like 10 for example and then remove the + 1. You will notice that it will only return the number 9 at the most and 0 will be the lowest number returned.
System.out.print((randGen.nextInt(arr_1.length) + 1) + " ");

Generate a random number that is not in array [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
so I have this code that basically reads from a text file. The text file contains 9 rows of 9 random numbers, as well as 9 columns - it is for a 9 x 9 Sudoku puzzle, so think of it that way.
Here is what the text file that is being read in looks like:
1,1,0,0,1,0,0,0,0
1,0,0,1,1,1,0,0,0
0,1,1,0,0,0,0,1,0
1,0,0,0,1,0,0,0,1
1,0,0,1,0,1,0,0,1
1,0,0,0,1,0,0,0,1
0,1,0,0,0,0,1,1,0
0,0,0,1,1,1,0,0,1
0,0,0,0,1,0,0,1,1
For this particular facet, the values from the file are used to determine if a cell is empty is or not. If it is a number 1, than that cell will contain some sort of value, but if the number is 0, that cell is empty, and will need to have a random number generated for it.
How do I make it so that when Math.random is used to generate said random number, it checks to see if that same number is already in that row, and if it is, generate a new one?
Here is the code. Thanks in advance...
import java.util.*;
import java.io.*;
import java.math.*;
public class RandomNumberGenerator {
// set Sudoku value rows to unchangeable number 9
private static final int ROWS = 9;
// set columns to unchangeable number 9
private static final int COLUMNS = 9;
public static void main(String[] args) { // main
// load in text file
ReadSudokuFile puzzle = new ReadSudokuFile("puzzle.txt");
// set array to get number values from getDisplayValues method
int puzzleNumbers[][] = puzzle.getDisplayValues();
// rows loop
for (int rows = 0; rows < ROWS; rows++) {
// columns loop
for (int columns = 0; columns < COLUMNS; columns++) {
// A cell containing the number 0 is an empty input box in Sudoku grid
if (puzzleNumbers[rows][columns] == 0) {
// populate that empty input box to a random number between 1 and 9
puzzleNumbers[rows][columns] = (int)((Math.random() * 9) + 1); // cast Math.random as an int & add 1 so a zero doesn't display
}
} // end columns loop
// print out the array to console
System.out.println(Arrays.toString(puzzleNumbers[rows]));
} // end rows loop
} // end main
}
There is another file that this file pulls info from, but it is not relevant here for this specific question. Thanks again!
One possible method, using Java 8, is to filter members of the row from a stream of random numbers. Something like:
Random rand = new Random();
puzzleNumbers[row][col] = rand.ints(0, 10)
.filter(n -> Arrays.binarySearch(puzzleNumbers[row], 0, col, n) < 0)
.findAny().get();
I've left out the row and col iteration for clarity.
This can be extended fairly easily to filter out numbers in the row or 3x3 cell. Let me know in comments if you want examples for those.
well you can make a private method that checks that.
public boolean checkRow(int row,int generatedNum){
boolean flag = true;
for (int columns = 0; columns < COLUMNS; columns++) {
// A cell containing the number 0 is an empty input box in Sudoku grid
if (puzzleNumbers[row][columns] == generatedNum) {
flag = false;
break;
}
}
}
You can populate an ArrayList with the numbers from 1 to 9 and the get a random index. When you need start over, you can just reset the ArrayList.
public class Test {
public static void main(String[] args) {
final ArrayList<Integer> numbers = new ArrayList<>();
// Populate the ArrayList with numbers ( from 1 to 9 )
resetNumbers(numbers);
// Getting 5 random numbers from 1 to 9
for (int i = 0; i < 5; i++) {
System.out.println(getRandomIndex(numbers));
}
// Reset the number list
resetNumbers(numbers);
System.out.println();
// Get another 9 random numbers from 1 to 9
for (int i = 0; i < 9; i++) {
System.out.println(getRandomIndex(numbers));
}
}
public static void resetNumbers(ArrayList<Integer> list) {
list.clear();
populateList(list, 1, 9);
}
public static void populateList(ArrayList<Integer> list, int from, int to) {
for (int i = from; i <= to; i++) {
list.add(i);
}
}
public static int getRandomIndex(ArrayList<Integer> numbers) {
int index = (int)((Math.random() * numbers.size()) + 0);
int result = numbers.get(index);
numbers.remove(index);
return result;
}
}

Categories

Resources