So the question is:
Write a program that reads a sequence of input values and displays a bar chart of the values using asterisks. You may assume that all values are positive. First figure out the maximum value. That value’s bar should be drawn with 40 asterisks. Shorter bars should use proportionally fewer asterisks.
eg.
***********************
*********
****************************************
****
*******************
This is my code below:
int count = 0;
//Finds largest Value
int largestValue = numbersArray[0];
for (int i = 1; i < numbersArray.length; i++) {
if (numbersArray[i] > largestValue) {
largestValue = numbersArray[i];
count++;
}
}
//Prints number of asterisks
final int MAX = 40;
String asterisks = "****************************************";
for (int i = 0; i < count + 2; i++) {
System.out.print(numbersArray[i]);
if (numbersArray[i] == largestValue) {
System.out.print(asterisks);
} //if (numbersArray[i] != largestValue) {
else {
for (int j = 0; j < (40 * numbersArray[i] / largestValue); j++) {
System.out.print("*");
}
}
System.out.println();
}
This code doesn't seem to run properly.
If I enter values in the order: 5 8 6 4 7, it will just print the stars for 5 and 8, and not the rest. Basically it prints stars for values till the largest number.
I can't find what's wrong with my code. Any help would be greatly appreciated!
Thanks for reading <3
First of all, you don't need to count variable - it does nothing helpful to you and you for some reason limit yourself (you increment everytime you find a larger element so you only increment once since there's nothing larger than 8).
What you should be doing is finding the largest value, as you did, and then running over the entire array and displaying each element proportional to that value, as you did (but without the special case for the actual largest value - that is atrocious).
Also, you should note that division of two integers would result in an integer, which is not what you want, so you'll have to cast one of them to float or double.
//finds largest Value
int largestValue = numbersArray[0];
for (int i = 1; i < numbersArray.length; i++) {
if (numbersArray[i] > largestValue) {
largestValue = numbersArray[i];
}
}
//Prints number of asterisks
final int MAX = 40;
for (int i = 0; i < numbersArray.length; i++) {
int portion = (int)(MAX * (numbersArray[i] / (float)largestValue));
for (int j = 0; j < portion; j++) {
System.out.print("*");
}
System.out.println();
}
So you'll find the largest value is 8.
Then for 5, you'll do 5/8 which is 0.625 and times MAX (40) that would be 25, so you'll print 25 *.
Then for 8 - 8/8 = 1.0 * MAX = 40 so you'll print the whole 40 *.
For 6 - 6/8 = 0.75 * MAX = 30 so you'll print 30 * and so on.
Note that if you want to fine-tune it, you could use Math.round instead of simply casting the portion to int (which simply truncates the floating point).
Related
for(i=0; i<array.length; i++){
sum = 4 * 5;
}
What I'm trying to do is add ((array.length - 1) - i) 0's to the value of sum. For this example assume array length is 3. sum equals 20. So for the first iteration of the loop i want to add ((3 - 1) - 0) 0's to the value of sum, so sum would be 2000. The next iteration would be ((3 - 1) - 1) 0's. so sum would equal 200 and so on. I hope what I am trying to achieve is clear.
So my questions are:
Is it possible to just shift an int to add extra digits? My search thus far suggests it is not.
If not, how can i achieve my desired goal?
Thankyou for reading my question and any help would be greatly apreciated.
You can just multiply it by 10 however many times.
200 * 10 = 2000
etc
So in your case, you'd have to use a for loop until the end of the array and multiply sum every iteration. Be careful though, because the max value of an int is 2^31, so it of surpasses that, it will roll back to 0
You can add n zeroes to the end of a number, sum by multiplying sum by 10 * n.
int sum = 20;
for (int i = 0; i < ary.length; ++i) {
int zeroesToAdd = ary.length - 1 - i
sum *= (zeroesToAdd > 0) ? zeroesToAdd * 10 : 1
}
System.out.println("Sum after loop: " + sum);
for(int i=array.length; i>0; i--){
sum = 20;
for(int j=0; j < (i - 1); j++)
{
sum *= 10;
}
}
Use inner loop to multiply by 10 the number of times i is for that iteration. You would need to reset sum in your outer loop each time.
You will want to check your for-loop condition: i>array.length. Since i starts at 0, this loop will not run unless the array's length is also 0 (an empty array). The correct condition is i < array.length.
This "shift" you want can be achieved by creating a temporary variable inside the loop that is equal to the sum times 10i. In Java's Math library, there is a pow(a,b) function that computes ab. With that in mind, what you want is something like this:
int oldSum = 4 * 5;
for (int i = 0; i < array.length; i++) {
int newSum = oldSum * Math.pow(10,i);
}
Multiply by 10 instead, and use < (not >) like
int sum = 20;
int[] array = { 1, 2, 3 };
for (int i = 0; i < array.length; i++) {
int powSum = sum;
for (int j = array.length - 1; j > i; j--) {
powSum *= 10;
}
System.out.println(powSum);
}
Output is (as requested)
2000
200
20
For array of length = n; you will end up adding (n - 1) + (n - 2) + ... + 2 + 1 + 0 zeros for i = 0, 1, ... n-2, n-1 respectively.
Therefore, number of zeros to append (z) = n * (n-1) / 2
So the answer is sum * (10 ^ z)
[EDIT]
The above can be used to find the answer after N iteration. (I miss read the question)
int n = array.length;
long sum = 20;
long pow = Math.pow(10, n-1); // for i = 0
for (int i = 0; i < n; i++) {
System.out.println(sum*pow);
pow /= 10;
}
i'm just started to learn java yesterday. But, now i met difficulty to show the arithmetic progression like the display below:
1 2 2 2 3 3 3 3 3 4 4 4 4 4 4 4
From that example, i know that every odd numbers, the numbers increment. I've tried to make it, but the display just keep showing like this:
2 4 4 4 6 6 6 6 6 8 8 8 8 8 8 8 10 10 10 10 10 10 10 10 10
Here's my code:
for (int i = 0; i <= 10; i++) {
if (i % 2 == 0) {
for(int j = 1; j<i; j++){
System.out.print(i + " ");
}
}
}
And then, i want to take the last value of it. For example, if i have row = 3, it must be value = 2.
because :
row = 1 2 3 4 5 6 7 8 9 10
value = 1 2 2 2 3 3 3 3 3 4
Would you tell me, what line is exactly must be fix? Thank you
It's not about a line that is wrong, it's your approach that's a bit off. You could fix it in multiple ways. Easiest (but not most efficient) way is this:
for (int i = 0; i <= 10; i++) {
if (i % 2 == 0) {
for(int j = 1; j<i; j++){
System.out.print((i/2) + " ");
}
}
}
As you can see, only the output was changed and now it works. However, iterating over 11 numbers (0-10) when you only really care about 4-5 is not necessarily the best way to go here.
It also doesn't make your code easy to understand.
Here's an alternative.
int amount = 1;
for (int i = 1; i <= 5; i++) {
for (int j = 0; j < amount; j++) {
System.out.print(i + " ");
}
amount = amount + 2;
}
Here you can see that the outer for has been changed to only take the numbers we actually care about, which means we can remove the if completely.
We just have to somehow decide how many times we want to execute the print call, which is done with the amount variable.
Try this.
for (int i = 1, r = 1; i <= 4; ++i, r += 2)
System.out.print((i + " ").repeat(r));
You can calculate value from row with this method.
static int value(int row) {
return (int)Math.ceil(Math.sqrt(row));
}
So you can also do like this.
for (int row = 1; row <= 16; ++row)
System.out.print(value(row) + " ");
result:
1 2 2 2 3 3 3 3 3 4 4 4 4 4 4 4
Hey it's a representation of a sequence that grows by 2 every step.
i.e the first element is 1 which shows up one time.
the second element is 3 which shows up 3 times (2 2 2)
and so on and on..
so the code you need is:
int a = 1;
for(int i=1; i<=10;i++){
int j=1;
while(j<=a){
System.out.print(i);
j++;
}
a+=2;
}
printing the value in a wanted row:
Scanner in = new Scanner(System.in);
int rowU = in.nextInt(); // User inputs row
int row = 1; // a variable to keep track of the rows
int repeats = 1; // the number of times a value shoud appear
for(int value=1;value<=10;value++){
int j=1;
while(j<=repeats){
if(row==rowU) // if we got to the wanted row
System.out.println(value); // print the wanted value
j++;
row++;
}
repeats+=2;
}
There is a better, more efficient way to get the value of a wanted row:
int wanted_value = Math.ceil(Math.sqrt(wanted_row));
Thanks to #saka for bringing this one up!
Hope I helped :)
i % 2 == 0 means that the following code is only going to be executed, if i is even.
You could try removing the if, and change the second for to something like
int j = 0; j < 2 * i - 1; j++.
This code snippet will do the work
int n=4;
int printTimes=1;
for(int i=1;i<=n;i++)
{
for(int j=0;j<printTimes;j++)
System.out.print(i+" ");
printTimes+=2;
}
System.out.println();
Here is the example code.
int start = 1;
int end = 5;
int time = 1;
for (int i = start,j = time; i < end; i++,j+=2) {
for (int k = 0; k < j; k++) {
System.out.print(i+" ");
}
}
for(i=0; i<array.length; i++){
sum = 4 * 5;
}
What I'm trying to do is add ((array.length - 1) - i) 0's to the value of sum. For this example assume array length is 3. sum equals 20. So for the first iteration of the loop i want to add ((3 - 1) - 0) 0's to the value of sum, so sum would be 2000. The next iteration would be ((3 - 1) - 1) 0's. so sum would equal 200 and so on. I hope what I am trying to achieve is clear.
So my questions are:
Is it possible to just shift an int to add extra digits? My search thus far suggests it is not.
If not, how can i achieve my desired goal?
Thankyou for reading my question and any help would be greatly apreciated.
You can just multiply it by 10 however many times.
200 * 10 = 2000
etc
So in your case, you'd have to use a for loop until the end of the array and multiply sum every iteration. Be careful though, because the max value of an int is 2^31, so it of surpasses that, it will roll back to 0
You can add n zeroes to the end of a number, sum by multiplying sum by 10 * n.
int sum = 20;
for (int i = 0; i < ary.length; ++i) {
int zeroesToAdd = ary.length - 1 - i
sum *= (zeroesToAdd > 0) ? zeroesToAdd * 10 : 1
}
System.out.println("Sum after loop: " + sum);
for(int i=array.length; i>0; i--){
sum = 20;
for(int j=0; j < (i - 1); j++)
{
sum *= 10;
}
}
Use inner loop to multiply by 10 the number of times i is for that iteration. You would need to reset sum in your outer loop each time.
You will want to check your for-loop condition: i>array.length. Since i starts at 0, this loop will not run unless the array's length is also 0 (an empty array). The correct condition is i < array.length.
This "shift" you want can be achieved by creating a temporary variable inside the loop that is equal to the sum times 10i. In Java's Math library, there is a pow(a,b) function that computes ab. With that in mind, what you want is something like this:
int oldSum = 4 * 5;
for (int i = 0; i < array.length; i++) {
int newSum = oldSum * Math.pow(10,i);
}
Multiply by 10 instead, and use < (not >) like
int sum = 20;
int[] array = { 1, 2, 3 };
for (int i = 0; i < array.length; i++) {
int powSum = sum;
for (int j = array.length - 1; j > i; j--) {
powSum *= 10;
}
System.out.println(powSum);
}
Output is (as requested)
2000
200
20
For array of length = n; you will end up adding (n - 1) + (n - 2) + ... + 2 + 1 + 0 zeros for i = 0, 1, ... n-2, n-1 respectively.
Therefore, number of zeros to append (z) = n * (n-1) / 2
So the answer is sum * (10 ^ z)
[EDIT]
The above can be used to find the answer after N iteration. (I miss read the question)
int n = array.length;
long sum = 20;
long pow = Math.pow(10, n-1); // for i = 0
for (int i = 0; i < n; i++) {
System.out.println(sum*pow);
pow /= 10;
}
I have create a program that takes a random array which is created by starting from 0 and adding Math.random() (double between 0 and 0.999) n times, and calculates the weighted average of each position within a certain radius. I currently have a program that does this but i was wondering how to create one using a torus. The basic principle is the last element is now equal to the first element and when the first element updates its position it takes into account the difference between the other elements including some of the last elements in the array.
Any help on the matter would be much appreciated. Its not help with the coding but with the principle behind it, I cant work out how this would be possible for multiple iterations.
heres the code so far that works for one iteration. After one the code is incorrect and calculates the wrong values.
import java.text.DecimalFormat;
import java.util.Scanner;
/**
* Created by jameshales on 12/03/2014.
*/
public class Torus {
public static void main(String[] args) {
DecimalFormat df = new DecimalFormat("#.###"); // this sets all decimals to a max of 3 decimal places.
System.out.println("how many numbers of agents on the real line?"); // This asks the question "how many numbers on the real line?" to the user.
Scanner input = new Scanner(System.in);
int n = 0;
n=Integer.parseInt(input.nextLine()); // the scanner reads the input and assigns it to the variable n
double[] agentPosition = new double[n]; // create an array with decimal places allowed called agentPosition
double[] newAgentPosition = new double[n]; // create an array with decimal places allowed called newAgentPosition
double[] originalAgentPosition = new double[n]; // create an array with decimal places allowed called originalAgentPosition
System.out.println("Please select your desired radius? select 1 normally"); // This asks the question "Please select your desired radius?
double r = 0;
r = input.nextDouble(); // the scanner reads the next input and assigns it to the variable r
int t = 0; // sets t to 0
double epsilon = 0.001; // this allows us to sets epsilon to 0.
// start the array from position 0 with its value set to 0
for (int i = 0; i <= n - 1; i++) { // starting from position 1 it creates a random number between 0 and 0.999 and adds it to the previous agentPosition to fill the array in a random increasing way.
if (i > 0)
agentPosition[i] = agentPosition[i - 1] + Math.random(); // this equation creates the random array
else agentPosition[i] =0.0;
}
System.arraycopy(agentPosition,0,originalAgentPosition,0,n);
// This takes the first randomly created array(agentPosition), copyies each element starting from 0 to n and calls it originalAgentPosition.
while(true) { // This is the start of the while loop, this will keep running until false
for (int i = 0; i <= n - 1; i++) {
// this will go through the array 1 position at a time in an increasing order from position 0 to n-1
double total1 = agentPosition[i]; // sets the initial value of total1 to 0
double total2 = 0; // sets the initial value of total2 to 0
int numposition = 1; // this starts at 1 so it includes the position in the array when dividing.(also stops dividing by 1)
for (int j = i - 1; j >= 0; j--) { // this will work from the initial value of the array to the one before the one selected.
if ((agentPosition[i] - agentPosition[j]) <= r) { // this calculates the absolute value of the difference between 2 positions on the array. (from i working downwards)
numposition++; // this sums the number of positions within the radius of the chosen position.
total1 += agentPosition[j]; // this sums up all the values within the radius below to the total1.
} else break; // stops the program once it has passed a position of a distance of 1
}
for (int k = i + 1; k <= n - 1 ; k++) { // this will go from the one after the position selected to the last position in the array to test if the distance is greater than 1, stops otherwise..
if (Math.abs(agentPosition[k] - agentPosition[i]) <= r) { // this calculates the absolute value of the difference between 2 positions on the array(i and positions greater).
numposition++; // this sums the number of positions within the radius of the chosen position.
total2 += agentPosition[k]; // this sums up all the values within the radius above to the total1.
} else break; // stops the program once it has passed a position of a distance of 1
}
for (int j = n - 2; j >= 1; j--) { // this will work from the initial value of the array to the one before the one selected.
if (((agentPosition[n-1] + agentPosition[i]) - agentPosition[j]) <= r) { // this calculates the absolute value of the difference between 2 positions on the array. (from i working downwards)
numposition++;
total1 += (agentPosition[j] - agentPosition[n - 1]); // this sums up all the values within the radius below to the total1.
} else break;// stops the program once it has passed a position of a distance of 1
}
for (int k = 1; k <= n - 2 ; k++) { // this will go from the one after the position selected to the last position in the array to test if the distance is greater than 1, stops otherwise..
if (Math.abs((agentPosition[i] - agentPosition[n - 1]) - agentPosition[k]) <= r) { // this calculates the absolute value of the difference between 2 positions on the array(i and positions greater).
numposition++; // this sums the number of positions within the radius of the chosen position.
total2 += (agentPosition[n - 1] + agentPosition[k]); // this sums up all the values within the radius above to the total1.
} else break;// stops the program once it has passed a position of a distance of 1
}
newAgentPosition[i] = (total1 + total2) / numposition; // this calculates the new weighted average. ( sum of assigned random variable/ sum of position)
}
for (int i = 0; i <= n - 1; i++){
if (newAgentPosition[i] > originalAgentPosition[n - 1]){
newAgentPosition[i] = newAgentPosition[i] - originalAgentPosition[n - 1];
}
if(newAgentPosition[i] < 0) { // This checks if the agentPosition is smaller than 0 and then adds the largest agent to make all the elements within the range.
newAgentPosition[i] = newAgentPosition[i] + originalAgentPosition[n - 1];
}
}
t++; // This sums up how many iterations it will take.
double largestDiff = 0.0; // This assigns largestDiff to 0
for (int i = 0; i <= n-1; i++) {
double diff = Math.abs(agentPosition[i] - newAgentPosition[i]); // This calculates the difference between the previous and current array at position i.
if(diff > largestDiff) // If the difference between the agents is bigger than 0, assign it to the variable largestDiff.
largestDiff = diff;
}
if(largestDiff <= epsilon){ // This checks if the difference is bigger than the set epsilon,
break; // This stops the program if the difference is smaller than epsilon
}
agentPosition = new double[n];
System.arraycopy(newAgentPosition, 0, agentPosition, 0, n); // This takes the newly generated array(newAgentPosition), copyies each element starting from 0 to n and assigns it back to agentPosition. (this stops the problem j and with taking the newly created elements.)
}
for (int i = 0 ; i <= n - 1; i++) { // starting from position 1 it creates a random number between 0 and 0.999 and adds it to the previous agentPosition to fill the array in a random increasing way.
System.out.println(i + ": " + df.format(originalAgentPosition[i]) + "\t->\t" + df.format(agentPosition[i]));
}
int sumdofclusters = 1; // This sets the sum of clusters to 1
System.out.println("The different clusters are:\n" + df.format(agentPosition[0])); // This prints out the first cluster only.
for (int i = 1; i <= n - 1 ; i++) {
if(Math.abs(agentPosition[i] - agentPosition[i - 1]) >= epsilon) { // This checks if the element after the element at hand is different by a set epsilon.(how to work out different clusters)
sumdofclusters++; // This sums the number of clusters.
System.out.println(df.format(agentPosition[i])); // This prints out the different clusters other than the first 1.
}
}
System.out.println("Number of clusters is:" + sumdofclusters); // This prints out the number of clusters.
System.out.println("Number of iterations:" + t); // This prints out the number of iterations.
}
}
You can create a circular list using an array with modulus division.
getElementAt(double[] arr, int index)
{
index = index % arr.length;
index = index + arr.length; // If index is negative, modulus division gives us negative result, so this makes it positive.
index = index % arr.length; // In case the previous step made index >= n
return arr[index]
}
If n is arr.length then
0 <= index < n will be like normal.
n <= index will wrap around the list (e.g. arr[n] == arr[0], arr[n+1] == arr[1], etc.)
index < 0 will wrap around the list in the other direction (e.g. arr[-1] == arr[n-1], arr[-2] == arr[n-2], etc.)
so I'm currently working on an assignment that I just can't seem to finish. Well I have everything finished but would like the extra credit. I've been looking around the web and can't really seem to find exactly what I'm looking for.
public class PascalTester
{
public static void main(String[] args)
{
Scanner kb = new Scanner(System.in);
System.out.println("Welcome to the Pascal's Triangle program!");
System.out.println("Please enter the size of the triangle you want");
int size = kb.nextInt();
int[][] myArray = new int[size][size];
myArray = fillArray(myArray);
//myArray = calculateArray(myArray);
printArray(myArray); //prints the array
}
private static int[][] fillArray(int[][] array)
{
array[0][1] = 1;
for (int i = 1; i < array.length; i++)
{
for (int j = 1; j < array[i].length; j++)
{
array[i][j] = array[i-1][j-1] + array[i-1][j];
}
}
return array;
}
private static void printArray(int[][] array)
{
for (int i = 0; i < array.length; i++)
{
for (int j = 0; j < array[i].length; j++)
{
if(array[i][j] != 0)
System.out.print(array[i][j] + " ");
}
System.out.println();
}
}
}
The only issue that I'm having now is to properly format the output to look like an actual triangle. Any suggestions would be very helpful at this point in time. Thanks in advance
One approach to this, is, assuming you have all numbers formatted to the same width, is to treat the problem as that of centering the lines.
Java Coding left as exercise to reader but essentially:
for lineText : triange lines
leadingSpacesCount = (80/2) - lineText.length();
print " " x leadingSpacesCount + lineText
Try to use the technique at http://www.kodejava.org/examples/16.html to make an array with array.length - i - 1 spaces (need to add the number spaces between numbers.. and 2 number of 2 digit numbers if any..).
Print this array at the start of the outer for loop.
The challenge here is that you want to start printing at the top of the triangle, but you don't know where to center each row until you get to the last (and widest) row of the triangle. The trick is to not print anything until you know how wide the last row is. One way to do this is to generate all the rows as String (or StringBuilder) objects and compute the maximum width. Then, from the top, center each line by first printing an appropriate number of spaces. The correct number of spaces will be
(maxLineLength - currentLine.length()) / 2
Alternatively, you can simply assume a maximum line length and center all lines in that width. If the longer lines exceed the maximum width, then the triangle will be distorted below a certain row. (Just be sure to not try printing a negative number of spaces!)
If anyone is looking for the actual code to do this take a look at my implementation in Java, it's similar to what Craig Taylor mentioned (numbers formatted to the same width) plus it uses an algorithm to compute the elements without memory (or factorials).
The code has comments explaining each step (calculation and printing):
/**
* This method will print the first # levels of the Pascal's triangle. It
* uses the method described in:
*
* https://en.wikipedia.org/wiki/Pascal%27s_triangle#Calculating_a_row_or_diagonal_by_itself
*
* It basically computes the Combinations of the current row and col
* multiplied by the previous one (which will always be 1 at the beginning
* of each pascal triangle row). It will print each tree element to the output
* stream, aligning the numbers with spaces to form a perfect triangle.
*
* #param num
* # of levels to print
*/
public static void printPascalTriangle(int num) {
// Create a pad (# of spaces) to display between numbers to keep things
// in order. This should be bigger than the # of digits of the highest
// expected number and it should be an odd number (to have the same
// number of spaces to the left and to the right between numbers)
int pad = 7;
// Calculate the # of spaces to the left of each number plus itself
// (this is the width of the steps of the triangle)
int stepsWidth = pad / 2 + 1;
// Now calculate the maximum # of spaces from the left side of the
// screen to the first triangle's level (we will have num-1 steps in the
// triangle)
int spaces = (num - 1) * stepsWidth;
for (int n = 0; n < num; n++) {
// Print the left spaces of the current level, deduct the size of a
// number in each row
if (spaces > 0) {
System.out.printf("%" + spaces + "s", "");
spaces -= stepsWidth;
}
// This will represent the previous combination C(n k-1)
int prevCombination = 1;
for (int k = 1; k <= n + 1; k++) {
System.out.print(prevCombination);
// Calculate how many digits this number has and deduct that to
// the pad between numbers to keep everything aligned
int digits = (int) Math.log10(prevCombination);
if (digits < pad) {
System.out.printf("%" + (pad - digits) + "s", "");
}
// Formula from Wikipedia (we can remove that "+1" if we start
// the row loop at n=1)
prevCombination = prevCombination * (n + 1 - k) / k;
}
// Row separator
System.out.println();
}
}
Hope it helps someone!