How to get random words of a give length (L) from a dictionary which has been implemented using a trie? - data-structures

How to retrieve a random word of a given length from a Trie
The answer above explains how to select the first character but I am confused how we will proceed after that. I want words of Length L but when I start traversing the tree, I wouldn't know if the branch that is being traversed has depth L.
Dictionary
package com.FastDictionary;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import sun.rmi.runtime.Log;
/**
* Dictionary implementation.
* Uses Trie Data Structure
* Creates a singleton object
*/
public class FastDictionary {
private int nineWordCount;
private int totalWordCount;
// Root Node
private DictionaryNode root;
// Singleton object
private static FastDictionary fastDictionary;
// Flag; True if words.txt has been processed once
private boolean isProcessed;
private FastDictionary() {
this.root = new DictionaryNode();
isProcessed = false;
this.nineWordCount = 0;
this.totalWordCount = 0;
}
private boolean sanitiseSearch(String text) {
if (text == null) {
return false;
}
else {
return text.matches("[a-zA-Z]");
}
}
/**
* Add a word to Dictionary
* #param word word to be added
*/
public void addWord(String word) {
if (word == null) {
throw new IllegalArgumentException("Word to be added to Dictionary can't be null");
}
// Sanitise input
if (word.contains(" ")) {
throw new IllegalArgumentException(
"Word to be added to Dictionary can't contain white spaces");
}
DictionaryNode currentNode = this.root;
for (char c: word.toCharArray()) {
DictionaryNode child = currentNode.getChild(c);
if (child == null) {
currentNode = currentNode.addChild(c);
}
else {
currentNode = child;
}
}
// Last node contains last character of valid word
// Set that node as Leaf Node for valid word
currentNode.setLeaf();
}
/**
*
* #param word String to be checked if it is a valid word
* #return True if valid word
*/
public boolean isWord(String word) {
if (word == null) {
throw new IllegalArgumentException("Word to be added to Dictionary can't be null");
}
// Sanitise input
if (word.contains(" ")) {
throw new IllegalArgumentException(
"Word to be added to Dictionary can't contain white spaces");
}
DictionaryNode currentNode = this.root;
for (char c: word.toCharArray()) {
DictionaryNode child = currentNode.getChild(c);
if (child == null) {
return false;
}
currentNode = child;
}
// Returns true if Last Character was leaf
return currentNode.isLeaf();
}
/**
*
* #param text String that needs to be searched
* #return List of Strings which are valid words searched using 'text'
*
*/
public ArrayList<String> getWords(String text) {
ArrayList<String> words = new ArrayList<String>();
DictionaryNode currentNode = this.root;
for (int i = 0; i < text.length() ; i++) {
DictionaryNode child = currentNode.getChild(text.charAt(i));
if (child == null) {
return words;
}
if (child.isLeaf()) {
words.add(text.substring(0,i+1));
}
currentNode = child;
}
return words;
}
/**
*
* #param inputFileStream Text file containing list of valid words
* Switches Flag isProcessed to True
*/
public void processFile(InputStream inputFileStream) {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(inputFileStream));
String line;
while((line = br.readLine()) != null) {
line = line.trim();
this.addWord(line);
// Nine Word test
if (line.length() == 9) {
this.nineWordCount++;
}
this.totalWordCount++;
}
}
catch(Exception e){
System.out.print(e);
}
this.isProcessed = true;
}
/**
*
* #return True if valid words text file has been processed
* Word file needs to be processed just once
*/
public boolean isProcessed() {
return this.isProcessed;
}
/**
* Factory method to create Singleton Object
* #return Singleton object
*/
public static FastDictionary getInstance() {
if (fastDictionary == null) {
fastDictionary = new FastDictionary();
}
return fastDictionary;
}
public int getNineWordCount() {
return this.nineWordCount;
}
}
**Node**
package com.FastDictionary;
import java.util.HashMap;
/**
* Node of the Trie Data Structure used for FastDictionary
*/
public class DictionaryNode {
// Character which the Node represents
private char nodeChar;
// Points to children
private HashMap<Character, DictionaryNode> children = new HashMap<Character,DictionaryNode>();
// Is Node the last character for a valid word
private boolean isLeaf;
/**
* To create Root Node
*/
DictionaryNode() {
this.nodeChar = '.';
this.isLeaf = false;
}
/**
* To create Child Node
* #param c Character that Node represents
*/
DictionaryNode(char c) {
this.nodeChar = c;
isLeaf = false;
}
/**
*
* #param c Character that Node represents
* #return Child Node which was created
*/
public DictionaryNode addChild(char c) {
DictionaryNode child = new DictionaryNode(c);
this.children.put(c, child);
return child;
}
/**
*
* #return true if Node is the last character for a valid word; default is false
*/
public boolean isLeaf() {
return this.isLeaf;
}
/**
* Set Node as Leaf Node for a valid word
*/
public void setLeaf() {
this.isLeaf = true;
}
/**
*
* #param c the character which the Child Node represnts
* #return Child Node representing character c; null if no such Child exists
*/
public DictionaryNode getChild(char c) {
DictionaryNode child = this.children.get(c);
return child;
}
}

