Using recursion to create a one line number pattern
Write a recursive method that prints out a numeric sequence. printSequence(4) prints 1 2 3 4 3 2 1
public class Practice {
public static void main(String[] args){
printSequence(4);
}
public static void printSequence(int n){
System.out.print(n);
if(n>1){
printSequence(n1);
}
System.out.print(n);
}
}
My code is there, and the output is pretty obvious, but it's 43211234. My desired output is 1234321, and I'm not sure how to get there. Unless I can use two methods, but only call one in main, I don't think I can use two methods.
Does anyone know how I can get my desired output: 1 2 3 4 3 2 1
recursively, and only using one method?
See also questions close to this topic

Java: final string comparison does not work
I have created final strings for certain commands but when I try to check if the command given by the user matches, it does not work.
These are examples of my final strings:
public static final String END = "quit"; public static final String SHOW = "print";
But if I were to use it e.g. like this:
String command = scanner.nextLine(); if (command == SHOW) { System.out.println("Print this line."); }
It sees that they do not match even if they do. I tried printing the finalized variables:
System.out.println(END);
and it prints its value, but for some reason when I compare them to identical strings provided by the user, it does not recognize them.
I have tried to search similar examples and read about finalizing variables, but I think I am missing something important. I know that the problem is with the final variables and not elsewhere, because the program works if I compare these same strings with equal. E.g:
String command = scanner.nextLine(); if (command.equals("print") { System.out.println("Print this line."); }
I am assuming that there is something very simple that I am doing wrong, but I could not find any answer anywhere that I would understand. I am still a beginner and all the other examples regarding similar questions include some features that I don't understand, so they don't help me to see what I am doing wrong.

Stack class in java.util a violation of Liskov substitution principle?
From the documentation of https://docs.oracle.com/javase/7/docs/api/java/util/Stack.html
public class Stack<E> extends Vector<E>
Isn't this a violation of the Liskov substitution principle? The LSP in simple terms states that objects of the same superclass should be able to be swapped with each other without breaking anything.
For example: Let us say that I have a function that takes a Vector as an input. If while calling a function I start passing it a Stack then it might break because Stack prevents random access of elements.
import java.util.*; class Book {} class TextBook extends Book {} public class Sample { public static void process(Vector<Book> books) { # This should not be allowed for Stack, Stack is FILO System.out.println(books.get(1)); } public static void main(String[] args) { Vector<Book> books = new Vector<>(); books.add(new Book()); books.add(new Book()); books.add(new Book()); process(books); System.out.println("ok"); Stack<Book> bookz = new Stack(); bookz.add(new Book()); bookz.add(new Book()); bookz.add(new Book()); process(bookz); System.out.println("ok"); } }

Can i combine unicode categories in Regex?
I want to get such set of symbols:
\P{L}
unicode category use as base add
хХxXтТTоОoO0
symbols to\P{L}
unicode category  do not use symbols
_.
By that i get such regex in Java:
[[\P{L}]&&[^_.]&&[хХxXтТTоОoO0]]
But this not working, what's wrong?

Time Limit Exceeded  Recondtructing Binary Tree
Trying to practice using inorder and postorder arrays to reconstruct a binary tree. My code works with small inputs and some different edge cases but when I have a super large postorder and inorder array, it times out and not sure why. Any way that I can refactor this to make it faster? I'm thinking using a dictionary to store the indices, but not sure where I should place the mapped array indices in this code.
def buildTree(inorder, postorder): # base case: if inorder == null: return null (L and R trees do not exist) # Determine root from postorder # Determine L and R subtrees from inorder # create node from root # assign node.left to left tree and node.right to right tree # return root if not inorder: return None else: rootVal = postorder[1] rootNode = TreeNode(rootVal) for i in range(len(inorder)): if inorder[i] == rootVal: rootIndex = i break # default if no L or no R subtree rightInST, leftInST = [], [] if rootIndex + 1 < len(inorder): # right tree found rightInST = inorder[rootIndex + 1:] if rootIndex > 0: # left tree found leftInST = inorder[:rootIndex] rightPostST = [x for x in postorder if x in rightInST] leftPostST = [x for x in postorder if x in leftInST] rootNode.right = buildTree(rightInST, rightPostST) rootNode.left = buildTree(leftInST, leftPostST) return rootNode

Get all combinations for arbitrary number of elements
How can I make a method in Java which obtains input integer
n
, and an array of doublex
, and returns all combinations of n elements out of values in x.Where
x={1,2,3}
and n=2,the expected returns/combinations are
{1,1},{1,2},{1,3},{2,2},{2,1},{2,3},{3,1},{3,2},{3,3}
(the order is not ignored.) The number should be(int) Math.pow(x.length, n)
e.g.
static List<Double[]> getAll(int n, double[] x){ List<Double[]> combinations = new ArrayList<>(); //number of combinations should be x.length ^ n // when n = 1; for (int i=0;i<x.length;i++) combinations.add({x[i]}); return combinations; } // return patterns[i] is the i th pattern //which contains numelements from the input depths, // patterns[i][j] is the j th double in patterns[i] private double[][] void makePatterns(int num, double[] depths) { int patternN = (int) Math.pow(depths.length, num); double[][] patterns = new double[patternN][num]; System.out.println(patterns.length); int i = 0; int k = 0; while (i < patternN) { for (int j = 0; j < num; j++) { // System.out.println(i+" "+j+" "+(i / (int)Math.pow(depths.length, j))%depths.length); patterns[i][j] = x[(i / (int)Math.pow(depths.length, j))%depths.length]; } i++; } return patterns; }
This
makePatterns
is where I started... 
How to translate this from template?
def build_repr(operations, templates): """ Build the representation of the series of operations with the given templates. The operations are prioritized from right to left. Restrictions: You should use recursion. You should do input validation. Parameters: operations (list(str)): List of numbers and operations to be executed on them Returns: (str): String representation of the operations >>> build_repr([0, '+', 1, '', 3], {'+': '({0}, +, {1})', '':\ '({0}, , {1})'}) '(0, +, (1, , 3))' >>> build_repr([0, '+', 1, '', 3], \ {'+': '({0}, add, {1})', '':'({0}, minus, {1})'}) '(0, add, (1, minus, 3))' >>> build_repr([0, '+', 1, '', 3], \ {'+': '({0}, add, {1})', '': '({0}, minus, {1})'}) '(0, add, (1, minus, 3))' """