How does this array print this barchart? - java

public class BarChart // Modified from Fig 7.6
{
public static void main(String[] args)
{
int[] grades = {90, 71, 89, 75, 83, 87, 81, 100, 99, 83,
65, 100, 91, 78, 88, 62, 55, 84, 73, 89}; // 20 elements
int[] frequency = new int[11]; // 11 ranges
System.out.println("Grade distribution:");
for (int i = 0; i < grades.length; i++) {
frequency[grades[i]/10]++; //How does this work? why does it say 10
}
for (int i = 0; i < frequency.length; i++)
{
if (i == 10) {
System.out.printf("%5d: ", 100);
}
else {
System.out.printf("%02d-%02d: ", i * 10, i * 10 + 9);
}
for (int stars = 0; stars < frequency[i]; stars++) { // How does it know where to print the stars?
System.out.print("*");
}
System.out.println();
}
}
}
Output:
I am having trouble understanding how this program works. I put in some questions as comments to get a clearer answer. I attached a pic of the output as well.

I have commented in the code directly:
public class BarChart // Modified from Fig 7.6
{
public static void main(String[] args)
{
/*array that contains the data that will be used to display the distribution*/
int[] grades = {90, 71, 89, 75, 83, 87, 81, 100, 99, 83,
65, 100, 91, 78, 88, 62, 55, 84, 73, 89}; // 20 elements
/*this frequecncy is used to divided your interval [0,100] in 11 slices*/
int[] frequency = new int[11]; // 11 ranges
System.out.println("Grade distribution:");
for (int i = 0; i < grades.length; i++) {
/*division of your i element of grade array by 10,
10 here is used here to make correspond your grades
to your slices defined in the frequency variable,
(type int divided by 10 will give an int as output
(the decimals are truncated -> equivalent as taking the floor of the number)
so you have an int that can be used as an index for your frequency array,
the grades[i]/10 will be incremented by 1 -> this will allow to print the stars after*/
frequency[grades[i]/10]++;
}
for (int i = 0; i < frequency.length; i++) //loop that will do the display
{
if (i == 10) {
System.out.printf("%5d: ", 100);//this will print the last line of your output,
//printf will not print the EOL char so the other printing operations are done on the same line
}
else {
System.out.printf("%02d-%02d: ", i * 10, i * 10 + 9);
//this is will create your DD-DD intervals (00-09:, 10-19)
}
for (int stars = 0; stars < frequency[i]; stars++) {
// the value stored in frequency thanks to this operation: frequency[grades[i]/10]++; will be displayed,
//you loop from 0 until you reach the value of frequency[i] and display a star at each loop
System.out.print("*");
}
System.out.println();//this will print the end of line character
}
}
}

Related

Adding up all the elements of each column in a 2D array

