Java Triangle Recursion - java

I am having trouble printing out triangles recursively involving spaces and asterisks. Apparently stringbuffer or stringbuilder may be necessary to calculate the correct number of spaces and asterisks, but I am having a bit of difficulty. The 2 triangles should look like:
****
***
**
*
and
*
**
***
****
public static String printTriangle(int num)
{
if (num == 0) {
return "";
}
String dots = "";
for (int i = 0; i < num; i++) {
dots = dots + "*";
}
System.out.println(dots);
return printTriangle(num-1) + dots;
}
public static String printTriangle2(int num) {
if (num == 0) {
return "";
}
String dots = printTriangle2(num-1);
dots = dots + ".";
String spaces = "";
for (int i = 0; i < num; i++) {
spaces = spaces + " ";
}
String line = spaces + dots;
System.out.println(line);
return line;
}
This is what I have so far. Any help would be appreciated.
This is the output currently:
****
***
**
*
.
..
...
....

Here's a fairly simple implementation:
static void printTriangle(int n, int len)
{
if(n == len) return;
printRow(n, len);
printTriangle(n+1, len);
printRow(n, len);
}
static void printRow(int n, int len)
{
for(int i=0; i<n; i++) System.out.print(" ");
for(int i=n; i<len; i++) System.out.print("*");
System.out.println();
}
Test:
printTriangle(0, 4);
Output:
****
***
**
*
*
**
***
****
Although I like this:
static void printTriangle(String s)
{
if(!s.contains("*")) return;
System.out.println(s);
printTriangle(" " + s.replaceFirst("\\*", ""));
System.out.println(s);
}
Called with
printTriangle("****");

try the follwing code and call with step=0
printTriangle(4,0)
printTriangle2(4,0)
public static String printTriangle(int num, int step)
{
if (num == 0) {
return "";
}
String ast = "";
for (int i = 0; i < num; i++) {
ast = ast + "*";
}
String sps = "";
for (int i = 0; i < step; i++) {
sps = sps + " ";
}
System.out.println(sps+ast);
return printTriangle(num-1, step+1) ;
}
public static String printTriangle2(int num, int step)
{
if (num == 0) {
return "";
}
String ast = "";
for (int i = 0; i <= step; i++) {
ast = ast + "*";
}
String sps = "";
for (int i = 0; i < num; i++) {
sps = sps + " ";
}
System.out.println(sps+ast);
return printTriangle2(num-1, step+1) ;
}

Related

Limiting # of characters per line

I'm a beginner and I'm having trouble trying to display the output so that if its too big it will move it to the next line.
This is what I have so far:
import java.util.Scanner;
public class numberBracket {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("howMany: ");
int howMany = scanner.nextInt();
System.out.println("lineLength: ");
int lineLength = scanner.nextInt();
scanner.nextLine();
printNumbers(howMany, lineLength);
}
public static void printNumbers(int howMany, int lineLength) {
Integer charLength = Integer.valueOf(lineLength);
for(int i = 1; i <= howMany; i ++) {
String t = "[" + i + "]";
while(t.length() > charLength ) {
int index = t.lastIndexOf(' ', charLength);
System.out.print(t.substring(0, index));
t = t.substring(index + 1);
}
System.out.print(t);
}
}
}
So if they enter 10 for the lineLength it would be
[1][2][3]
[4]
and if they entered 12 it would be
[1][2][3][4]
You can use this snippet:
public static void printNumbers(int howMany, int lineLength) {
StringBuilder sb = new StringBuilder();
int length = 0;
for (int i = 1; i <= howMany; i++) {
String t = "[" + i + "]";
if (length + t.length() > lineLength) {
sb.append("\n");
length = 0;
}
length += t.length();
sb.append(t);
}
System.out.println(sb.toString());
}
public static void printNumbers(int howMany, int lineLength) {
String printed = "";
for (int i = 1; i <= howMany; i++) {
String t = "[" + i + "]";
if ((printed.length() + t.length()) > lineLength) {
printed = "";
System.out.println();
}
printed += t;
System.out.print(t);
}
}
I believe you have to check if it has room in the current line before printing.
If it does have room print it, if it doesn't, print in a new line.
public static void printNumbers(int howMany, int lineLength) {
int alreadyPrintedLength = 0;
for(int i = 1; i <= howMany; i ++) {
String t = "[" + i + "]";
int actualCharLength = t.length();
boolean hasRoomInCurrentLine = (alreadyPrintedLength + actualCharLength) <= lineLength;
if (hasRoomInCurrentLine) {
System.out.print(t);
alreadyPrintedLength += actualCharLength;
} else {
System.out.print(System.lineSeparator() + t);
alreadyPrintedLength = actualCharLength;
}
}
}

