pyramid printing using Java - java

Pyramid example
Note:
System.our.printf(“%n.mf”, num) will print out a float number num with width n and m decimal places.
Calculation of a^b in Java: Math.pow(a,b)
For the above pyramid printing, you may break the pattern into three parts: spaces on the left, numbers on the left and numbers on the right. For each line i, there are total 2*i-1 numbers.
public static void main(String[] args) {
int rows = 5, k = 0, count = 0, count1 = 0;
for(int i = 1; i <= rows; ++i) {
for(int space = 1; space <= rows - i; ++space) {
System.out.print(" ");
++count;
}
while(k != 2 * i - 1) {
if (count <= rows - 1) {
System.out.print((i + k) + " ");
++count;
}
else {
++count1;
System.out.print((i + k - 2 * count1) + " ");
}
++k;
}
count1 = count = k = 0;
System.out.println();
}
}
}

I decided to give this a try, mainly because I wanted to present some concepts having to do with problem-solving.
First, I made the height of the pyramid a variable. This forced me to consider how different pyramid heights would affect the width of each segment of each line.
Next, I decided to pre-calculate the powers of two. There's no point in recalculating the values for each line. So, I wrote a method to return a precalculated array of integers.
Next, I calculated how much space the largest power of two would take up. I formatted the number using the NumberFormat class. The NumberFormat class will format the number according to the Locale in which you're running the code. I used the format method of the String class to give each number enough space.
Next, I divided each line into a blank area, a number area, and a blank area. That way, I could work on each part of a line separately. The blank area on the left side of the pyramid line is the same length as the blank area on the right side of the line, so I only had to create it one time for each line.
I used a StringBuilder to create each line of the pyramid. It's faster to use a StringBuilder than to concatenate String values. I used StringBuilder segments to create the parts of a pyramid line.
I didn't use static methods because I wanted to show how you instantiate the class in the main method. In general, I try to avoid the use of static methods.
Here's the result of one test run. I assure you, I ran several dozen tests on this code.
1
1 2 1
1 2 4 2 1
1 2 4 8 4 2 1
1 2 4 8 16 8 4 2 1
1 2 4 8 16 32 16 8 4 2 1
1 2 4 8 16 32 64 32 16 8 4 2 1
1 2 4 8 16 32 64 128 64 32 16 8 4 2 1
1 2 4 8 16 32 64 128 256 128 64 32 16 8 4 2 1
1 2 4 8 16 32 64 128 256 512 256 128 64 32 16 8 4 2 1
Here's the code.
import java.text.NumberFormat;
public class NumberPyramid {
public static void main(String[] args) {
int power = 10;
NumberPyramid np = new NumberPyramid();
np.createPyramid(power);
}
private static final NumberFormat NF =
NumberFormat.getNumberInstance();
public void createPyramid(int power) {
int[] values = createPowersArray(power);
String maximum = NF.format(values[power - 1]);
int segmentSize = maximum.length() + 2;
String format = "%" + segmentSize + "s";
for (int index = 0; index < power; index++) {
StringBuilder builder = new StringBuilder();
StringBuilder blankArea = createBlankArea(
index, power, segmentSize);
builder.append(blankArea);
builder.append(createNumberArea(index, values, format));
builder.append(blankArea);
System.out.println(builder.toString());
}
}
private int[] createPowersArray(int power) {
int[] values = new int[power];
values[0] = 1;
for (int i = 1; i < power; i++) {
values[i] = values[i - 1] * 2;
}
return values;
}
private StringBuilder createNumberArea(int index,
int[] values, String format) {
StringBuilder builder = new StringBuilder();
for (int j = 0; j <= index; j++) {
builder.append(String.format(format,
NF.format(values[j])));
}
for (int j = index - 1; j >= 0; j--) {
builder.append(String.format(format,
NF.format(values[j])));
}
return builder;
}
private StringBuilder createBlankArea(int index,
int power, int segmentSize) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < power - index - 1; i++) {
builder.append(createBlankSegment(segmentSize));
}
return builder;
}
private StringBuilder createBlankSegment(int length) {
StringBuilder builder = new StringBuilder(length);
for (int i = 0; i < length; i++) {
builder.append(" ");
}
return builder;
}
}

