How to Reverse an Int with For Loops - java

i am having trouble with reversing this code. what i am trying to have as
this is what i have so far but i can't seem to wrap my head around how the third for loop is supposed to be
public static void main(String[] args) {
Scanner input = new Scanner(System.in); //gets the users input
int rows;
int number = 0;
int i = 0;
rows = input.nextInt(); //takes the users input from console
while (rows <= 0) {
System.out.println("INVALID");
rows = input.nextInt();
}
for (int c = 1; c <= rows; c++) {
for (i = 0; i < c; i++) {
System.out.print(++number + " ");
}
for (int j = c; j < rows; j++) {
System.out.print("* * ");
}
for(i = 0; i < c; i++) {
System.out.print(number + " ");
//number--;
}
System.out.println();
}

Before running your last loop you should store number in some temp variable:
int temp = number;
for(i = 0; i < c; i++) {
System.out.print(temp-- + " ");
}

As I said in the comment, you need to decrement the number but at the same time need to keep track of the highest values in a line to use it as a starting value in the next iteration. Something like this should work:
public static void main(String[] args) {
int rows;
int number = 0;
int highestValue = 0;
int i = 0;
rows = 5;
for (int c = 1; c <= rows; c++) {
number = highestValue; // reset number to the highest value from previous line
for (i = 0; i < c; i++) {
System.out.print(++number + " ");
}
highestValue = number; // setting the highest value in line
for (int j = c; j < rows; j++) {
System.out.print("* * ");
}
for(i = 0; i < c; i++) {
System.out.print(number-- + " "); // decrementing
}
System.out.println();
}

Do you have to implement this yourself, because otherwise there are tons of libraries handling arrays.
The steps you have to take are:
Find a way to read the input (integers) in a single line and store them in some kind of container (either an array, or a list).
You may have to isolate what a single integer is (e.g. "1 2 3" is 3 integers, which you want to reverse, while "12 3" is just 2, and you only want to reverse 2).
You need to ensure that your input is valid (e.g. a user may enter "1 a b c")
You need to flip the integers within the container or better copy the original container in reverse order. For this, you only need to iterate over the container's elements and add them to the target container in reverse order
for (Integer in : inputList) {
outputList.addFirst(in);
}
If you only want to print the integers, you don't have to store them in a list, you could just iterate over the container in reverse order.

It seems to bit a pattern program, you can add the number-- in you sysout
public static void main( String[] args )
{
Scanner input = new Scanner(System.in); //gets the users input
int rows;
int number = 0;
int i = 0;
rows = input.nextInt(); //takes the users input from console
while (rows <= 0) {
System.out.println("INVALID");
rows = input.nextInt();
}
for (int c = 1; c <= rows; c++) {
for (i = 0; i < c; i++) {
System.out.print(++number + " ");
}
for (int j = c; j < rows; j++) {
System.out.print("* * ");
}
for(i = 0; i < c; i++) {
System.out.print(number-- + " ");
//number--;
}
System.out.println();
}
}
Such type of pattern you can create through collections

Related

Math Equation Pattern

I am creating a pattern that, when user enters the number of rows, prints a triangle with a specific number pattern. I am having a hard time coming up with a mathematical equation that will output this pattern:
I have already written a code that works but not with the pattern that I am wanting to create. Can someone help me?
Here's my code so far:
import java.util.Scanner;
public class trianglePattern {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.println("How many rows?: ");
int rows = input.nextInt();
for(int i =0;i<rows;i++) {
System.out.format("%"+4*(rows-i+1)+"s","");
for(int j=i+1; j>1; j--)
System.out.format("%4d", j);
for(int j=1; j<=i+1; j++)
System.out.format("%4d", j);
System.out.println();
}
}
}
Switched the loops, added a power function and fiddled a little with the loop indexes:
import java.util.Scanner;
public class trianglePattern {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.println("How many rows?: ");
int rows = input.nextInt();
for(int i = 0; i < rows; i++) {
System.out.format("%"+4*(rows-i+1)+"s","");
for(int j = 0; j <= i; j++)
System.out.format("%4d", (int) Math.pow(2,j));
for(int j = i - 1; j >= 0; j--)
System.out.format("%4d", (int) Math.pow(2,j));
System.out.println();
}
}
}
Nice problem...
Scanner input = new Scanner(System.in);
System.out.println("How many rows?: ");
int rows = input.nextInt();
ArrayList<Integer> list = new ArrayList<>();
for(int i=0; i<rows; i++) {
list.add(i);
}
for(int i=rows-2; i>-1; i--) {
list.add(i);
}
// I print this here just for your help(delete it afterwards)
for (Integer integer : list) {
System.out.print(((int) Math.pow(2, integer)) + " ");
}
System.out.println("\n");
for(int i=rows; i>=1; i--) {
for (Integer integer : list) {
int number = ((int) Math.pow(2, integer-i+1));
if(number>=1) {
System.out.format("%d\t", ((int) Math.pow(2, integer-i+1)));
} else {
System.out.print(" ");
}
}
System.out.println("\n");
}
(Tip): in the Arraylist list i save all the exponents i need to calculate the last row of the problem.
Try this. The spacing is based on several factors.
The sum of the field widths. Each field width is kept is a list. It is used to reduce the leading space based on the row being printed.
That each column field width is sized for the maximum value in that column. The width for a given column is also maintained in a list. Since the widths are symmetric about the central column, left side formats are also used to print right side values.
Scanner input = new Scanner(System.in);
System.out.println("How many rows?: ");
int rows = input.nextInt();
List<Integer> fws = new ArrayList<>();
List<String> fmts = new ArrayList<>();
Function<Integer, Integer> fw = r -> (int) (Math
.log10(1 << r)) + 2;
int sumWidths = 0;
for (int r = 0; r < rows; r++ ) {
int f = fw.apply(r);
fws.add(f);
sumWidths += f;
fmts.add("%" + f + "d");
}
rows--;
String pad = " ".repeat(sumWidths);
for (int r = rows; r >= 0; r--) {
System.out.print(pad);
int v = 1;
for (int c = r; c < rows; c++) {
System.out.printf(fmts.get(c), v);
v <<= 1;
}
System.out.printf(fmts.get(rows), v);
for (int c = rows-1; c >= r; c--) {
v >>= 1;
System.out.printf(fmts.get(c), v);
}
System.out.println();
pad = pad.substring(r > 0 ? fws.get(r-1) : pad.length());
}
}