Extract the particular portion from a String

I have the below String variable
String s = "abc,xyz,lmn,ijk";
I want to extract only the portion of the String (i.e - 'lmn')
And, Should not use in-built functions like, SubString(), Split(), IndexOf(). But I can use charArray()
And this question was asked in my interview.
I tried the below code,
But not sure how to proceed. Can any one please provide your thoughts?
String s = "abc,xyz,lmn,ijk";
int counter = 0;
char[] ch = s.toCharArray();
for (int i = 0; i < ch.length; i++) {
if (ch[i] == ',') {
counter++;
}
}
Here's one way:
public static void main(String[] args) {
String s = "abc,xyz,lmn,ijk";
char[] ch = s.toCharArray();
int counter = 0;
int place = 2;
for (int i = 0; i < ch.length-2; i++) {
if(ch[i] == ',') {
counter++;
}
if(counter == place && ch[i] != ',') {
System.out.print(ch[i]);
}
}
}
It prints everything after the second comma, but before the third one.
public static void main(String[] args) {
// TODO Auto-generated method stub
String s = "abc,xyz,lmn,ijk";
StringBuffer sb=new StringBuffer();
char[] ch = s.toCharArray();
for (int i = 0; i < ch.length; i++) {
if(','==(ch[i]))
{
if (sb.toString().equals("lmn")) {
System.out.println(sb.toString());
}
else
{
int length=sb.length();
sb.delete(0, length);
}
}
else
{
sb.append(ch[i]);
}
}
}
I would do it this way.
String s = "abc,xyz,lmn,ijk";
String x = "c,x"; // String to found
String r = "";
boolean coincidence = false;
int a=0; // Initial index if of the first character in x is found
int b=0; // Last index If it was possible to search for the last character of x
int c=0; // Index "iterator" on String x
char[] ch = s.toCharArray();
for (int i = 0; i < ch.length; i++) {
if(c == x.length())
break;
else{
if(ch[i] == x.charAt(c) && !coincidence){
a = i; b = i; c++;
coincidence = true;
}
else if(ch[i] == x.charAt(c) && coincidence){
b++; c++;
}else{
coincidence = false;
a = 0; b = 0; c = 0;
}
}
}
System.out.println("String: " + s);
System.out.println("String to find: " + x);
System.out.println("Was found? " + ((coincidence)? "Yes" : "No"));
if(coincidence){
System.out.println("Intervals indexes in String: ["+a + "," + b +"]");
// String extration
for (int i = a; i <= b; i++)
r += s.charAt(i);
System.out.println("String extracted: " + r);
}

Using java, input string="aabbcdeaaaabbb" and the output must be aaaa

Using java, input string="aabbcdeaaaabbb" and the output must be aaaa, as sequence here is having repeated 4 times a. Can anyone help me to get this "aaaa" as output using java implementation.
Algorithm to find the Longest substring having same character repeated.
for eg:
I/P: aabbcdefaaaacccccc O/P: cccccc
Please check my program below and suggest any optimization for faster processing:
public class LongestSubString {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(
System.in));
System.out
.println("Enter a word to find longest substring with same characters repeated");
String word = reader.readLine();
System.out.println("Entered word is: " + word);
System.out.println("Longest repeated characters substring is: "
+ subStringFinder(word));
}
/*
*longest substring finder with same character repeated
*/
public static String subStringFinder(String word) {
char[] tokens = word.toCharArray();
int len = tokens.length;
int wordLen = word.length();
System.out.println("len of input word: " + wordLen);
List<String> myList = new ArrayList<>();
StringBuilder strConcat = new StringBuilder("");
for (int j = 0; j <= len - 1; j++) {
if (j + 1 > len - 1) {
if ((strConcat.length() >= 1)
&& (strConcat.charAt(strConcat.length() - 1) == (tokens[j]))) {
strConcat.append("" + tokens[j]);
myList.add(strConcat.toString());
}
}
else {
if (tokens[j] == tokens[j + 1]) {
if ((strConcat.length() >= 1)
&& (strConcat.charAt(strConcat.length() - 1) == (tokens[j]))) {
strConcat.append("" + tokens[j]);
myList.add(strConcat.toString());
} else {
strConcat = new StringBuilder("");
strConcat.append("" + tokens[j]);
}
} else {
if ((strConcat.length() >= 1)
&& (strConcat.charAt(strConcat.length() - 1) == (tokens[j]))) {
strConcat.append("" + tokens[j]);
myList.add(strConcat.toString());
} else {
strConcat = new StringBuilder("");
strConcat.append("" + tokens[j]);
}
}
}
}
int max = 0, index = 0;
for (int i = 0; i < myList.size(); i++) {
String strEle = myList.get(i);
int strLen = strEle.length();
if (max < strLen) {
max = strLen;
index = i;
}
}
return myList.get(index);
}
}
I believe your code is overly complicated. You don’t need a StringBuilder nor an ArrayList. I tried to understand your intention, but then skipped it and wrote my own version instead. Hope it helps anyway.
public static String subStringFinder(String word) {
if (word == null || word.isEmpty()) {
return word;
}
char currentChar = word.charAt(0);
int longestStart = 0;
int longestLength = 0;
int currentStart = 0;
int currentLength = 1;
for (int ix = 1; ix < word.length(); ix++) {
if (word.charAt(ix) == currentChar) {
currentLength++;
} else {
if (currentLength > longestLength) {
longestStart = currentStart;
longestLength = currentLength;
}
currentChar = word.charAt(ix);
currentStart = ix;
currentLength = 1;
}
}
if (currentLength > longestLength) {
longestStart = currentStart;
longestLength = currentLength;
}
return word.substring(longestStart, longestStart + longestLength);
}
String in = "aabbcdeaaaabbb";
String t;
ArrayList<String> out = new ArrayList<String>();
String l="";
int c=0;
String n;
for(int i=0;i<in.length;i++) {
n=in.substring(i, i+1); //get the current character
if(n.equals(l)){
l=n; c++;
}
else {
t=n;
for(int j=1;j<c;j++) {
n+=t;
}
c=0;
out.add(n);
c=0;
}
}

