-
Notifications
You must be signed in to change notification settings - Fork 1
/
032_BarChart.java
69 lines (53 loc) · 2.09 KB
/
032_BarChart.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
// Question Link: https://www.pepcoding.com/resources/online-java-foundation/function-and-arrays/bar-chart-official/ojquestion
/*
i/p: n = 5
arr = 2 3 1 4 5
o/p:
*
* *
* * *
* * * *
* * * * *
*/
import java.util.Scanner;
public class BarChart {
// Function to find the maximum height in the array - TC = O(n), SC = O(1)
public static int maxHeight(int[] arr) {
int max = arr[0]; // Initialize max with the first element
// Traverse the array to find the maximum value
for (int i = 1; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i]; // Update max if a larger value is found
}
}
return max; // Return the maximum height
}
// Function to print the bar chart - TC = O(n * maxHeight), SC = O(1)
public static void printBarChart(int[] arr) {
int max = maxHeight(arr); // Get the maximum height
// Loop from the maximum height down to 1
for(int ht = max; ht >= 1; ht--) {
// Check each bar at the current height level
for(int i = 0; i < arr.length; i++) {
if(arr[i] >= ht) // If bar height is at least current height level
System.out.print("* "); // Print a star
else
System.out.print(" "); // Otherwise, print spaces
}
System.out.println(); // Move to the next line after each height level
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Read the number of bars in the bar chart
int n = sc.nextInt();
// Create an array to store the heights of the bars
int[] arr = new int[n];
// Populate the array with bar heights from user input
for(int i = 0; i < arr.length; i++) {
arr[i] = sc.nextInt();
}
printBarChart(arr); // Call function to print the bar chart
sc.close(); // Close the scanner to prevent resource leak
}
}