So I have this dummy 2D array:
int mat[][] = {
{10, 20, 30, 40, 50, 60, 70, 80, 90},
{15, 25, 35, 45},
{27, 29, 37, 48},
{32, 33, 39, 50, 51, 89}};
I want to add up all the values by columns so it would add 10 + 15 + 27 + 32 and return 84 and so on. I have this so far:
public void sum(int[][] array) {
int count = 0;
for (int rows = 0; rows < array.length; rows++) {
for (int columns = 0; columns < array[rows].length; columns++) {
System.out.print(array[rows][columns] + "\t");
count += array[0][0];
}
System.out.println();
System.out.println("total = " + count);
}
}
Can anyone help with this? Also the System.out.print(array[rows][columns] + "\t" ); prints the array out by rows, is there a way to print it out by columns?
One possible Solution would be to first find maximum size of all sub arrays and iterate that many times to find sum of each column avoiding unavailable values.
public static void main(String[] args) {
int mat[][] = {{10, 20, 30, 40, 50, 60, 70, 80, 90},
{15, 25, 35, 45},
{27, 29, 37, 48},
{32, 33, 39, 50, 51, 89},
};
// Find maximum possible length of sub array
int maxLength = 0;
for (int i = 0; i < mat.length; i++) {
if (maxLength < mat[i].length)
maxLength = mat[i].length;
}
for (int i = 0; i < maxLength; i++) {
int sum = 0;
for (int j = 0; j < mat.length; j++) {
// Avoid if no value available for
// ith column from this subarray
if (i < mat[j].length)
sum += mat[j][i];
}
System.out.println("Sum of Column " + i + " = " + sum);
}
}
Use an ArrayList to get the sum of all the columns.
public static void sum(int[][] array) {
ArrayList<Integer> sums = new ArrayList<>();
for (int row = 0; row < array.length; row++) {
for (int column = 0; column < array[row].length; column++) {
if (sums.size() <= column) {
sums.add(column, 0);
}
int curVal = sums.get(column);
sums.remove(column);
sums.add(column, curVal + array[row][column]);
}
}
for (int i = 0; i < sums.size(); i++) {
System.out.println("Sum of column " + i + " = " + sums.get(i));
}
}
Here is one alternative.
The supplied data.
int mat[][] = { { 10, 20, 30, 40, 50, 60, 70, 80, 90 },
{ 15, 25, 35, 45 }, { 27, 29, 37, 48 },
{ 32, 33, 39, 50, 51, 89 }, };
First, find the maximum length of the array in which to store the sum.
int max = Arrays.stream(mat).mapToInt(a -> a.length).max().orElse(0);
Allocate the new array to hold the sums.
int[] sums = new int[max];
Now just use the Arrays.setAll method to sum them, taking careto not exceed the current array's length.
for (int[] arr : mat) {
Arrays.setAll(sums, i-> i < arr.length ? sums[i] + arr[i] : sums[i]);
}
System.out.println(Arrays.toString(sums));
Prints
[84, 107, 141, 183, 101, 149, 70, 80, 90]
You can use Stream.reduce method to summarise the elements of the rows of the matrix by the columns:
int[][] matrix = {
{10, 20, 30, 40, 50, 60, 70, 80, 90},
{15, 25, 35, 45},
{27, 29, 37, 48},
{32, 33, 39, 50, 51, 89}};
int[] arr = Arrays.stream(matrix)
// summarize in pairs
// the rows of the matrix
.reduce((row1, row2) -> IntStream
// iterate over the indices
// from 0 to maximum row length
.range(0, Math.max(row1.length, row2.length))
// summarize in pairs the elements of two rows
.map(i -> (i < row1.length ? row1[i] : 0) +
(i < row2.length ? row2[i] : 0))
// an array of sums
.toArray())
// the resulting array
.get();
System.out.println(Arrays.toString(arr));
// [84, 107, 141, 183, 101, 149, 70, 80, 90]
See also:
• Sum of 2 different 2d arrays
• How to calculate the average value of each column in 2D array?
…and the same with lambda:
int[] array = Arrays.stream(mat)
.reduce((a1, a2) -> IntStream.range(0, Math.max(a1.length, a2.length))
.map(i -> i < a1.length && i < a2.length ? a1[i] + a2[i]
: i < a1.length ? a1[i] : a2[i] ).toArray()).get();
gets the sums of each column in the int[] array:
[84, 107, 141, 183, 101, 149, 70, 80, 90]

distrubuting people to groups evenly based on userinput