program to make a star pattern with a single for loop

I made the following program
public class StarPattern5 {
public static void main(String args[])
{
int j=1;
for(int i=1;i<=15;i++)
{
System.out.print("*");
if(i==1 || i==3 || i==6 || i==10)
{
System.out.println();
}
}
}
}
it's printing
*
**
***
****
*****
I want to optimize it so that we can print 50 lines without writing too much code.Thanx in advance..:)
Just accumulate a string in the loop:
String s = "";
for (int i = 0; i < 50; ++i) {
System.out.println(s += "*");
}
or:
for (String s = "*"; s.length() <= 50; s += "*") {
System.out.println(s);
}
You can use the StringUtils class from the Apache common lang package like this:
public class StarPattern5 {
public static void main(String args[]){
for(int i =1;i<=50;i++)
System.out.println(StringUtils.repeat('*',i));
}
}
This will preserve you from writing too much code but it uses a 3rd party library, it depends of what you exactly want/need.
Here's a single loop variation that resets i to 0 if it reaches a variable called count.
public class star {
public static void main(String...banana)
{
for (int i = 0, count = 1; i < 50; i++)
{
if (i == count)
{
count++;
i = 0;
System.out.println("");
}
System.out.print("*");
}
}
}
You can print such triangle using recursion with the same time complexity of 1 for loop as following:
public String printTriangle (int count) {
if( count <= 0 ) return "";
String p = printTriangle(count - 1);
p = p + "*";
System.out.println(p);
return p;
if you want to print triangle of 50 lines then pass the argument count = 50.
static void Main(string[] args)
{
Console.Write("Enter a Number : ");
int num;
num = Convert.ToInt32(Console.ReadLine());
string design = null;
////////Forpatern
/// *****
/// ****
/// ***
/// **
/// *
////----start----------
for (int i = num; i >= 0; i--)
{
if (num != 1)
{
if (i == 0)
{
num = num - 1;
//Console.WriteLine();
design = design + System.Environment.NewLine + ("*");
i = num;
}
else
{
design = design + ("*");
}
}
}
//-----End
int spaceCounter = 0;
int Rows = num;
////////For patern
/// *****
/// ****
/// ***
/// **
/// *
////----start----------
for (int i=num;i>=0;i--)
{
if(spaceCounter==0)
{
if (i != 0)
{
design = design + "*";
}
else {
num = num - 1;
i = Rows + 1;
spaceCounter = Rows - num;
design = design + System.Environment.NewLine;
}
}
else if(spaceCounter>0){
design = design + " ";
spaceCounter = spaceCounter - 1;
}
}
///---------End
Console.WriteLine(design);
Console.ReadLine();
}
It's so easy. Like this, you can make it by yourself
public class StarPattern5 {
public static void main(String args[])
{
StringBuilder sb = new StingBuilder("");
for(int i =1;i<=50;i++){
sb.append("*");
System.out.println(sb.toString());
}
}
#CPP Program for Print the dynamic pyramid pattern by using one loop in one line.
https://www.linkedin.com/posts/akashdarji8320_cpp-cplusplus-c-activity-6683972516999950336-ttlP
#include <iostream>
using namespace std;
int main() {
int rows;
cout<<"Enter number of rows :: ";
cin>>rows;
for( int i = 1, j = rows, k = rows; i <= rows*rows; i++ )
if( i >= j && cout<<"*" && i % k == 0 && (j += rows-1) && cout<<endl || cout<<" " );
}

how can i calculate the number of specific chars in a string?

Given a string how can i figure out the number of times each char in a string repeats itself
ex: aaaabbaaDD
output: 4a2b2a2D
public static void Calc() {
Input();
int count = 1;
String compressed = "";
for (int i = 0; i < input.length(); i++) {
if (lastChar == input.charAt(i)) {
count++;
compressed += Integer.toString(count) + input.charAt(i);
}
else {
lastChar = input.charAt(i);
count = 1;
}
}
System.out.println(compressed);
}
What you'r looking for is "Run-length encoding". Here is the working code to do that;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RunLengthEncoding {
public static String encode(String source) {
StringBuffer dest = new StringBuffer();
// iterate through input string
// Iterate the string N no.of.times where N is size of the string to find run length for each character
for (int i = 0; i < source.length(); i++) {
// By default run Length for all character is one
int runLength = 1;
// Loop condition will break when it finds next character is different from previous character.
while (i+1 < source.length() && source.charAt(i) == source.charAt(i+1)) {
runLength++;
i++;
}
dest.append(runLength);
dest.append(source.charAt(i));
}
return dest.toString();
}
public static String decode(String source) {
StringBuffer dest = new StringBuffer();
Pattern pattern = Pattern.compile("[0-9]+|[a-zA-Z]");
Matcher matcher = pattern.matcher(source);
while (matcher.find()) {
int number = Integer.parseInt(matcher.group());
matcher.find();
while (number-- != 0) {
dest.append(matcher.group());
}
}
return dest.toString();
}
public static void main(String[] args) {
String example = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW";
System.out.println(encode(example));
System.out.println(decode("1W1B1W1B1W1B1W1B1W1B1W1B1W1B"));
}
}
This program first finds the unique characters or numbers in a string. It will then check the frequency of occurance.
This program considers capital and small case as different characters. You can modify it if required by using ignorecase method.
import java.io.*;
public class RunLength {
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public static void main(String[] args) throws IOException {
System.out.println("Please enter the string");
String str = br.readLine();//the input string is in str
calculateFrequency(str);
}
private static void calculateFrequency(String str) {
int length = str.length();
String characters[] = new String[length];//to store all unique characters in string
int frequency[] = new int[length];//to store the frequency of the characters
for (int i = 0; i < length; i++) {
characters[i] = null;
frequency[i] = 0;
}
//To get unique characters
char temp;
String temporary;
int uniqueCount = 0;
for (int i = 0; i < length; i++) {
int flag = 0;
temp = str.charAt(i);
temporary = "" + temp;
for (int j = 0; j < length; j++) {
if (characters[j] != null && characters[j].equals(temporary)) {
flag = 1;
break;
}
}
if (flag == 0) {
characters[uniqueCount] = temporary;
uniqueCount++;
}
}
// To get the frequency of the characters
for(int i=0;i<length;i++){
temp=str.charAt(i);
temporary = ""+temp;
for(int j=0;i<characters.length;j++){
if(characters[j].equals(temporary)){
frequency[j]++;
break;
}
}
}
// To display the output
for (int i = 0; i < length; i++) {
if (characters[i] != null) {
System.out.println(characters[i]+" "+frequency[i]);
}
}
}}
Some hints: In your code sample you also need to reset count to 0 when the run ends (when you update lastChar). And you need to output the final run (after the loop is done). And you need some kind of else or continue between the two cases.
#Balarmurugan k's solution is better - but just by improving upon your code I came up with this -
String input = "aaaabbaaDD";
int count = 0;
char lastChar = 0;
int inputSize = input.length();
String output = "";
for (int i = 0; i < inputSize; i++) {
if (i == 0) {
lastChar = input.charAt(i);
count++;
} else {
if (lastChar == input.charAt(i)) {
count++;
} else {
output = output + count + "" + lastChar;
count = 1;
lastChar = input.charAt(i);
}
}
}
output = output + count + "" + lastChar;
System.out.println(output);

Categories