My X's are being placed 1 space off in my histogram

import java.util.*;
public class HistogramGenerator {
public int getHeightOfHistogram(int[] occurences) {
// occurences = {1,0,0,0,1,0,0,0,0,1,0,0,0,2,0,0,0,0,0,0,0,0,0,0]
int max = occurences[0];
for (int i = 1; i < occurences.length; i++) {
if (occurences[i] > max) {
max = occurences[i];
}
}
return max;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a line: ");
String sentenceEntered = sc.nextLine();
System.out.println("Letter Histogram");
HistogramGenerator histogram = new HistogramGenerator();
String letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; //Map of all the characters
int[] occurences = new int[letters.length()]; //max size of all possible matches
// loop through sentenceEntered to find occurences of each character
for (int i = 0; i < sentenceEntered.length(); i++) {
int charValue = sentenceEntered.charAt(i);
int index = letters.indexOf(charValue); // index of the character we are searching for
if (index < 0)
continue;
occurences[index]++;
}
int heightOfHistogram = histogram.getHeightOfHistogram(occurences);
String[][] histogramArray = new String[heightOfHistogram][letters.length()]; //[2][26]
for (int j =0; j < occurences.length; j++) {
int numXtoInsert = occurences[j];
while(numXtoInsert > 0){
histogramArray[heightOfHistogram - numXtoInsert][j] = "X";
numXtoInsert--;
}
}
// print 26 dashes (length of letters)
for(int k=0; k < letters.length(); k++){
System.out.print("-");
}
System.out.println();
// print histogram
for(int row =0; row < histogramArray.length; row++){
for(int col=0; col < histogramArray[row].length; col++){
if (histogramArray[row][col] == null) {
System.out.print("");
continue;
}
System.out.print(histogramArray[row][col] + " ");
}
System.out.println();
}
System.out.println();
// print 26 dashes ( length of letters)
for(int u=0; u < letters.length(); u++){
System.out.print("-");
}
System.out.println();
// print all characters in letters
System.out.print(letters);
}
}
basically whatever word i put in it prints out something close to it, but not really correctly, if i type in apple for example it'll print out an X close to A, and X on P and an X close to P, and and X close to l and E.
maybe there's something wrong with the logic? I don't know, need some quick help!
The issue is with the printing logic. When you find a null value, you need to print a space. When you don't find a null value, you should not add an extra space. See below for the updated working logic:
// print histogram
for(int row =0; row < histogramArray.length; row++){
for(int col=0; col < histogramArray[row].length; col++){
if (histogramArray[row][col] == null) {
System.out.print(" ");
continue;
}
System.out.print(histogramArray[row][col]);
}
System.out.println();
}
System.out.println();

Making Tree with Nested Loops

So, for my programming class, our teacher tasked us with making a tree out of *'s and other random characters. There has to be a star at the top of the tree that increases in size every so often, depending how large the user wants the tree. For some reason, if the number the user enters is greater than 15, the bottom half is too far to the right. I tried changing my code, but then everything less than 15 is too far the right. How can I get that to work?
Scanner scan = new Scanner(System.in);
System.out.println("Enter the size of the tree you would like");
int a = scan.nextInt();
int b = 0;
int c = 0;
int d = 0;
if ( a >= 12){
d = 1;
} else {
d = 0;
}
//Top Half of Star
for (int i = 0; i < a / 4; i++) {
for (int j = i; j < a; j++){
System.out.print(" ");
}
for (int j = 0; j < 2 * i + 1; j++){
System.out.print("*");
b = b + 1;
}
System.out.println("");
}
//Bottom Half of Star
for (int i = 1; i < a/4; i++){
for (int j = d; j < a; j++){
System.out.print(" ");
}
for (int j = c; j < b/3; j++){
System.out.print("*");
}
c = c + 2;
d = d - 1;
System.out.println("");
I think this is what you're looking for, if you're defining the size as the number of rows.
import java.util.Scanner;
public class NestedTree
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter the size of the tree you would like");
int size = scan.nextInt(); // Get the size of the tree
for (int i = 0; i < size; i++) {
int spaces = size - i;
for (int s = 0; s < spaces; s++) { // Print spaces
System.out.print(" ");
}
for (int r = 0; r <= i; r++) { // Print stars
System.out.print("* ");
}
System.out.print("\n"); // new line
}
}
}