ReadFile randomGenerate = new ReadFile();
Input userNum = new Input();
String classnum = userNum.fileToSelect();
int lineNumber = randomGenerate.lineCounter(classnum);
//number of students in classnum.txt
ArrayList<String> people = randomGenerate.readPeople();
//a string of names(first word on each row)
int userPut = userNum.numInput();
int maxNum = lineNumber/userPut;
Right not, I am reading off a txt file - the first word of each row which is the name of a person. I want to distribute this ArrayList of people into even groups, with the number of groups based on userinput.
int[] numbers = RandomNumbersWithoutRepetition(0, lineNumber, lineNumber);
//an array of numbers IN ORDER
int[] randomNumbers = RandomizeArray(numbers);
//shuffles the array
I generated a set of numbers in order, and then shuffled them, which works fine.
But, my method of grouping people has been based off ifelse conditions which don't work so well. So is there an efficient method to put this ArrayList of names into user-desired groups?
I have x number of students.
I have n number of groups.
I'm assuming there's no other criteria for dividing students into groups.
Basically, you divide the number of groups into the number of students. Yes, you have to deal with a remainder. But it's straightforward.
Here are the results of a test. I created 53 students and shuffled them. I then divided the students into 4 groups. I manually formatted the output to fit in the answer. Group 1 has 14 students, while the remaining groups have 13 students.
Students: 42, 27, 5, 26, 32, 30, 44, 10, 17, 29, 40, 52,
47, 38, 49, 18, 46, 24, 34, 12, 13, 53, 35, 20, 1,
2, 41, 23, 43, 28, 8, 11, 50, 37, 9, 7, 48, 3, 33,
25, 31, 15, 22, 21, 14, 45, 36, 16, 51, 19, 4, 6, 39
Group 1: 42, 27, 5, 26, 32, 30, 44, 10, 17, 29, 40, 52, 47, 38
Group 2: 49, 18, 46, 24, 34, 12, 13, 53, 35, 20, 1, 2, 41
Group 3: 23, 43, 28, 8, 11, 50, 37, 9, 7, 48, 3, 33, 25
Group 4: 31, 15, 22, 21, 14, 45, 36, 16, 51, 19, 4, 6, 39
And here's the code. The groupStudents and sortStudents methods are the methods that do the work.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class StudentGroups {
public static void main(String[] args) {
int numberOfGroups = 4;
int numberOfStudents = 53;
StudentGroups sg = new StudentGroups(numberOfStudents);
sg.printStudents();
List<List<Integer>> groups = sg.groupStudents(
numberOfGroups);
sg.printGroups(groups);
}
private List<Integer> students;
public StudentGroups(int numberOfStudents) {
students = new ArrayList<>(numberOfStudents);
for (int i = 0; i < numberOfStudents; i++) {
students.add(i + 1);
}
Collections.shuffle(students);
}
public void printStudents() {
System.out.print("Students: ");
for (int i = 0; i < students.size(); i++) {
System.out.print(students.get(i));
if (i < (students.size() - 1)) {
System.out.print(", ");
}
}
System.out.println();
}
public List<List<Integer>> groupStudents(int groups) {
List<List<Integer>> output = new ArrayList<>();
int size = students.size();
int group = size / groups;
int remainder = size % groups;
sortStudents(output, size, group, remainder);
return output;
}
private void sortStudents(List<List<Integer>> output,
int size, int group, int remainder) {
List<Integer> list = new ArrayList<>();
int count = 0;
for (int i = 0; i < size; i++) {
list.add(students.get(i));
if (count == 0 && remainder > 0) {
if (group > 0) {
list.add(students.get(++i));
}
remainder--;
}
if (++count >= group) {
addList(output, list);
list = new ArrayList<>();
count = 0;
}
}
addList(output, list);
}
private void addList(List<List<Integer>> output,
List<Integer> list) {
if (list.size() > 0) {
output.add(list);
}
}
public void printGroups(List<List<Integer>> groups) {
for (int j = 0; j < groups.size(); j++) {
System.out.print("Group ");
System.out.print(j + 1);
System.out.print(": ");
List<Integer> students = groups.get(j);
for (int i = 0; i < students.size(); i++) {
System.out.print(students.get(i));
if (i < (students.size() - 1)) {
System.out.print(", ");
}
}
System.out.println();
}
}
}

How to sort only odd integers from an array of both odd and even integers and only display the sorted odd integer?

here is the integer array given to me 111,77, 88, 44, 32, 11, 13, 25, 44 I need to sort & display only the odd elements of the array .
I had tried solving it using loops and if condition
i had expected the output as 11 13 25 77 111
import java.lang.reflect.Array;
public class oddsortSolution {
public static void main(String args[]) {
int n[] = { 111, 77, 88, 44, 32, 11, 13, 25, 44 };
int i = 0;
int temp = 0;
while (i < n.length) {
if (n[i] % 2 != 0) {
for (int j = i + 1; j < n.length; j++) {
if (n[j] > n[i]) {
n[j] = temp;
n[j] = n[i];
n[i] = temp;
}
}
}
}
System.out.println(n[1]);
}
}
You basically need to keep track of your odd array size, increment it every time you find an odd value, determine if the value should be swapped somewhere in the existing array (ranging from 0 to oddArraySize) and insert it in the correct position. Try the following code,
public class oddsortSolution {
public static void main(String args[]) {
int n[] = { 111, 77, 88, 44, 32, 11, 13, 25, 44 };
int oddArraySize = 0;
for (int i = 0;i < n.length; i++) {
if (n[i] % 2 != 0) {
oddArraySize++;
for (int j = 0; j < oddArraySize; j++) {
if (j == oddArraySize - 1) {
n[j] = n[i];
} else if (n[j] > n[i]) {
int temp = n[j];
n[j] = n[i];
n[i] = temp;
}
}
}
}
int[] oddArray = Arrays.copyOfRange(n, 0, oddArraySize);
System.out.println( Arrays.toString( oddArray ));
}
}

