How can I make this code a recursive method?
for (int i = 3; i < arr.length; i++) {
writer.write(arr[i] + "\n");
strout += arr[i] + "\n";
}
You can try encapsulating the code in a function:
public static String printRecursive(BufferedWriter writer, String[] arr, int i) throws IOException {
String strout = "";
if(i<arr.length) {
writer.write(arr[i] + "\n");
//System.out.println(arr[i] + "\n");
strout += arr[i] + "\n" + printRecursive(writer,arr,i+1);
}
return strout;
}
And you can call it from main:
String strRec = printRecursive(writer,arr,3);
I hope this help you.
Edited: Added writer according last comment
Something like that?
let arr = [/* array elements */];
let idx = 3;
let stdout = "";
const recursiveMethod = () => {
writer.write(`${arr[idx]}\n`);
strout += `${arr[idx]}\n`;
if(idx < arr.length) {
idx++;
return recursiveMethod();
}
}
recursiveMethod();
Related
So I'm currently working on a personal project and I made a program that tries to swap every 2 letter in a given string.
So I want the output like this:
(Note Input String is "abllte")
ballet
So I wrote this method
public static String codeString(String input) {
String firstLetter = "";
String secoundLetter = "";
String result = "";
for(int i = 0; i < input.length()-1; i++){
for(int c = 0; c < i; c = c +2)
{
firstLetter = input.substring(c,c + 1);
secoundLetter = input.substring(c + 1, c + 2);
}
result = result + secoundLetter + firstLetter;
}
return result;
}
But I get this output:
ababllll
Any idea how to solve this?
Thank you in advance!
You only need one loop. This works for both even and odd length character strings.
first, the methods used return the StringBuilder in its current modified state.
So sb.insert(i, sb.charAt(i+1)) inserts the char at i+1 at i
So if sb contained ab, StringBuilder would now contain bab
insert returns the modifed StringBuilder so now sb.deleteCharAt(i+2) deletes the second a (the one that was just copied).
this is then repeated until all characters are swapped.
Because of the constant inserting and deletion of characters this is not very efficient.
for (String s : new String[] { "abcdefg", "abcdefgh" }) {
StringBuilder sb = new StringBuilder(s);
for (int i = 0; i < sb.length() - 1; i += 2) {
sb.insert(i, sb.charAt(i + 1)).deleteCharAt(i + 2);
}
System.out.println(s + " -> " + sb);
}
Prints
abcdefg -> badcfeg
abcdefgh -> badcfehg
For a more efficient algorithm, this would be the way to go. It's also much more intuitive.
for (String s : new String[] { "abcdefg", "abcdefgh" }) {
char ch[] = s.toCharArray();
for (int i = 0; i < ch.length - 1; i+=2) {
char c = ch[i];
ch[i] = ch[i + 1];
ch[i + 1] = c;
}
String d = String.valueOf(ch);
System.out.println(s + " -> " + d);
}
This prints the same as above.
I'm not sure what the point of your nested for loop is. You can do this with just one loop.
public static String codeString(String input) {
String firstLetter = "";
String secoundLetter = "";
String result = "";
for(int i = 0; i < input.length()-1; i+=2){
firstLetter = input.substring(i,i+1);
secoundLetter = input.substring(i+1,i+2);
result = result + secoundLetter + firstLetter;
}
return result;
}
If your input string has an odd number of characters, you'll have to append the extra last character.
public static String codeString(String input) {
String firstLetter = "";
String secoundLetter = "";
String result = "";
for(int i = 0; i < input.length()-1; i+=2){
firstLetter = input.substring(i, i+1);
secoundLetter = input.substring(i+1, i+2);
result = result + secoundLetter + firstLetter;
}
if(input.length() % 2 == 1)
result += input.substring(input.length()-1, input.length());
return result;
}
You do not need a nested loop. Change the outer loop to step by 2 i.e. i = i + 2 and remove the inner loop.
public class Main {
public static void main(String[] args) {
System.out.println(codeString("abllte"));
}
public static String codeString(String input) {
String firstLetter = "";
String secondLetter = "";
String result = "";
for (int i = 0; i < input.length() - 1; i = i + 2) {
firstLetter = input.substring(i, i + 1);
secondLetter = input.substring(i + 1, i + 2);
result = result + secondLetter + firstLetter;
}
return result;
}
}
Output:
ballet
An alternative approach:
You can create a function with two parameters: input string as the first parameter and n as the second parameter, where every n characters in the input string need to be reversed.
public class Main {
public static void main(String[] args) {
System.out.println(codeString("abllte", 1));
System.out.println(codeString("abllte", 2));
System.out.println(codeString("abllte", 3));
System.out.println(codeString("abllte", 4));
}
public static String codeString(String input, int n) {
if (n <= input.length() / 2) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < input.length() - n + 1; i = i + n) {
result.append(new StringBuilder(input.substring(i, i + n)).reverse());
}
return result.toString();
} else {
return input;
}
}
}
Output:
abllte
ballet
lbaetl
abllte
When I run this, I can see exact result "false" but I also want to see what difference there is. For instance
"ozer and gunthy" match but "albundy and aldy" does not
package start;
public class Start {
public static void main(String[] args) {
String[] a = {"ozer + gunthy + albundy"};
String[] b = {"ozer + günthy + aldy"};
boolean b1 = false;
if (a.length != b.length){
b1 = false;
}else {
for (int i = 0; i < a.length; i++){
if (a[i] == b[i]){
b1 = true;
}else {
b1 = false;
break;
}
}
}
System.out.println(b1);
}
}
You will want to replace
a[i] == b[i]
with
a[i].equals(b[i])
You will also need to fix your arrays
public static String[] list1 = {"ozer", "gunthy","albundy"};
public static String[] list2 = {"ozer", "günthy","aldy"};
then, you will need to write and call a method to properly analyze the arrays to your specification:
public String methodName(String[] list1, String[] list2)
{
String output = "";
if (list1.length != list2.length)
{
return "The Arrays differ in length";
}
else
{
for (int i = 0; i < list1.length; i++)
{
if (list1[i].equals(list2[i]))
{
output += "" + list1[i] + " is equal to " + list2[i] + "\n";
}
else
{
output += "" + list1[i] + " is not equal to " + list2[i] + "\n";
}
}
}
return output;
}
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) ;
}
Before I get into the issue, let me describe the problem that the code is supposed to be solving.
The code is supposed to take in input from a file in the following syntax:
1,2,3,4;5
The code is supposed to take the integer that is after the semicolon and assign it to a variable, which it does. Then the code is supposed to take the values that are before the semicolon and find and return all two pairs of integers that add up to the value after the semicolon.
Example: if the input is
1,2,3,4;5
then the output should be
1,4;3,2
The problem I have is that my String result is not being edited by the nested for loops within the code. I get no compile time or runtime errors. It just does not edit the String result and I can't figure out why. Could you guys take a look?
import java.util.*;
import java.io.*;
public class NumberPairs2 {
public static void main (String[] args) throws IOException {
File file = new File("C:/Users/James/Desktop/txt.txt"); // Takes in a file as input
BufferedReader buffer = new BufferedReader(new FileReader(file));
String line;
while ((line = buffer.readLine()) != null) {
String result = ""; // creates an empty string
line = line.trim(); // set the file contents equal to null
if (line.length() != 0){
int sumTest = Integer.parseInt(line.substring(line.indexOf(";") + 1));
String[] intArray = line.split(";");
String[] intArray2 = intArray[0].split(",");
for (int i = 0; i < intArray2.length - 1; i++){
for(int j = i + 1; i < intArray2.length; i++){
if (intArray2[i] != "," && intArray2[j] != "," && Integer.parseInt(intArray2[i]) + Integer.parseInt(intArray2[j]) == sumTest){
result += intArray[i] + ", " + intArray[j] + ";";
System.out.println(result);
}
}
}
//int compare = ()
}
else {
result = null;
System.out.println(result);
}
}
}
}
This may help
for (int i = 0; i < intArray2.length - 1; i++){
for(int j = i + 1; j < intArray2.length; j++){
if (Integer.parseInt(intArray2[i]) + Integer.parseInt(intArray2[j]) == sumTest){
result += intArray2[i] + ", " + intArray2[j] + ";";
}
}
}
System.out.println(result);
You need to use intArray2[i] & intArray2[j] when adding to result instead of intArray[i] & intArray[j]. Your code is currently getting an ArrayIndexOutOfBoundsException while trying to use intArray2 indices in intArray.
for (int i = 0; i < intArray2.length - 1; i++){
for(int j = i + 1; j < intArray2.length; j++){
if (Integer.parseInt(intArray2[i]) + Integer.parseInt(intArray2[j]) == sumTest){
result += intArray2[i] + ", " + intArray2[j] + ";";
System.out.println(result);
}
}
}
one option to remove the last semicolon would be to append to result as follows
//if not 1st pair, add semicolon
if(!result.equals("")){
result += "; ";
}
result += intArray2[i] + ", " + intArray2[j];
If I change the text to two words the program wont output anything. Not a clue on how to fix this, thanks in advance.
public class test {
public static void main(String args[]) {
String text = "The cat sat on the mat!"; //Change the string to "Hello there!"
int wordLengthCount [] = new int [20];
String wordCountText = "";
String sentence[] = text.split("[,\\-:\\?\\!\\ ]");
for (int i = 0; i < sentence.length; i++)
{
wordLengthCount[sentence[i].length()]++;
}
for(int wordLength=0; wordLength<sentence.length; wordLength++)
{
if (wordLengthCount[wordLength] != 0){
wordCountText += wordLengthCount[wordLength] + " with length of " + wordLength + "\n";
}
}
System.out.println(wordCountText);
}
}
You need to iterate over all wordLengthCount
Quick fix:
for (int wordLength = 0; wordLength < wordLengthCount.length; wordLength++) {
if (wordLengthCount[wordLength] != 0) {
wordCountText += wordLengthCount[wordLength] + " with length of " + wordLength + "\n";
}
}
Live demo