find the answer below:
public class Main {
static int rows = 10;
public static void main(String[] args) {
LinkedList<Integer> numbers = new LinkedList<>();
for(int i = 1 ; i <= rows ; i++){
if(i ==1 ) numbers.add(1);
else {
int totalNumber = i * 2 -1;
insertNumbers(totalNumber, numbers);
}
printNumbers(numbers, i);
System.out.println();
numbers.clear();
}
}
private static void insertNumbers(int totalNumber, LinkedList<Integer> numbers) {
int numbersOnEachSide = (totalNumber - 1) / 2;
for (int i = 0; i < numbersOnEachSide ; i++ ) numbers.add((int) Math.pow(2, i));
numbers.add((int) Math.pow(2,numbersOnEachSide));
for(int i = 0 ; i < numbersOnEachSide ; i++) numbers.add((int) Math.pow(2, numbersOnEachSide-1-i));
}
private static void printNumbers(LinkedList<Integer> numbers, int i) {
int spaceNorows = rows - i;
printSpaces(spaceNorows);
for (Integer number : numbers) {
System.out.print(number + "\t");
}
printSpaces(spaceNorows);
}
private static void printSpaces(int spaceNorows) {
for(int j = 0 ; j< spaceNorows ; j++) System.out.print("\t");
}
}
output:
1
1 2 1
1 2 4 2 1
1 2 4 8 4 2 1
1 2 4 8 16 8 4 2 1
1 2 4 8 16 32 16 8 4 2 1
1 2 4 8 16 32 64 32 16 8 4 2 1
1 2 4 8 16 32 64 128 64 32 16 8 4 2 1
1 2 4 8 16 32 64 128 256 128 64 32 16 8 4 2 1
1 2 4 8 16 32 64 128 256 512 256 128 64 32 16 8 4 2 1
p.s please take a look at https://stackoverflow.com/tour to ask a proper question in later posts.
EDIT : How to run the code in CMD
To run the application above:
1- save all the code above in a file named - for example - Main.java
2- run CMD in windows or terminal in linux and compile the Main.java using javac Main.java.
3- The compiled file will be put in the same directory as the java file.
4- run the compiled class using java Main.
change Main to whatever name you give to the file
Since you are running the code in the cmd it might not display the 10 row pyramid properly(due to screen resolution, size, etc). So,
change the row field in static int rows = 10; to 5 to see the
pyramid properly.
You can further changing the fixed row number to dynamically get it from user.

Related

Trying to write a code that goes from 10-1 and back

I am trying to write code that goes from 10-1 and back:
10
9
8
7
6
5
4
3
2
1
0
1
2
3
4
5
6
7
8
9
10
I cannot figure it out. I've got this so far:
package numbers;
class Numbers {
protected static Object Numbers;
public static void main(String[] args) {
int n;
for(n=10; n>=0; n--) { //count BACKWARDS
//if n <=0 n = 1
System.out.println(n);
}
}
}
You can use two for loops.
for(int i = 10; i > 0; i--) System.out.println(i);
for(int i = 0; i <= 10; i++) System.out.println(i);
Here is one way. Based on your expected output I presume you mean from ten to zero and back. Go from -10 to 10 inclusive and change the sign when < 0.
uses the ternary operater (?:) (e.g) a ? b : c
given a conditional, if a is true, do b, else to c
for (int i = -10; i <= 10 ; i++) {
System.out.printf("%d ",i < 0 ? -i : i);
}
Prints
10 9 8 7 6 5 4 3 2 1 0 1 2 3 4 5 6 7 8 9 10
You can also change the print statement to to use the absolute value.
System.out.printf("%d ",Math.abs(i));
But here is the fun one. A recursive solution. Just not very efficient. It keeps printing the adjusted value and calling itself until the condition is met, then returns and prints values on the call stack in ascending order.
tenToOneToTen(10);
public static void tenToOneToTen(int i) {
if (i > 0) {
System.out.printf("%d ",i);
tenToOneToTen(i-1);
}
System.out.printf("%d ", i);
}