using binarySearch to do a paircount of integers in a java int array

I tried using Arrays.binarySearch to find the number of pairs of ints in an array.In the following array, a brute force algorithm will find 4 pairs..However the binarysearch version gives 3 which is the wrong answer.
brute force:
public static int brutePairCount(int[] a){
int paircount = 0;
int N = a.length;
for(int i=0;i<N;i++){
for(int j=i+1;j<N;j++){
if(a[i]==a[j] ){
paircount++;
}
}
}
return paircount;
}
public static void main(String[] args) {
int[] nums = new int[]{12, 12, 23, 23, 45, 67, 75, 75, 85, 92, 111, 113, 113, 134, 142, 156};
int cnt1 = brutePairCount(nums);
System.out.println("pairs="+cnt1);
}
binarysearch:
public static int bsPairCount(int[] a){
Arrays.sort(a);
int paircount = 0;
int N = a.length;
for(int i=0;i<N;i++){
int key = a[i];
int idx = Arrays.binarySearch(a, key);
if(idx > i){
paircount++;
}
}
return paircount;
}
public static void main(String[] args) {
int[] nums = new int[]{12, 12, 23, 23, 45, 67, 75, 75, 85, 92, 111, 113, 113, 134, 142, 156};
int cnt1 = bsPairCount(nums);
System.out.println("pairs="+cnt1);
}
I found that the logic
if(idx > i){
paircount++;
}
is the source of error.My debugger shows that ,at i=11, key =113 ,the binarysearch(key) returns 11 itself,and so count is not incremented.
From the javadocs of Arrays.binarySearch :
If the range contains multiple elements equal to the specified object,
there is no guarantee which one will be found.
I think I found the problem,but how do I solve this? my brain is a bit addled (lack of sleep:( )..Can someone shed some light?

How do you sort numbers in ascending order from a for loop?

i have a for loop that multiples 3 and 7 by all numbers between 1 and 100. It only shows the numbers that are less the 100 after the multiplication though. How would you sort it so that its in ascending order?
for(int i = 1; i<=100; i++){
int result1 = 3 * i;
int result2 = 7*i;
if (result1 <=100){
System.out.println(+result1);
}
if (result2 <= 100){
System.out.println(+result2);
}
}
would use another if statement to sort it?
How about:
for(int i = 1; i<=100; i++){
if(i % 3 == 0 || i % 7 == 0)
System.out.println(i);
}
This sounds like it'll do what you need:
[mike#mike ~]$ cat temp/SO.java
package temp;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class SO {
private static final int MAX_VAL = 100;
public static void main(String[] args) {
List<Integer> results = new ArrayList<Integer>();
for (int i = 1; i <= MAX_VAL; i++) {
int result1 = 3 * i;
int result2 = 7 * i;
if (result1 <= MAX_VAL) {
results.add(result1);
}
if (result2 <= MAX_VAL) {
results.add(result2);
}
}
Collections.sort(results);
System.out.println(results);
}
}
[mike#mike ~]$ javac temp/SO.java
[mike#mike ~]$ java temp.SO
[3, 6, 7, 9, 12, 14, 15, 18, 21, 21, 24, 27, 28, 30, 33, 35, 36, 39, 42, 42, 45, 48, 49, 51, 54, 56, 57, 60, 63, 63, 66, 69, 70, 72, 75, 77, 78, 81, 84, 84, 87, 90, 91, 93, 96, 98, 99]

Categories

Resources