How to print a properly sorted Radix Trie - algorithm

I was trying to print a properly sorted Radix Trie but when I tried to do it, it does with DFS but single letters are printed in a wrong place... What am I doing wrong? Am I doing wrong with the recursion or do I need another condition that I'm missing?
Ex:
0692
072755
0
1008
1076
10
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Trie {
static class TrieNode {
TrieNode[] children = new TrieNode[128];
boolean leaf;
}
public static void insertString(TrieNode rootNode, String s) {
TrieNode root = rootNode;
for (char ch : s.toCharArray()) {
TrieNode next = root.children[ch];
if (next == null)
root.children[ch] = next = new TrieNode();
root = next;
}
root.leaf = true;
}
public static void printSorted(TrieNode node, String s) {
for (char ch = 0; ch < node.children.length; ch++) {
TrieNode child = node.children[ch];
if (child != null)
printSorted(child, s + ch);
}
if (node.leaf) {
System.out.println(s);
}
}
public static void main(String[] args) throws IOException {
TrieNode root = new TrieNode();
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in)
);
String line = null;
while ((line = br.readLine()) != null) {
insertString(root, line);
line = null;
}
printSorted(root, "");
}
}

in your printSorted function, try printing the leaf first as the leaf is always less than its children.

Related

How to create a Binary Tree using a String array?

I am given an assignment where I need to do the following:
input your binary tree as an array, using the array representation and node labels A, ..., J, as Strings. Label null stands for a non-existent node, not for a node having a value of null.
Check the validity of your binary tree input: each node, excepting the root, should have a father.
Generate the dynamic memory implementation of the tree, using only the nodes with labels different than null.
So far I have:
public class Project1{
public static void main(String[] args){
String[] input = new String[]{"A","B","C","D","E","F","G","H","I","J"};
}
public class BinaryTree<T> implements java.io.Serializable{
private T data;
private BinaryTree<T> left;
private BinaryTree<T> right;
public BinaryTree(T data){
this.data = data;
left = null;
right = null;
}
public T getData(){
return data;
}
public void attachLeft(BinaryTree<T> tree){
if(tree != null){
left = tree;
}
}
public void attachRight(BinaryTree<T> tree){
if(tree != null){
right = tree;
}
}
public BinaryTree<T> detachLeft(){
BinaryTree<T> t = left;
left = null;
return t;
}
public BinaryTree<T> detachRight(){
BinaryTree<T> t = right;
right = null;
return t;
}
public boolean isEmpty(){
return data == null;
}
public void inOrder(BinaryTree<T> tree){
if (tree != null){
inOrder(tree.left);
System.out.println(tree.getData());
inOrder(tree.right);
}
}
public void preOrder(BinaryTree<T> tree){
if(tree != null){
System.out.println(tree.getData());
preOrder(tree.left);
preOrder(tree.right);
}
}
public void postOrder(BinaryTree<T> tree){
if(tree != null){
postOrder(tree.left);
postOrder(tree.right);
System.out.println(tree.getData());
}
}
}
What I don't understand is how to create a BinaryTree using my data from the string array

Longest consecutive sequence in Binary tree

I'm trying to implement the logic for "Longest consecutive sequence in Binary tree". The logic I have implemented inside the method { longestConsecutivePath } is not working as expected for the tree structure. It is giving me the lognest path length as 5.
Output:
curLength : 5
BSTNode node = new BSTNode(1);
node.setRight(new BSTNode(2));
node.getRight().setRight(new BSTNode(3));
node.getRight().getRight().setRight(new BSTNode(4));
node.getRight().getRight().getRight().setRight(new BSTNode(5));
node.getRight().setLeft(new BSTNode(7));
node.getRight().getLeft().setLeft(new BSTNode(8));
node.getRight().getLeft().getLeft().setLeft(new BSTNode(9));
node.getRight().getLeft().getLeft().getLeft().setLeft(new BSTNode(10));
node.getRight().getLeft().getLeft().getLeft().getLeft().setLeft(new BSTNode(11));
node.getRight().getLeft().getLeft().getLeft().getLeft().getLeft().setLeft(new BSTNode(12));
Class implementing the Longest Consecutive sequence logic:
public class LongestConsecutivePath {
static BSTNode root = null;
public LongestConsecutivePath() {
root = createBinaryTree();
System.out.println("Before finding the longest consecutive path:");
inorder();
}
public void inorder() {
if (null == root) {
return;
}
inorder(root);
}
private void inorder(BSTNode node) {
if (null != node) {
inorder(node.getLeft());
System.out.print(node.getData() + " ");
inorder(node.getRight());
}
}
public BSTNode createBinaryTree() {
BSTNode node = new BSTNode(1);
node.setRight(new BSTNode(2));
node.getRight().setRight(new BSTNode(3));
node.getRight().getRight().setRight(new BSTNode(4));
node.getRight().getRight().getRight().setRight(new BSTNode(5));
node.getRight().setLeft(new BSTNode(7));
node.getRight().getLeft().setLeft(new BSTNode(8));
node.getRight().getLeft().getLeft().setLeft(new BSTNode(9));
node.getRight().getLeft().getLeft().getLeft().setLeft(new BSTNode(10));
node.getRight().getLeft().getLeft().getLeft().getLeft().setLeft(new BSTNode(11));
node.getRight().getLeft().getLeft().getLeft().getLeft().getLeft().setLeft(new BSTNode(12));
return node;
}
public int longestConsecutivePath() {
if (null == root) {
return 0;
}
return longestConsecutivePath(root, 0, root.getData() + 1);
}
public int longestConsecutivePath(BSTNode node, int curLength,
int targetLength) {
if (null == node) {
return curLength;
}
if (node.getData() == targetLength) {
System.out.println("\nnode data value: "+node.getData());
curLength += 1;
longestPath = curLength;
} else {
curLength = 1;
}
longestLeft = longestConsecutivePath(node.getLeft(), curLength,
node.getData() + 1);
longestRight = longestConsecutivePath(node.getRight(), curLength,
node.getData() + 1);
return Math.max(curLength, Math.max(longestLeft, longestRight));
}
public static void main(String[] args) {
LongestConsecutivePath consecutivePath = new LongestConsecutivePath();
int curLength = consecutivePath.longestConsecutivePath();
System.out.println("\ncurLength : " + curLength);
}
}
BSTNode.java
public class BSTNode {
BSTNode left, right;
int data;
/* Default constructor */
public BSTNode() {
left = null;
right = null;
data = 0;
}
/* Constructor */
public BSTNode(int data) {
left = null;
right = null;
this.data = data;
}
public BSTNode getLeft() {
return left;
}
public void setLeft(BSTNode left) {
this.left = left;
}
public BSTNode getRight() {
return right;
}
public void setRight(BSTNode right) {
this.right = right;
}
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
}

Building anagram finder and I have one eclipse error: insert } to complete block.