How To Sort Subsets in Java

Dear friends I have an assignment and I almost solved it. But I'm having a big problem recently which I couldn't figure a way out for 2 days. If you could help me I would very appreciate it!
So, let's say user entered 5 (N) I immediately create this sequence to get subsets out of it: {1,2,3,4,5}
If N = 4 than the sequence is like: {1, 2, 3, 4} etc.
Than this code below generates all kind of the variations of subsets:
public static int[] genarator(int N)
{
int[] generator = new int[(int) Math.pow(2, N)];
int[] binDigit = new int[(int) Math.pow(2, N)];
for (int i = 0; i < Math.pow(2, N); i++)
generator[i] = (i >> 1) ^ i; // Right Shifting
for (int i = 0; i < Math.pow(2, N); i++)
{
int one = 1;
binDigit[i] = 0;
while (generator[i] > 0)
{
binDigit[i] += (generator[i] % 2) * one;
generator[i] /= 2;
one = one * 10;
}
}
return binDigit;
}
And the way it returns the results like this (In case of: N = 4 {1, 2, 3, 4}) shown here :
1
1 2
2
2 3
1 2 3
1 3
3
3 4
1 3 4
1 2 3 4
2 3 4
2 4
1 2 4
1 4
4
But my lecturer wants from my program to return the result in this order:
1
2
3
4
1 2
1 3
1 4
2 3
2 4
3 4
1 2 3
1 2 4
1 3 4
2 3 4
1 2 3 4
I for now use TreeSet<Long> and parseLong so I can get true results till 1 <= N <= 9. But whenever user enters 10 or higher as N it goes crazy.
To recap, my question is how can I store those numbers which I get from int[] genarator(int N) and display them like my lecturer requires ?
How generator works and how do I get numbers in wrong order? Code is below:
int N = read.nextInt();
int[] sequence = new int[N];
for (int i = 0; i < N; i++)
sequence[i] = i + 1;
int[] tempArray = new int[(int) Math.pow(2, N)];
tempArray = genarator(N);
for (int i = 1; i < Math.pow(2, N); i++)
{
for (int j = 0; j < N; j++)
{
if (tempArray[i] % 10 == 1)
{
System.out.print(sequence[j] + " ");
}
tempArray[i] /= 10;
}
System.out.println();
}
Thank you for checking and I am really sorry for this too long question. But I couldn't make it clear with a short explanation.
What you can do is create a set abstraction that can be compared to other sets. See Java tutorials on Comparators.
//don't call this Set as there is already a Java Set
//interface that youdon't want to confuse yourself with
public class MySet implements Comparable<MySet>{
int[] backingArray;
public MySet(int n) {
//initialize the Set
this.backingArray = generator(n);
}
public static Int[] generator(int n) {
//..whatever you do to generate your results
}
#Override
public int compareTo(MySet otherSet) {
//define how sets are compared (e.g what your professor is asking.
//In your example, if one set is shorter than another,
//it is considered 'smaller')
}
}
Set<MySet> allSets = ....;
and simply invoke Collections.sort(allSets);

Using Loops to print patterns