Yes, he only shows how to choose first character from root node. However, after you update your currentNode following that character, you can apply exact same principal to find next character from the new node. Another way of viewing what his algorithm did is, given a node, an integer L(5 in his example), finds i'th (1234 in his example) word which is in the subtree of that node and is exactly L depth away from it.
So after you have made your first move, you can recursively call that algorithm from new node, with L-1 as depth. This is basic idea. Of course,some details need to be filled.
Firstly, updating i before next recursive call. Say algorithm chose first character to be d. And first 3 letters i.e a b c combinedly had 1000 5-letter words. So now, you need to find (1234-1000)=234th word from this new node.
Secondly, instead of having lengthFrequencyByLetter and totalLengthFrequency for entire tree,now you need to have them for every single node, which will require lots of ram. (you can optimize that by using HashMap though.)
A very high level implementation could be:
String randomWord(Node currentNode,int L,int index){
if(L==0) return node.wordContainedWithin();
char ch = find_next_character(node,L,index); //'d' in our example
newNode = currentNode.getChild(ch); //node following d
//following example, words_before = 1000
int words_before = sum(lengthFrequencyByLetter[x][L] of all x before ch)
int new_index = index - words_before;
return randomWord(newNode,L-1,new_index);
}
Now to get a random L-letter word, look up root's totalLengthFrequency[L], generate a number i (1234 here) between 0 to that value, and call randomWord as:
randomWord(tree.root,L,i)

Related

How to read numeric value from excel file using spring batch excel