Problem is that the eclipse recommendation makes little sense -- to me. I checked my blocks several times.
This is my first time posting code so I'm hoping it's formatted ok.
The eclipse error is on line 73: below the ; "anagrams.add(current);" This is the second line below the last for loop in the code.
package anagrecur2;
import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;
import java.io.*;
public class AnagRecur2Main {
public static void main(String[] args) {
List<String> anagrams = new ArrayList<String>();
List<String> preString = new ArrayList<String>();
List<String> postString = new ArrayList<String>();
List<String> word = new ArrayList<String>();
word.add("t");
word.add("e");
word.add("a");
word.add("m");
preString.add("");
postString.add("");
String c;
String current;
}
ArrayList<String> getAnagrams (String word, String preString){
// remove the first occurrence of each
// character in preString from word and
// stores it in postString
}
ArrayList<String> removePreStringFromWord(List word){
ArrayList<String> postString;
ArrayList<String> preString;
for (int i = 0; i < preString.size(); i++) {
for (int j = 0; j < word.size(); j++) {
if (preString.get(i)== word.get(j)){
word.remove(j);
}else {
postString.add((String) word.get(j));
}
}
return postString;
}
}
// using a string as if it is a c# string.
// for java you need to convert the string to
// char array
//ArrayList<String> word;
//String current;
//char poststrCharA;
ArrayList<String> anagrams;
ArrayList<String> preString;
ArrayList<String> postString;
String[] prestrAr = new String[preString.size()];{
prestrAr = preString.toArray(prestrAr);
for(String s : prestrAr){
System.out.println(s);
}
for (String poststrCharA : postString){
poststrCharA.toCharArray();
System.out.println("postStringtoCharAr"+poststrCharA);
}
// adds string combo to anagrams if
// it is a true word
for (String c : prestrAr) {
String current = prestrAr + c;
anagrams.add(current);
}
void getAnagrams(char word, char current){
System.out.println("word= "+word+"current= "+current);
}
}
First off, your getAnagrams doesn't return a string Array list. Also, what are you trying to accomplish with this file?

SimpleTextLoader UDF in Pig

I want to create a Custom Load function for Pig UDF, I have created a SimpleTextLoader using the link
https://pig.apache.org/docs/r0.11.0/udf.html , I have successfully generate the jar file for this code, register in pig and run a Pig Script.I am getting the empty output. I don't know how to solve this issue, any help would be appreciated.
Below is my Java code
public class SimpleTextLoader extends LoadFunc{
protected RecordReader in = null;
private byte fieldDel = '\t';
private ArrayList<Object> mProtoTuple = null;
private TupleFactory mTupleFactory = TupleFactory.getInstance();
private static final int BUFFER_SIZE = 1024;
public SimpleTextLoader() {
}
public SimpleTextLoader(String delimiter)
{
this();
if (delimiter.length() == 1) {
this.fieldDel = (byte)delimiter.charAt(0);
} else if (delimiter.length() > 1 && delimiter.charAt(0) == '\\') {
switch (delimiter.charAt(1)) {
case 't':
this.fieldDel = (byte)'\t';
break;
case 'x':
fieldDel =
Integer.valueOf(delimiter.substring(2), 16).byteValue();
break;
case 'u':
this.fieldDel =
Integer.valueOf(delimiter.substring(2)).byteValue();
break;
default:
throw new RuntimeException("Unknown delimiter " + delimiter);
}
} else {
throw new RuntimeException("PigStorage delimeter must be a single character");
}
}
private void readField(byte[] buf, int start, int end) {
if (mProtoTuple == null) {
mProtoTuple = new ArrayList<Object>();
}
if (start == end) {
// NULL value
mProtoTuple.add(null);
} else {
mProtoTuple.add(new DataByteArray(buf, start, end));
}
} #Override
public Tuple getNext() throws IOException {
try {
boolean notDone = in.nextKeyValue();
if (notDone) {
return null;
}
Text value = (Text) in.getCurrentValue();
System.out.println("printing value" +value);
byte[] buf = value.getBytes();
int len = value.getLength();
int start = 0;
for (int i = 0; i < len; i++) {
if (buf[i] == fieldDel) {
readField(buf, start, i);
start = i + 1;
}
}
// pick up the last field
readField(buf, start, len);
Tuple t = mTupleFactory.newTupleNoCopy(mProtoTuple);
mProtoTuple = null;
System.out.println(t);
return t;
} catch (InterruptedException e) {
int errCode = 6018;
String errMsg = "Error while reading input";
throw new ExecException(errMsg, errCode,
PigException.REMOTE_ENVIRONMENT, e);
}
}
#Override
public void setLocation(String string, Job job) throws IOException {
FileInputFormat.setInputPaths(job,string);
}
#Override
public InputFormat getInputFormat() throws IOException {
return new TextInputFormat();
}
#Override
public void prepareToRead(RecordReader reader, PigSplit ps) throws IOException {
in=reader;
}
}
Below is my Pig Script
REGISTER /home/hadoop/netbeans/sampleloader/dist/sampleloader.jar
a= load '/input.txt' using sampleloader.SimpleTextLoader();
store a into 'output';
You are using sampleloader.SimpleTextLoader() that doesn't do anything as it is just an empty constructor.
Instead use sampleloader.SimpleTextLoader(String delimiter) which is performing the actual operation of split.

Class not found Kryo exception in hive 0.13 - Hadoop

I have a GenericUDF (see code below) that was running fine on Hadoop-1 and Hive-0.12. But when testing the same GenericUDF using Hive-0.13 + Hadoop-2, I am getting the below error.
Vertex failed, vertexName=Map 12, vertexId=vertex_1409698731658_42202_1_00, diagnostics=[Vertex Input: ccv initializer failed., org.apache.hive.com.esotericsoftware.kry
o.KryoException: Unable to find class: com.xxx.xxx.Id1
Here is the code for my UDF.
package com.xxx.xxx;
import org.apache.hadoop.hive.*;
public class Id1 extends GenericUDF {
private MapredContext context;
private long sequenceNum = 0;
private static final int padLength = 10;
StringBuilder sb = null;
public ObjectInspector initialize(ObjectInspector[] arguments)
throws UDFArgumentException {
sequenceNum = 0;
sb = new StringBuilder();
return PrimitiveObjectInspectorFactory.javaStringObjectInspector;
}
public Object evaluate(DeferredObject[] arguments) throws HiveException {
int sbLength = sb.toString().length();
if (sbLength > 0)
sb.replace(0, sbLength, "");
String taskId = null;
if (context.getJobConf() != null)
taskId = context.getJobConf().get("mapred.taskid");
sequenceNum++;
if (taskId != null) {
sb.append(taskId.replace("attempt_", ""));
}
int i = 0;
String seqStr = String.valueOf(sequenceNum);
sb.append(seqStr);
return sb.toString();
}
public String getDisplayString(String[] children) {
return "id1()";
}
#Override
public void configure(MapredContext context) {
this.context = context;
}
}
I am certain this has something to do with Hive-0.13, but not able to see any post related to this error.

Resources