Hey guys so I'm working on a problem where I need to print
1 2 3 4 5 6
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
public class Set_5_P5_18b {
public static void main(String[] args) {
int x;
String y;
x = 1;
y = "";
System.out.println("Pattern B:");
while (x < 7) {
y = y + x + " ";
x++;
}
System.out.println(y);
}
}
What I wrote above print's the first line but I can't figure out how to modify it to print the second, could anyone help me please?
Yuo need the outer for loop to run for say x ranging from values 6 to 1. For each value of x you need a inner loop that runs for values 1 ... x and prints out values in a line.
Keep this in mind and try to come up with pseudo code first and then the implementation code.
you'd have to reset the variables x, when you quit while :P
So commonly when you are writing a for loop and you realize that you want a certain aspect of the for loop to change each time the program iterates, 9/10 times you want to use nested for loops (for loop within a for loop).
So essentially every time that you iterate through the for loop you want to have the duration of the for loop decrease. So...
for (int num =1; num < <number that you want to change>; num++) {}
Here is the code method.
public static void print(int x) {
for (int lengthOfFor = x; lengthOfFor > 0; lengthOfFor--) {
for (int num = 1; num <= lengthOfFor; num++) {
System.out.print(num + " ");
}
System.out.print("\n");
}
}
This is how you would do call the method.
public class print
{
public static void print(int x) {
for (int lengthOfFor = x; lengthOfFor > 0; lengthOfFor--) {
for (int num = 1; num <= lengthOfFor; num++) {
System.out.print(num + " ");
}
System.out.print("\n");
}
}
public static void main (String[] args) {
print(6);
}
}
Your output can be observed like a 2-dimensional array where:
index i grows top-to-bottom and represents row index
index j grows left-to-right and represents column index
What you are doing right now is iterating over the columns of the first row and that is it.
As mentioned in the comments, you should add a second loop to iterate over the rows as well.
Here is how you can achieve this with two for loops:
int colSize = 6;
int rowSize = 6;
for(int i = 1; i <= rowSize; i++) {
for(int j = 1; j <= colSize; j++) {
System.out.print(j + " "); // print individual column values
}
System.out.println(); // print new line for the next row
colSize--; // decrement column size since column size decreases after each row
}
java-8 solution:
public static void printPattern(int rows) {
IntStream.range(0, rows).map(r -> rows - r).forEach(x -> {
IntStream.rangeClosed(1, x).forEach(y -> {
System.out.print(String.format("%3d", y));
});
System.out.println();
});
}
Usage:
printPattern(9);
Output:
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7
1 2 3 4 5 6
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1

How to make a java program with output a triangle of numbers?

I understand that there is a similar post to this one, but based on the answers I can not both apply the answers to my current class, or understand the rest of the answers.
I need to create a program using nested "for loops" that creates an output like this one (just symmetrical). I have been trying to get this to work for two whole evenings now, and can't figure it out...
1
1 2 1
1 2 4 2 1
1 2 4 8 4 2 1
1 2 4 8 16 8 4 2 1
1 2 4 8 16 32 16 8 4 2 1
1 2 4 8 16 32 64 32 16 8 4 2 1
1 2 4 8 16 32 64 128 64 32 16 8 4 2 1
I would GREATLY appreciate any help!!!
public class PyramidOfDoom {
public static void main(String[] args)
int k = 2;
int totalWidth = 8;
for (int row = 1; row <= totalWidth; row++) {
for (int col = 1; col <= totalWidth; col++) {
if (col <= totalWidth - row) {
System.out.print(" ");
} else {
System.out.print(k);;
}
}
System.out.println();
}
}
}
I thinks it can be done in simple steps as 1. print leading spaces 2. print increasing numbers 3. print decreasing number 4. print trailing spaces 5 print new line.
Sample code(concept) as below.
int row = 10;
for(int i=1; i<=numRow ; i++){
int num = 1;
for(int j=0; j<numRow- i; j++ ){
System.out.print(" ");
}
for(int j=numRow-i+1; j<=numRow ; j++ ){
System.out.print(num+" ");
num=num*2;
}
num=num/2;
for(int j=numRow+1; j<numRow+i; j++ ){
num=num/2;
System.out.print(num+" ");
}
for(int j=numRow+i+1; j<=numRow*2; j++ ){
System.out.print(" ");
}
System.out.print("\n");
}
You're not changing k at all. You need to keep multiplying it by 2 until you get to the middle of the row, then start dividing it by 2. As it stands, in your System.out.println(k), how can you expect it to print anything but 2 if you never manipulate it? :)
Also, you have two semicolons in your System.out.println(k);;. That seems odd to me, but I suppose it actually makes sense that it would compile.