I am reading values from .xlsx using spring batch excel and POI. I see numeric values are printing with different format than the original value in .xlsx
Please suggest me , How to print the values as its in .xlsx file. Below are the details.
In my Excel values are as follows
The values are printing as below
My code is as below
public ItemReader<DataObject> fileItemReader(InputStream inputStream){
PoiItemReader<DataObject> reader = new PoiItemReader<DataObject>();
reader.setLinesToSkip(1);
reader.setResource(new InputStreamResource(DataObject));
reader.setRowMapper(excelRowMapper());
reader.open(new ExecutionContext());
return reader;
}
private RowMapper<DataObject> excelRowMapper() {
return new MyRowMapper();
}
public class MyRowMapper implements RowMapper<DataObject> {
#Override
public DataRecord mapRow(RowSet rowSet) throws Exception {
DataObject dataObj = new DataObject();
dataObj.setFieldOne(rowSet.getColumnValue(0));
dataObj.setFieldTwo(rowSet.getColumnValue(1));
dataObj.setFieldThree(rowSet.getColumnValue(2));
dataObj.setFieldFour(rowSet.getColumnValue(3));
return dataObj;
}
}
I had this same problem, and its root is the class org.springframework.batch.item.excel.poi.PoiSheet inside PoiItemReader.
The problem happens in the method public String[] getRow(final int rowNumber) where it gets a org.apache.poi.ss.usermodel.Row object and convert it to an array of Strings after detecting the type of each column in the row. In this method, we have the code:
switch (cellType) {
case NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
Date date = cell.getDateCellValue();
cells.add(String.valueOf(date.getTime()));
} else {
cells.add(String.valueOf(cell.getNumericCellValue()));
}
break;
case BOOLEAN:
cells.add(String.valueOf(cell.getBooleanCellValue()));
break;
case STRING:
case BLANK:
cells.add(cell.getStringCellValue());
break;
case ERROR:
cells.add(FormulaError.forInt(cell.getErrorCellValue()).getString());
break;
default:
throw new IllegalArgumentException("Cannot handle cells of type '" + cell.getCellTypeEnum() + "'");
}
In which the treatment for a cell identified as NUMERIC is cells.add(String.valueOf(cell.getNumericCellValue())). In this line, the cell value is converted to double (cell.getNumericCellValue()) and this double is converted to String (String.valueOf()). The problem happens in the String.valueOf() method, that will generate scientific notation if the number is too big (>=10000000) or too small(<0.001) and will put the ".0" on integer values.
As an alternative to the line cells.add(String.valueOf(cell.getNumericCellValue())), you could use
DataFormatter formatter = new DataFormatter();
cells.add(formatter.formatCellValue(cell));
that will return to you the exact values of the cells as a String. However, this also mean that your decimal numbers will be locale dependent (you'll receive the string "2.5" from a document saved on an Excel configured for UK or India and the string "2,5" from France or Brazil).
To avoid this dependency, we can use the solution presented on https://stackoverflow.com/a/25307973/9184574:
DecimalFormat df = new DecimalFormat("0", DecimalFormatSymbols.getInstance(Locale.ENGLISH));
df.setMaximumFractionDigits(340);
cells.add(df.format(cell.getNumericCellValue()));
That will convert the cell to double and than format it to the English pattern without scientific notation or adding ".0" to integers.
My implementation of the CustomPoiSheet (small adaptation on original PoiSheet) was:
class CustomPoiSheet implements Sheet {
protected final org.apache.poi.ss.usermodel.Sheet delegate;
private final int numberOfRows;
private final String name;
private FormulaEvaluator evaluator;
/**
* Constructor which takes the delegate sheet.
*
* #param delegate the apache POI sheet
*/
CustomPoiSheet(final org.apache.poi.ss.usermodel.Sheet delegate) {
super();
this.delegate = delegate;
this.numberOfRows = this.delegate.getLastRowNum() + 1;
this.name=this.delegate.getSheetName();
}
/**
* {#inheritDoc}
*/
#Override
public int getNumberOfRows() {
return this.numberOfRows;
}
/**
* {#inheritDoc}
*/
#Override
public String getName() {
return this.name;
}
/**
* {#inheritDoc}
*/
#Override
public String[] getRow(final int rowNumber) {
final Row row = this.delegate.getRow(rowNumber);
if (row == null) {
return null;
}
final List<String> cells = new LinkedList<>();
final int numberOfColumns = row.getLastCellNum();
for (int i = 0; i < numberOfColumns; i++) {
Cell cell = row.getCell(i);
CellType cellType = cell.getCellType();
if (cellType == CellType.FORMULA) {
FormulaEvaluator evaluator = getFormulaEvaluator();
if (evaluator == null) {
cells.add(cell.getCellFormula());
} else {
cellType = evaluator.evaluateFormulaCell(cell);
}
}
switch (cellType) {
case NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
Date date = cell.getDateCellValue();
cells.add(String.valueOf(date.getTime()));
} else {
// Returns numeric value the closer possible to it's value and shown string, only formatting to english format
// It will result in an integer string (without decimal places) if the value is a integer, and will result
// on the double string without trailing zeros. It also suppress scientific notation
// Regards to https://stackoverflow.com/a/25307973/9184574
DecimalFormat df = new DecimalFormat("0", DecimalFormatSymbols.getInstance(Locale.ENGLISH));
df.setMaximumFractionDigits(340);
cells.add(df.format(cell.getNumericCellValue()));
//DataFormatter formatter = new DataFormatter();
//cells.add(formatter.formatCellValue(cell));
//cells.add(String.valueOf(cell.getNumericCellValue()));
}
break;
case BOOLEAN:
cells.add(String.valueOf(cell.getBooleanCellValue()));
break;
case STRING:
case BLANK:
cells.add(cell.getStringCellValue());
break;
case ERROR:
cells.add(FormulaError.forInt(cell.getErrorCellValue()).getString());
break;
default:
throw new IllegalArgumentException("Cannot handle cells of type '" + cell.getCellTypeEnum() + "'");
}
}
return cells.toArray(new String[0]);
}
private FormulaEvaluator getFormulaEvaluator() {
if (this.evaluator == null) {
this.evaluator = delegate.getWorkbook().getCreationHelper().createFormulaEvaluator();
}
return this.evaluator;
}
}
And my implementation of CustomPoiItemReader (small adaptation on original PoiItemReader) calling CustomPoiSheet:
public class CustomPoiItemReader<T> extends AbstractExcelItemReader<T> {
private Workbook workbook;
#Override
protected Sheet getSheet(final int sheet) {
return new CustomPoiSheet(this.workbook.getSheetAt(sheet));
}
public CustomPoiItemReader(){
super();
}
#Override
protected int getNumberOfSheets() {
return this.workbook.getNumberOfSheets();
}
#Override
protected void doClose() throws Exception {
super.doClose();
if (this.workbook != null) {
this.workbook.close();
}
this.workbook=null;
}
/**
* Open the underlying file using the {#code WorkbookFactory}. We keep track of the used {#code InputStream} so that
* it can be closed cleanly on the end of reading the file. This to be able to release the resources used by
* Apache POI.
*
* #param inputStream the {#code InputStream} pointing to the Excel file.
* #throws Exception is thrown for any errors.
*/
#Override
protected void openExcelFile(final InputStream inputStream) throws Exception {
this.workbook = WorkbookFactory.create(inputStream);
this.workbook.setMissingCellPolicy(Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
}
}
just change your code like this while reading data from excel.
dataObj.setField(Float.valueOf(rowSet.getColumnValue(idx)).intValue();
this is only working for Column A,B,C

Sentinel node in Binary Search Trees

I was wondering if in a way to avoid having to deal with the root as a special case in a Binary Search Tree I could use some sort of sentinel root node?
public void insert(int value) {
if (root == null) {
root = new Node(value);
++size;
} else {
Node node = root;
while (true) {
if (value < node.value) {
if (node.left == null) {
node.left = new Node(value);
++size;
return;
} else {
node = node.left;
}
} else if (value > node.value) {
if (node.right == null) {
node.right = new Node(value);
++size;
return;
} else {
node = node.right;
}
} else return;
}
}
}
For instance, in the insert() operation I have to treat the root node in a special way. In the delete() operation the same will happen, in fact, it will be way worse.
I've thought a bit regarding the issue but I couldn't come with any good solution. Is it because it is simply not possible or am I missing something?
The null node itself is the sentinel, but instead of using null, you can use an instance of a Node with a special flag (or a special subclass), which is effectively the null node. A Nil node makes sense, as that is actually a valid tree: empty!
And by using recursion you can get rid of the extra checks and new Node littered all over (which is what I presume is really bothering you).
Something like this:
class Node {
private Value v;
private boolean is_nil;
private Node left;
private Node right;
public void insert(Value v) {
if (this.is_nil) {
this.left = new Node(); // Nil node
this.right = new Node(); // Nil node
this.v = v;
this.is_nil = false;
return;
}
if (v > this.v) {
this.right.insert(v);
} else {
this.left.insert(v);
}
}
}
class Tree {
private Node root;
public Tree() {
root = new Node(); // Nil Node.
}
public void insert(Value v) {
root.insert(v);
}
}
If you don't want to use recursion, your while(true) is kind of a code smell.
Say we keep it as null, we can perhaps refactor it as.
public void insert(Value v) {
prev = null;
current = this.root;
boolean left_child = false;
while (current != null) {
prev = current;
if (v > current.v) {
current = current.right;
left_child = false;
} else {
current = current.left;
left_child = true;
}
}
current = new Node(v);
if (prev == null) {
this.root = current;
return;
}
if (left_child) {
prev.left = current;
} else {
prev.right = current;
}
}
The root will always be a special case. The root is the entry point to the binary search tree.
Inserting a sentinel root node means that you will have a root node that is built at the same time as the tree. Furthermore, the sentinel as you mean it will just decrease the balance of the tree (the BST will always be at the right/left of its root node).
The only way that pops in my mind to not manage the root node as a special case during insert/delete is to add empty leaf nodes. In this way you never have an empty tree, but instead a tree with an empty node.
During insert() you just replace the empty leaf node with a non-empty node and two new empty leafs (left and right).
During delete(), as a last step (if such operation is implemented as in here) you just empty the node (it becomes an empty leaf) and trim its existing leafs.
Keep in mind that if you implement it this way you will have more space occupied by empty leaf nodes than by nodes with meaningful data. So, this implementation has sense only if space is not an issue.
The code would look something like this:
public class BST {
private Node root;
public BST(){
root = new Node();
}
public void insert(int elem){
root.insert(elem);
}
public void delete(int elem){
root.delete(elem);
}
}
public class Node{
private static final int EMPTY_VALUE = /* your empty value */;
private int element;
private Node parent;
private Node left;
private Node right;
public Node(){
this(EMPTY_VALUE, null, null, null);
}
public Node(int elem, Node p, Node l, Node r){
element = elem;
parent = p;
left = l;
right = r;
}
public void insert(int elem){
Node thisNode = this;
// this cycle goes on until an empty node is found
while(thisNode.element != EMPTY_VALUE){
// follow the correct path for the insertion here
}
// insert new element here
// thisNode is an empty node at this point
thisNode.element = elem;
thisNode.left = new Node();
thisNode.right = new Node();
thisNode.left.parent = thisNode;
thisNode.right.parent = thisNode;
}
public void delete(int elem){
// manage delete here
}
}

BASH brace expansion algorithm

I am stuck on this algorithmic question :
design an algorithm that parse an expression like this :
"((a,b,cy)n,m)" should give :
an - bn - cyn - m
The expression can nest, therefore :
"((a,b)o(m,n)p,b)" parses to ;
aomp - aonp - bomp - bonp - b.
I thought of using stacks, but it is too complicated.
thanks.
You can parse it with a Recursive Descent Parser.
Let's say the comma separated strings are components, so for an expression ((a, b, cy)n, m), (a, b, cy)n and m are two components. a, b and cy are also components. So this is a recursive definition.
For a component (a, b, cy)n, let's say (a, b, cy) and n are two component parts of the component. Component parts will later be combined to produce final result (i.e., an - bn - cyn).
Let's say an expression is comma separated components, for example, (a, cy)n, m is an expression. It has two components (a, cy)n and m, and the component (a, cy)n has two component parts (a, cy) and n, and component part (a, cy) is a brace expression containing a nested expression: a, cy, which also has two components a and cy.
With these definitions (you might use other terms), we can write down the grammar for your expression:
expression = component, component, ...
component = component_part component_part ...
component_part = letters | (expression)
One line is one grammar rule. The first line means an expression is a list of comma separated components. The second line means a component can be constructed with one or more component parts. The third line means a component part can be either a continuous sequence of letters or a nested expression inside a pair of braces.
Then you can use a Recursive Descent Parser to solve your problem with the above grammar.
We will define one method/function for each grammar rule. So basically we will have three methods ParseExpression, ParseComponent, ParseComponentPart.
Algorithm
As I stated above, an expression is comma separated components, so in our ParseExpression method, it simply calls ParseComponent, and then check if the next char is comma or not, like this (I'm using C#, I think you can easily convert it to other languages):
private List<string> ParseExpression()
{
var result = new List<string>();
while (!Eof())
{
// Parsing a component will produce a list of strings,
// they are added to the final string list
var items = ParseComponent();
result.AddRange(items);
// If next char is ',' simply skip it and parse next component
if (Peek() == ',')
{
// Skip comma
ReadNextChar();
}
else
{
break;
}
}
return result;
}
You can see that, when we are parsing an expression, we recursively call ParseComponent (it will then recursively call ParseComponentPart). It's a top-down approach, that's why it's called Recursive Descent Parsing.
ParseComponent is similar, like this:
private List<string> ParseComponent()
{
List<string> leftItems = null;
while (!Eof())
{
// Parse a component part will produce a list of strings (rightItems)
// We need to combine already parsed string list (leftItems) in this component
// with the newly parsed 'rightItems'
var rightItems = ParseComponentPart();
if (rightItems == null)
{
// No more parts, return current result (leftItems) to the caller
break;
}
if (leftItems == null)
{
leftItems = rightItems;
}
else
{
leftItems = Combine(leftItems, rightItems);
}
}
return leftItems;
}
The combine method simply combines two string list:
// Combine two lists of strings and return the combined string list
private List<string> Combine(List<string> leftItems, List<string> rightItems)
{
var result = new List<string>();
foreach (var leftItem in leftItems)
{
foreach (var rightItem in rightItems)
{
result.Add(leftItem + rightItem);
}
}
return result;
}
Then is the ParseComponentPart:
private List<string> ParseComponentPart()
{
var nextChar = Peek();
if (nextChar == '(')
{
// Skip '('
ReadNextChar();
// Recursively parse the inner expression
var items = ParseExpression();
// Skip ')'
ReadNextChar();
return items;
}
else if (char.IsLetter(nextChar))
{
var letters = ReadLetters();
return new List<string> { letters };
}
else
{
// Fail to parse a part, it means a component is ended
return null;
}
}
Full Source Code (C#)
The other parts are mostly helper methods, full C# source code is listed below:
using System;
using System.Collections.Generic;
using System.Text;
namespace Examples
{
public class BashBraceParser
{
private string _expression;
private int _nextCharIndex;
/// <summary>
/// Parse the specified BASH brace expression and return the result string list.
/// </summary>
public IList<string> Parse(string expression)
{
_expression = expression;
_nextCharIndex = 0;
return ParseExpression();
}
private List<string> ParseExpression()
{
// ** This part is already posted above **
}
private List<string> ParseComponent()
{
// ** This part is already posted above **
}
private List<string> ParseComponentPart()
{
// ** This part is already posted above **
}
// Combine two lists of strings and return the combined string list
private List<string> Combine(List<string> leftItems, List<string> rightItems)
{
// ** This part is already posted above **
}
// Peek next char without moving the cursor
private char Peek()
{
if (Eof())
{
return '\0';
}
return _expression[_nextCharIndex];
}
// Read next char and move the cursor to next char
private char ReadNextChar()
{
return _expression[_nextCharIndex++];
}
private void UnreadChar()
{
_nextCharIndex--;
}
// Check if the whole expression string is scanned.
private bool Eof()
{
return _nextCharIndex == _expression.Length;
}
// Read a continuous sequence of letters.
private string ReadLetters()
{
if (!char.IsLetter(Peek()))
{
return null;
}
var str = new StringBuilder();
while (!Eof())
{
var ch = ReadNextChar();
if (char.IsLetter(ch))
{
str.Append(ch);
}
else
{
UnreadChar();
break;
}
}
return str.ToString();
}
}
}
Use The Code
var parser = new BashBraceParser();
var result = parser.Parse("((a,b)o(m,n)p,b)");
var output = String.Join(" - ", result);
// Result: aomp - aonp - bomp - bonp - b
Console.WriteLine(output);
public class BASHBraceExpansion {
public static ArrayList<StringBuilder> parse_bash(String expression, WrapperInt p) {
ArrayList<StringBuilder> elements = new ArrayList<StringBuilder>();
ArrayList<StringBuilder> result = new ArrayList<StringBuilder>();
elements.add(new StringBuilder(""));
while(p.index < expression.length())
{
if (expression.charAt(p.index) == '(')
{
p.advance();
ArrayList<StringBuilder> temp = parse_bash(expression, p);
ArrayList<StringBuilder> newElements = new ArrayList<StringBuilder>();
for(StringBuilder e : elements)
{
for(StringBuilder t : temp)
{
StringBuilder s = new StringBuilder(e);
newElements.add(s.append(t));
}
}
System.out.println("elements :");
elements = newElements;
}
else if (expression.charAt(p.index) == ',')
{
result.addAll(elements);
elements.clear();
elements.add(new StringBuilder(""));
p.advance();
}
else if (expression.charAt(p.index) == ')')
{
p.advance();
result.addAll(elements);
return result;
}
else
{
for(StringBuilder sb : elements)
{
sb.append(expression.charAt(p.index));
}
p.advance();
}
}
return elements;
}
public static void print(ArrayList<StringBuilder> list)
{
for(StringBuilder s : list)
{
System.out.print(s + " * ");
}
System.out.println();
}
public static void main(String[] args) {
WrapperInt p = new WrapperInt();
ArrayList<StringBuilder> list = parse_bash("((a,b)o(m,n)p,b)", p);
//ArrayList<StringBuilder> list = parse_bash("(a,b)", p);
WrapperInt q = new WrapperInt();
ArrayList<StringBuilder> list1 = parse_bash("((a,b,cy)n,m)", q);
ArrayList<StringBuilder> list2 = parse_bash("((a,b)dr(f,g)(k,m),L(p,q))", new WrapperInt());
System.out.println("*****RESULT : ******");
print(list);
print(list1);
print(list2);
}
}
public class WrapperInt {
public WrapperInt() {
index = 0;
}
public int advance()
{
index ++;
return index;
}
public int index;
}
// aomp - aonp - bomp - bonp - b.

Is it possible to design a tree where nodes have infinitely many children?

How can design a tree with lots (infinite number) of branches ?
Which data structure we should use to store child nodes ?
You can't actually store infinitely many children, since that won't fit into memory. However, you can store unboundedly many children - that is, you can make trees where each node can have any number of children with no fixed upper bound.
There are a few standard ways to do this. You could have each tree node store a list of all of its children (perhaps as a dynamic array or a linked list), which is often done with tries. For example, in C++, you might have something like this:
struct Node {
/* ... Data for the node goes here ... */
std::vector<Node*> children;
};
Alternatively, you could use the left-child/right-sibling representation, which represents a multiway tree as a binary tree. This is often used in priority queues like binomial heaps. For example:
struct Node {
/* ... data for the node ... */
Node* firstChild;
Node* nextSibling;
};
Hope this helps!
Yes! You can create a structure where children are materialized on demand (i.e. "lazy children"). In this case, the number of children can easily be functionally infinite.
Haskell is great for creating "functionally infinite" data structures, but since I don't know a whit of Haskell, here's a Python example instead:
class InfiniteTreeNode:
''' abstract base class for a tree node that has effectively infinite children '''
def __init__(self, data):
self.data = data
def getChild(self, n):
raise NotImplementedError
class PrimeSumNode(InfiniteTreeNode):
def getChild(self, n):
prime = getNthPrime(n) # hypothetical function to get the nth prime number
return PrimeSumNode(self.data + prime)
prime_root = PrimeSumNode(0)
print prime_root.getChild(3).getChild(4).data # would print 18: the 4th prime is 7 and the 5th prime is 11
Now, if you were to do a search of PrimeSumNode down to a depth of 2, you could find all the numbers that are sums of two primes (and if you can prove that this contains all even integers, you can win a big mathematical prize!).
Something like this
Node {
public String name;
Node n[];
}
Add nodes like so
public Node[] add_subnode(Node n[]) {
for (int i=0; i<n.length; i++) {
n[i] = new Node();
p("\n Enter name: ");
n[i].name = sc.next();
p("\n How many children for "+n[i].name+"?");
int children = sc.nextInt();
if (children > 0) {
Node x[] = new Node[children];
n[i].n = add_subnode(x);
}
}
return n;
}
Full working code:
class People {
private Scanner sc;
public People(Scanner sc) {
this.sc = sc;
}
public void main_thing() {
Node head = new Node();
head.name = "Head";
p("\n How many nodes do you want to add to Head: ");
int nodes = sc.nextInt();
head.n = new Node[nodes];
Node[] n = add_subnode(head.n);
print_nodes(head.n);
}
public Node[] add_subnode(Node n[]) {
for (int i=0; i<n.length; i++) {
n[i] = new Node();
p("\n Enter name: ");
n[i].name = sc.next();
p("\n How many children for "+n[i].name+"?");
int children = sc.nextInt();
if (children > 0) {
Node x[] = new Node[children];
n[i].n = add_subnode(x);
}
}
return n;
}
public void print_nodes(Node n[]) {
if (n!=null && n.length > 0) {
for (int i=0; i<n.length; i++) {
p("\n "+n[i].name);
print_nodes(n[i].n);
}
}
}
public static void p(String msg) {
System.out.print(msg);
}
}
class Node {
public String name;
Node n[];
}
I recommend you to use a Node class with a left child Node and right child Node and a parent Node.
public class Node
{
Node<T> parent;
Node<T> leftChild;
Node<T> rightChild;
T value;
Node(T val)
{
value = val;
leftChild = new Node<T>();
leftChild.parent = this;
rightChild = new Node<T>();
rightChild.parent = this;
}
You can set grand father and uncle and sibling like this.
Node<T> grandParent()
{
if(this.parent.parent != null)
{
return this.parent.parent;
}
else
return null;
}
Node<T> uncle()
{
if(this.grandParent() != null)
{
if(this.parent == this.grandParent().rightChild)
{
return this.grandParent().leftChild;
}
else
{
return this.grandParent().rightChild;
}
}
else
return null;
}
Node<T> sibling()
{
if(this.parent != null)
{
if(this == this.parent.rightChild)
{
return this.parent.leftChild;
}
else
{
return this.parent.rightChild;
}
}
else
return null;
}
And is impossible to have infinite child, at least you have infinite memory.
good luck !
Hope this will help you.

I have a modal Window implemented in SmartGWT - how can I close it when someone clicks off of the window?

I've created a class that extends the Window SmartGWT class, and it is set to be modal. I am trying to make the Window close when a user clicks off the window. I have tried to link it up to a FocusChangedHandler with no luck. Has anyone done something like this before?
/**
* Sets up a modal Dialog box that lets the user edit attributes associated
* with the properties of the {#link LabElement} that are given.
*
* #author Therin Irwin
*/
public class EditorDialog extends Window {
final DynamicForm dyn = new DynamicForm();
final RichTextEditor richTextEditor = new RichTextEditor();
final List attrItems = new ArrayList();
/**
* Creates a new EditorDialog with a RichTextEditor and a list of
* attributes for the element.
*
* #param name the name of the element being edited.
* #param attr the List of String attributes of the element that can be
* edited.
* #param hasText true if the element supports text inside, false if not.
*/
public EditorDialog(String name, List attr, boolean hasText) {
super();
VLayout vert = new VLayout();
this.setShowMinimizeButton(false);
this.setIsModal(true);
this.setShowModalMask(true);
this.setTitle(name + " Editor");
richTextEditor.setWidth(550);
richTextEditor.setHeight(100);
richTextEditor.setPadding(5);
richTextEditor.setCanDragResize(true);
richTextEditor.setResizeFrom("B");
richTextEditor.setShowEdges(true);
if (attr == null || attr.size() == 0) {
richTextEditor.setHeight(300);
}
else {
int i = 0;
FormItem[] fi = new FormItem[attr.size()];
for (String at : attr) {
TextItem temp = new TextItem(at, at);
attrItems.add(temp);
fi[i++] = temp;
}
dyn.setFields(fi);
dyn.setPadding(5);
dyn.setTop(100);
}
if (hasText)
vert.addMember(richTextEditor);
if (!(attr == null || attr.size() == 0))
vert.addMember(dyn);
this.addItem(vert);
this.centerInPage();
this.setAutoSize(true);
}
/**
* Returns the text of the RichTextEditor.
*
* #return the text entered into the RichTextEditor.
*/
public String getRichText() {
return richTextEditor.getValue();
}
/**
* Sets the text in the RichTextEditor to String value.
*
* #param value the String to put as the contents of the RichTextEditor.
*/
public void setRichText(String value) {
richTextEditor.setValue(value);
}
/**
* Returns the List of TextItems that hold the user-entered values for
* attributes.
*
* #return the TextItems associated with each attribute, in order.
*/
public DynamicForm getFormItems() {
return dyn;
}
public TextItem getFormItem(int item) {
return (TextItem) dyn.getFields()[item];
}
}
#Therin
I guess according to your requirement, you need to implement this property of Window:
this.setDismissOnOutsideClick(true);

Resources