I'm stuck on this question:
Printing stars and spaces
Define a method called printSpaces(int number) that produces the
number of spaces specified by number. The method does not print the
line break.
You will also have to either copy the printStars method your previous
answer or reimplement it in this exercise template. Printing a
right-leaning triangle
Create a method called printTriangle(int size) that uses printSpaces
and printStars to print the correct triangle. So the method call
printTriangle(4) should print the following: Sample output
> *
> **
> ***
> ****
I cannot get the spaces thing to work on the first question, and I'm totally lost on making the recursive triangle. I see that lots of answers are using for loops, however the class I'm working in wants them done as methods. I can't comprehend how to properly translate that. I got the triangle the other way around with this:
public class Test072 {
public static void main(String[] args) {
printTriangle(4);
}
public static void printTriangle(int size) {
int numSize = 0;
while (numSize < size) {
printStars(numSize);
numSize++;
}
}
public static void printStars(int number) {
int numStar = 0;
while (numStar <= number) {
System.out.print("*");
numStar++;
}
System.out.println();
}
}
Once we started adding spaces in, I totally got lost and have no idea how to call what and when. I don't know how to properly call the space method into the triangle method as they are asking.
This should do the job.
public static void printTriangle(int size) {
int numSize = 0;
while (numSize < size) {
printSpaces(size - numSize - 1);
printStars(numSize);
numSize++;
}
}
public static void printSpaces(int number) {
int numSpaces = 0;
while (numSpaces < number) {
System.out.print(" ");
numSpaces++;
}
}
public static void printStars(int number) {
int numStar = 0;
while (numStar <= number) {
System.out.print("*");
numStar++;
}
System.out.println();
}
}
//printStars is printing "number" numbers of stars on one line with a line break
public static void printStars(int number) {
for(int i=1;i<=number;i++){
System.out.print("*");
}
System.out.println();
}
//printSpaces print "number" number of spaces on one line
public static void printSpaces(int number) {
for(int i=1;i<=number;i++){
System.out.print(" ");
}
}
public static void printTriangle(int size) {
for(int i=1;i<=size;i++){
printSpaces(size-i);
printStars(i);
}
}
Related
I am trying to convert the following iterative code:
int rows = 3;
for (int i = 0; i <= rows; i++)
{
for (int j = 0; j < i; j++)
{
System.out.print("*");
}
for (int j = 0; j < rows-i; j++)
{
System.out.print("-");
}
System.out.println();
}
with the output:
---
*--
**-
***
to recursive code. This is for an assignment. I created the iterative code in hopes of being able to figure out how to directly convert it to recursive. Here's my effort of that:
public void stringY(int star, int count){
if (star > 0){
System.out.print("*");
stringY(star - 1, count);
}
}
public void stringX(int dash,int count){
if (dash == -1) {
return;
}else if (dash < count){
System.out.print("-");
stringX(dash - 1, count);
} else if (dash == count){
stringX(dash - 1, count);
}
}
public void printPattern(int n) {
if (n == -1){
return;
} else {
printPattern(n-1);
stringY(n, n);
stringX(n, n);
System.out.println();
}
}
My issue here is that while I get the output I am looking for with regard to the "*" part of the pattern, I have absolutely no clue how to get the "-" part of the pattern. Now being that this is an assignment I don't want any solutions, but any pointers in the right direction are absolutely welcome. I should note that my two requirements are: 1) I have to complete my assignment entirely without using loops and 2) I can use as many helper methods as I need, but the main calling method (printPattern) must stay public void and must continue to only accept integers. Further clarification: The other two methods in the recursive code block are helper methods I created.
First let m = number of '*' to print and let n = number of '-' to print
For each recursion, increment m by 1 and decrement n by 1.
public static void main(String[] args) {
printPattern(3);
}
public static void printPattern(int n) {
printing(n, n);
}
//Variable size basically represent the number of columns
public static void printing(int n, int size) {
//stop condition
if(n == -1)
return;
//m is the number of * to print
int m = size - n;
printAsterisk(m);
//n is the number of - to print
printHyphen(n);
System.out.println();
printing(n - 1, size);
}
public static void printAsterisk(int m) {
if(m == 0)
return;
System.out.print('*');
printAsterisk(m - 1);
}
public static void printHyphen(int n) {
if(n == 0)
return;
System.out.print('-');
printHyphen(n - 1);
}
Think of it this way, they are all just loops doing some work. All you need is theoretically one recursive function that calls itself till the passed value.
void loop(int i, int till, Worker doThis) {
if (i>=till) return;
doThis.work(i);
loop(i+1, till, doThis);
}
Worker is just an interface,
public interface Worker {
void work(int index);
}
Now we need to pass the work that needs to be done. There are three loops, hence three calls to the loop function.
final int rows = 3;
// outer loop
loop(0, rows+1, new Worker() {
public void work(int index) {
// Stars
loop(0, index, new Worker() {
public void work(int index) {
System.out.print("*");
}
});
// Dashes
loop(0, rows-index, new Worker() {
public void work(int index) {
System.out.print("-");
}
});
System.out.println();
}
});
I would start by extracting then STAR and DASH,
private static final String DASH = "-";
private static final String STAR = "*";
Next, I would write a method to repeat a String a given number of times. Also, I would use a StringBuilder (here I've done it recursively)
private static StringBuilder repeat(StringBuilder sb, String str, int n) {
if (n > 0) {
sb.append(str);
repeat(sb, str, n - 1);
}
return sb;
}
Next, a private recursive method to print the pattern based on StringBuilder
private static void printPattern(StringBuilder sb, int s) {
System.out.println(sb);
int p = sb.indexOf(DASH, s);
if (p > -1) {
sb.replace(p, p + DASH.length(), STAR);
printPattern(sb, s + STAR.length());
}
}
And finally the public method
public static void printPattern(int n) {
printPattern(repeat(new StringBuilder(), DASH, n), 0);
}
I'm trying to print a figure that prints 3 spaces then a star, then the next line prints 2 spaces, / and a star, and then 1 space, // and a star and so on.
I've got the code to print all the slashes and stars, but I can't figure out how to get the spaces to print with a descending number. This is for an assignment and I have to use nested for loops. Any thoughts?
PS I don't want an exact answer (i.e. "type in this code"), I just want a suggestion to try to point me in the right direction.
What I have so far is (H is the scale):
public class Pattern { //program that prints a boxed-in design
public static final int H = 9;
public static void main(String[] args) {
line();
design();
}
public static void line() {
System.out.print("+");
for (int d=1; d <=H-2; d++) {
System.out.print("-");
}
System.out.println("+");
}
public static void design() {
top();
}
public static void top() {
for (int row = 1; row <=H-2; row++){
System.out.print("|");
for (int sp =3; sp>=1; sp--){
System.out.print(" ");
}
for (int fsl=1; fsl<=row-1; fsl++){
System.out.print("/");
}
for (int star=1; star<=1; star++){
System.out.print("*");
}
for (int bsl=1; bsl<=row-1; bsl++){
System.out.print("\\");
}
System.out.print("|");
System.out.println();
}
}
}
So if I understand correctly, your row variable goes from 1 through 4, and you want 3 spaces in row 1, 2 spaces in row 2, 1 space in row 3 and 0 spaces in row 4? I suggest you should be able to find an arithmetic expression (like you have already found row-1 for the number of slashes) to give you the correct number of spaces on each line/row. If I need to say more, feel free to add a comment to this answer.
package com.acme;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import static java.util.Comparator.reverseOrder;
public class PrintIt {
public static void main(String[] args) {
printSpacesWithStar(10, Order.ASC);
printSpacesWithStar(10, Order.DESC);
}
private static void printSpacesWithStar(int numbers, Order order) {
Stream<Integer> streamOfInt = IntStream.rangeClosed(1, numbers)
.boxed();
switch (order) {
case ASC:
streamOfInt
.sorted(reverseOrder())
.forEach(Test::printingLogic);
break;
case DESC:
streamOfInt
.forEach(Test::printingLogic);
break;
}
}
private static void printingLogic(Integer currentValue) {
for (int k = 1; k < currentValue; k++) {
System.out.print(" ");
}
System.out.println("*");
}
enum Order {
ASC, DESC;
}
}
I am able to create a Max Heap using a function heapify() but when i try to call it again(to delete max and create a sorted array) the program gets stuck/doesn't stop taking input. What's wrong?
Is this a memory problem?If I increase the number of calls by increasing the frequency of for loop it still works fine.
public class HeapSort
{
int[] heap;
public void sort(int length)
{
int temp;
for(int i=length;i>=1;i--)
{
heapify(i,length);
}
//if I try to call heapify again(even once) after this,the program gets stuck
}
public void heapify(int i,int l)
{
int lchild=2*i,rchild,max;
int temp;
while(lchild<=l)
{
rchild=(2*i)+1;
if(rchild<=l)
max=(heap[lchild]>heap[rchild])? lchild:rchild;
else
max=lchild;
if(heap[i]<heap[max])
{
temp=heap[i];
heap[i]=heap[max];
heap[max]=temp;
i=max;
}
lchild=2*i;
}
}
public static void main(String args[]) throws IOException
{
BufferedReader r= new BufferedReader(new InputStreamReader(System.in));
int length=Integer.parseInt(r.readLine());
HeapSort Heap=new HeapSort();
Heap.heap=new int[length+1];
for(int i=1;i<=length;i++)
Heap.heap[i]=Integer.parseInt(r.readLine());
Heap.sort(length);
for(int i=1;i<=length;i++)
System.out.print(Heap.heap[i]+" ");
}
}
Heapify should be done for length/2 iterations because it is like a tree structure.
Here is a complete code for heap sort...This sort array 's'
public class HeapSort {
public static void main(String[] args) {
String s[]={"aaaa","dddd","cccc","gggg","bbbbb"};
AsHeap(s);
HeapSort(s);
for(String x:s){
System.out.println(x);
}
}
public static void AsHeap(String s[]){
for( int i = s.length / 2; i >= 0; i-- ){
DownHeap( s, i, s.length );
}
}
public static void HeapSort(String[] s){
for(int i=s.length-1;i>0;i--){
swap(s,0,i);
DownHeap(s,0,i);
}
}
public static int getLeftChildIndex(int i){
return 2 * i + 1;
}
private static void DownHeap(String[] s, int i, int length) {
int indexOfChild;
String temp;
for(temp=s[i];getLeftChildIndex(i)<length;i=indexOfChild){
indexOfChild=getLeftChildIndex(i);
if(indexOfChild !=length-1 && s[indexOfChild].compareTo(s[indexOfChild+1])<0){
indexOfChild++;
}
if(temp.compareTo(s[indexOfChild])<0){
s[i] = s[indexOfChild];
} else{
break;
}
}
s[i] = temp;
}
public static void swap(String s[],int x,int y){
String temp=s[x];
s[x]=s[y];
s[y]=temp;
}
}
The while loop isn't terminating when there is no swap between the parent and the child(i.e. the parent is greater than the child).
The value of i(just above main method) doesn't change when parent is greater. Simply taking the line i=max outside the if block [if(heap[i]
Also,is there any sequence to learn Algorithms?If so,kindly guide me.
Thank you.
Here I am working on the following problem where we are given n types of coin denominations of values v(1) > v(2) > ... > v(n) (all integers) The following code tries to find the minimum number of coins that are required to make a sum-C. Here the C is 100(see main function).When I run the code, error--"java.lang.StackOverflowError" comes. Please help.
import java.util.ArrayList;
public class Problem2 {
public static int count=4;
public static int []v={25,10,5,1}; //Array storing denominations
private static int findminimum(ArrayList<Integer> v2) {
int count=v2.get(0);
for(int i=0;i<v2.size();i++)
{
if(count>v2.get(i))
{
count=v2.get(i);
}
}
return count;
}
public static int countmincoins(int n)
{
int t;
if(n<0)
{
t=Integer.MAX_VALUE-100 ;
}
if(n==0)
{
t= 0;
}
else
{
ArrayList<Integer> a=new ArrayList<Integer>();
for(int i=0;i<v.length;i++)
{
int temp=0;
temp=countmincoins(n-v[i])+1; //Stackoverflow error
a.add(temp);
}
t=findminimum(a);
}
return t;
}
public static void main(String args[])
{
System.out.println(countmincoins(100));
}
}
If you use recursion then you need to reach a condition to terminate the recursion. But in your code I do not seen any termination logic. Thats why, it get to infinite loop and StackOverflowException. In your code you use following code to terminate.
if(n==0)
{
t= 0;
}
But here n may not be zero. Becuase countmincoins(n-v[i]) do not ensure you to n will be 0.
Your code is infinite cause t will never be <0 or ==0 given that the values in the array and the condition (n - v[i] )+1, v[i] will always return the same value in every call to the method, therefore infinite recursion.
If your not restricted to using recursion the following would be much simpler:
public static int[] denominations = {25,10,5,1};
public static int minimumCoins(int amount){
int total = 0;
for(int denomination: denominations){
while(amount - denomination >= 0){
amount -= denomination;
total++;
}
}
return total;
}
public static void main(String args[])
{
System.out.println(minimumCoins(98));
}
I have written the code but it displays Stackoverflowerror message.
class Sum
{
int ans=0,temp,temp2;
int getsum(int no)
{
if(no>0)
{
temp=no % 10;
ans=ans + temp;
getsum(no/10);
}
else
{
return ans;
}
}
}
class recsum
{
public static void main(String args[])
{
Sum s=new Sum();
int no,len;
len=args.length;
if(len==0)
{
System.out.println("No argruments are given ! ");
}
else
{
no=Integer.valueOf(args[0]).intValue();
System.out.println("Sum of digits= " + s.getsum(no));
}
}
}
You are over-complicating things a lot in your code. Here is a simpler working example:
public static int getSum(final String[] args, final int index) {
if (index < args.length) {
return Integer.valueOf(args[index]) + getSum(args, index + 1);
} else {
return 0;
}
}
public static void main(String[] args) {
if (args.length == 0) {
System.out.println("You need to provide numbers as arguments.");
}
final int sum = getSum(args, 0);
System.out.println("Sum: " + sum);
}
You are supposed to be recursive, this is in the getSum function, because it is calling itself with differing parameters.
In recursive functions, you always need to have an exit branch that causes the calling to stop.
As sums won't change if you add 0 this can be exploited for a very clean exit.
The Stack overflow is normally because you never bottom out of the recursion.
Change class Sum to this:
class Sum {
int ans = 0, temp = 0;
int getsum(int no) {
if((no/10)-.5 >= 1)
ans += getsum(no/10);
else
return ans;
}
}
I'm not completely sure if this will work, and I can't compile it right now. I think this is one way to do it, but again, I'm not completely sure.
Program: Write a program to use Command Line Arguments.
class Sumnum1
{
int i,t,num,sum=0;
void getData(String s)
{
num=Integer.parseInt(s);
}
int digitSum()
{
for(i=num;i>=1;i=i/10)
{
t=i%10;
sum=sum+t;
}
return sum;
}
public static void main(String arg[])
{
int ds=0;
Sumnum1 obj=new Sumnum1();
obj.getData(arg[0]);
ds=obj.digitSum();
System.out.println("sum of digit="+ds);
}
}
BY :ANKIT AGRAWAL (A.A.)