how to find 2 to the power of n . n ranges from 0 to 200

Assume my system as 32 bit machine. Considering this if I use long int for n>63 I will get my value as 0. How to solve it?
double is perfectly capable of storing powers of two up to 1023 exactly. Don't let someone tell you that floating point numbers are somehow always inexact. This is a special case where they aren't!
double x = 1.0;
for (int n = 0; n <= 200; ++n)
{
printf("2^%d = %.0f\n", n, x);
x *= 2.0;
}
Some output of the program:
2^0 = 1
2^1 = 2
2^2 = 4
2^3 = 8
2^4 = 16
...
2^196 = 100433627766186892221372630771322662657637687111424552206336
2^197 = 200867255532373784442745261542645325315275374222849104412672
2^198 = 401734511064747568885490523085290650630550748445698208825344
2^199 = 803469022129495137770981046170581301261101496891396417650688
2^200 = 1606938044258990275541962092341162602522202993782792835301376
Just wait around for a 256-bit compiler, then use int :-)
No, seriously, since you just want to start with 1 and keep doubling, your best bet is to get a big integer library like GNU MP.
You would do that with a piece of code like (untested):
#include <stdio.h>
#include "gmp.h"
int main (void) {
int i;
mpz_t num;
mpz_init_set_ui (num, 1);
for (i = 0; i <= 200; i++) {
printf ("2^%d = ", i);
mpz_out_str (NULL, 10, num);
printf ("\n");
mpz_mul_ui (num, num, 2);
}
return 0;
}
You could code up your own data structure of an array of longs with only two operations, double and print but I think it would be far easier to just use GMP.
If you do want to roll your own, have a look at this. It's a variation/simplification of some big integer libraries I've developed in the past:
#include <stdio.h>
#include <stdlib.h>
// Use 16-bit integer for maximum portability. You could adjust
// these values for larger (or smaller) data types. SZ is the
// number of segments in a number, ROLLOVER is the maximum
// value of a segment plus one (need to be less than the
// maximum value of your datatype divided by two. WIDTH is
// the width for printing (number of "0" characters in
// ROLLOVER).
#define SZ 20
#define ROLLOVER 10000
#define WIDTH 4
typedef struct {
int data[SZ];
} tNum;
// Create a number based on an integer. It allocates the segments
// then initialises all to zero except the last - that one is
// set to the passed-in integer.
static tNum *tNumCreate (int val) {
int i;
tNum *num = malloc (sizeof (tNum));
if (num == NULL) {
printf ("MEMORY ERROR\n");
exit (1);
}
for (i = 0; i < SZ - 1; i++) {
num->data[i] = 0;
}
num->data[SZ-1] = val;
}
// Destroy the number. Simple free operation.
static void tNumDestroy (tNum *num) {
free (num);
}
// Print the number. Ignores segments until the first non-zero
// one then prints it normally. All following segments are
// padded with zeros on the left to ensure number is correct.
// If no segments were printed, the number is zero so we just
// output "0". Then, no matter what, we output newline.
static void tNumPrint (tNum *num) {
int i, first;
for (first = 1, i = 0; i < SZ; i++) {
if (first) {
if (num->data[i] != 0) {
printf ("%d", num->data[i]);
first = 0;
}
} else {
printf ("%0*d", WIDTH, num->data[i]);
}
}
if (first) {
printf ("0");
}
printf ("\n");
}
// Double a number. Simplified form of add with carry. Carry is
// initialised to zero then we work with the segments from right
// to left. We double each one and add the current carry. If
// there's overflow, we adjust for it and set carry to 1, else
// carry is set to 0. If there's carry at the end, then we have
// arithmetic overflow.
static void tNumDouble (tNum *num) {
int i, carry;
for (carry = 0, i = SZ - 1; i >= 0; i--) {
num->data[i] = num->data[i] * 2 + carry;
if (num->data[i] >= ROLLOVER) {
num->data[i] -= ROLLOVER;
carry = 1;
} else {
carry = 0;
}
}
if (carry == 1) {
printf ("OVERFLOW ERROR\n");
exit (1);
}
}
// Test program to output all powers of 2^n where n is in
// the range 0 to 200 inclusive.
int main (void) {
int i;
tNum *num = tNumCreate (1);
printf ("2^ 0 = ");
tNumPrint (num);
for (i = 1; i <= 200; i++) {
tNumDouble (num);
printf ("2^%3d = ", i);
tNumPrint (num);
}
tNumDestroy (num);
return 0;
}
and its associated output:
2^ 0 = 1
2^ 1 = 2
2^ 2 = 4
2^ 3 = 8
2^ 4 = 16
2^ 5 = 32
2^ 6 = 64
2^ 7 = 128
2^ 8 = 256
2^ 9 = 512
: : : : :
2^191 = 3138550867693340381917894711603833208051177722232017256448
2^192 = 6277101735386680763835789423207666416102355444464034512896
2^193 = 12554203470773361527671578846415332832204710888928069025792
2^194 = 25108406941546723055343157692830665664409421777856138051584
2^195 = 50216813883093446110686315385661331328818843555712276103168
2^196 = 100433627766186892221372630771322662657637687111424552206336
2^197 = 200867255532373784442745261542645325315275374222849104412672
2^198 = 401734511064747568885490523085290650630550748445698208825344
2^199 = 803469022129495137770981046170581301261101496891396417650688
2^200 = 1606938044258990275541962092341162602522202993782792835301376
python supports big integers out of the box. At any linux prompt, run this:
$ python -c "for power in range(201): print power, 2**power"
0 1
1 2
2 4
3 8
4 16
5 32
6 64
<snip>
196 100433627766186892221372630771322662657637687111424552206336
197 200867255532373784442745261542645325315275374222849104412672
198 401734511064747568885490523085290650630550748445698208825344
199 803469022129495137770981046170581301261101496891396417650688
200 1606938044258990275541962092341162602522202993782792835301376
This can be easily made into a script if necessary. See any python tutorial.
It's been ages since I've used Java seriously, but: BigInteger class? It has all the usual mathematical (multiply, pow) and bitwise (shiftLeft) operations.
Your tagging is a little confusing though, which language did you prefer?
Use java.math.BigInteger.shiftLeft.
for (int i = 0; i <= 200; i++) {
System.out.format("%d = %s%n", i, BigInteger.ONE.shiftLeft(i));
}
Excerpt of output:
0 = 1
1 = 2
2 = 4
3 = 8
4 = 16
:
197 = 200867255532373784442745261542645325315275374222849104412672
198 = 401734511064747568885490523085290650630550748445698208825344
199 = 803469022129495137770981046170581301261101496891396417650688
200 = 1606938044258990275541962092341162602522202993782792835301376
If BigInteger is unavailable, you can also just manually do the multiplication and store it in a String.
String s = "1";
for (int i = 0; i < 200; i++) {
StringBuilder sb = new StringBuilder();
int carry = 0;
for (char ch : s.toCharArray()) {
int d = Character.digit(ch, 10) * 2 + carry;
sb.append(d % 10);
carry = d / 10;
}
if (carry != 0) sb.append(carry);
s = sb.toString();
System.out.format("%d = %s%n", i + 1, sb.reverse());
}
(see full output)
In C/C++ I don't know of a standard way you can store integers that big, pax's solution is the rightway to go.
However for Java, you do have a way out, BigInteger
Use scheme!
1 => (expt 2 200)
1606938044258990275541962092341162602522202993782792835301376
in kotlin :
var x= readLine()!!.toInt()
var y=BigDecimal(1)
for (i in 1..x)
{
y *= BigDecimal(2)
}
println(DecimalFormat().format(y))
If unsigned long int is 64 bits then the largest value for 2^n that you can represent is 2^63 (i.e. n = 63):
unsigned long int x = (1UL << n); // n = 0..63

Categories