Printing a triangle of prime numbers using for loop

I am trying to make a triangle of prime numbers .. the number of rows will be user defined
for example if user gives "4" as number of rows then the program should show a triangle of prime numbers containing 4 rows
input :4
output :
2
3 5
7 11 13
17 19 23 29
These are two tasks: get the list of primes (or just something like nextPrime(int)) and get the triangle, both are very simple.
For the implementation of first, you may look at Next Prime number Java only working with certain numbers
For the implementation of second, just do something like:
for (int i = 1; i <= n; ++i) {
for (int j = 0; j < i; ++j) {
nextPrime = ...
System.out.print (nextPrime + " ");
}
System.out.println ();
}
Let say you already have your primes (sufficient amount).
int[] primes = ...;
Then for N strings create array is StringBuilders and fill them up with your numbers:
StringBuilder[] builders = new StringBuilder[N];
int count = 0;
for(int row = 0; row < N; row++) {
int size = row + 1;
builders[row] = new StringBuilder();
for(int i = 0; i < size; i++) {
builders[row].append(primes[count++]);
builders[row].append(' ');
}
}
And then you may print them
for(StringBuilder sb : builders)
System.out.println(sb);
//please try these
import java.util.*;
public class primePtt1
{
public static boolean isPrimeNumber(int num) {
int c=0;
for (int i = 1; i <= num; i++) {
if (num % i == 0)
c++;
}
if (c==2)
return true;
else
return false;
}
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.print("\nEnter no. of rows : ");
int rows = sc.nextInt();
int counter = 2;
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= i; j++) {
/* Try to find next prime number by incrementing counter and testing it for primality */
while(!isPrimeNumber(counter)){
counter++;
}
System.out.print(counter+" ");
counter++;
}
System.out.println();
}
}
}

Getting each letter in a String only once

I'm writing a Java program for Horspool's algorithm, and am having a bit of trouble. I'm trying to create an array of chars that will hold each letter in a string, but I don't want duplicates of the letters. Right now this is my code:
public static void main(String[] args)
{
Scanner scanIn = new Scanner (System.in);
int count = 0;
int count2 = 0;
int inc = 0;
//The text to search for the phrase in
String t = "";
//The phrase/pattern to search for
String p = "";
System.out.println(" ");
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
System.out.println("Harspool's Algorithm: ");
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
System.out.println(" ");
System.out.println("Please enter the full text: ");
t = scanIn.nextLine();
System.out.println("Please enter the pattern to search for: ");
p = scanIn.nextLine();
char[] text = new char[t.length()];
char[] pattern = new char[p.length()];
char[] alphabet = new char[t.length()];
for (int i = 0; i < alphabet.length; i++)
{
alphabet[i] = ' ';
}
for (int i = 0; i < text.length; i++)
{
text[i] = t.charAt(i);
}
for (int i = 0; i < pattern.length; i++)
{
pattern[i] = p.charAt(i);
}
while (inc < text.length)
{
for (int j = 0; j < text.length; j++)
{
if (text[inc] != alphabet[j])
{
count++;
}
if (count == p.length() - 1 && count2 < text.length)
{
alphabet[count2] = text[inc];
count2++;
count = 0;
inc++;
}
}
}
for (int i = 0; i < alphabet.length; i++)
{
System.out.print(alphabet[i]);
}
}
I believe the problem is in the while loop, but I can't figure out what exactly is going wrong. Right now, it will print out the entire string passed in, when it should be printing each letter only once. Could someone please help?
Instead of counting the occurrences of each character, Use Set<Character>. A set contains unique elements and so you will not have duplicates that way.
You can also convert a Set to an array by doing mySet.toArray(new String[mySet.size()]); or just mySet.toArray(new String[0]);
Your code is not easy to read. You might consider using the following algorithm instead.
int ccount[256];
int ii;
for(ii=0;ii<256;ii++) ccount[ii]=0;
for (ii = 0; ii < text.length; ii++)
{
ccount[t.charAt(i)%256]++;
}
for (ii = 0; ii<256; ii++) {
if(ccount[ii]>0) System.out.printf("%c", ii);
}
EDIT - made sure ccount was initialized, and captured characters outside of range 0-255 with % operator.

Categories

Resources