Get element in binary search tree given a path of ones and zeros - binary-search-tree

I have a string of ones and zeros, zero mean left and ones mean right, and I need to return the item to the end of the path. If the path leads to nothing returns null.
Tree:
15
/ \
12 18
/ / \
10 16 20
\ \
11 17
String 001 will return 11
String 101 will return 17
String 1111 will return null
How can I write this method in Java?

you can traverse among this tree and check for each character of the string if it is 0 then getleft() and if it is 1 then getright()
and so on, i hope this help :D
i have a midterm tomorrow so i don't have time to write it's implementation now :D

Related

Finding Characters in String

So, I'm having this problem and I have no idea how to handle it
Say I have a string with the following format:
"3 6 9 12 13 15 16"
I'm searching for "6" and I find it at position 3, and I remove it.
Next, I search for 6 again, and I find it at position IndexOf(6) (whatever that is). This time I don't want to remove it because it's the 6 in 16.
if string1.contains(6) then
string1 = string1.RemoveAt(string.IndexOf(6),2)
end if
This is vbnet, but any solution to this problem would help.
P.S. This is just a sample code, the main code I'm using has too many things attached to it, and cleaning it for this example would be a nightmare
You asked for a "fancier" solution so I'll give you one:
Dim input As String = "3 6 9 12 13 15 16"
Dim output As String = String.Join(" ", input.Split(" "c).Where(Function(s) s <> "6"))
Debug.WriteLine(output)
3 9 12 13 15 16
There could be more elegant ways of doing this, but if you are processing numbers, convert it to numbers, then you can just look for the number you are interested in.
If you need it in space delimited form, you can always convert it back.
I'm afraid there won't be any "shortcuts" with this one.
Another thing to consider if you are working with actual strings delimited by space, and are looking for patterns, then Regular Expressions is the way to go.
Dim input As String = "3 4 5 6 13 14 15 16"
Dim inputArray() As String = input.Split(" ")
Dim lst As New List(Of Integer)
For Each s In inputArray
lst.Add(Convert.ToInt32(s))
Next
If lst.Contains(6) Then
lst.Remove(6)
End If
A better way to solve the problem is to use regex (tested with sed on Mac OSX):
echo "6 3 6 9 12 13 15 16" | sed -E "s/(6 |[^1-9]6| 6$)//g"
# outputs
3 9 12 13 15 16

Split a string to its subwords

Every letter has a value
a b c d e f g h i j k l m n o p q r s t u v w x y z
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
TableA
String Length Value Subwords
exampledomain 13 132 #example-domain#example-do-main#
creditcard 10 85 #credit-card#credit-car-d#
TableB
Words Length Value
example 7 76
do 2 19
main 4 37
domain 6 56
credit 6 59
card 4 26
car 3 22
d 1 4
Explanation
TableA has string based over milion rows, and it will be new added 100k rows/daily to tableA.
And also "string" column has no whitespaces
TableB has words based over milion rows,there is every letter and words in 1-2 languages
What i want to do
i want to split strings in TableA to its subwords, as you see in example; "creditcard" i search in TableB all words and try to find which words when comes together matches the string
What i did,and couldnt solve my question
i took the string and JOIN the TableB with INNER JOINS i made 2-3 times INNER JOINS because there can be 3word 4word strings too, and that WORKED!! but it takes too much time even doing it for 100-200 strings. Guess i want to do it for 100k/everyday???
Now what i try to do
i gave values to everyletter as you see above,
Took the strings one by one and from their including letters i count the value of strings..
And the same for the words too in TableB..
Now i have every string in TableA and everyword in TableB with their VALUES..
_
1- i will take the string,length and value of it (Exmple; creditcard - 10 - 85)
2- and make a search in TableB to find the possible words when they come together, with their SUM(length), and SUM(value) matches the strings length and value, and write theese possibilities to a new column.
At last even their sum of length and sum of values matches each other there can be some posibilities that doesnt match the whole string i will elliminate theese ones (Example; "doma-in" can be "moda-in" too and their lengths and values are same but not same words)
I dont know but,i guess with that value method i can solve the time proplem??? , or if there is another ways to do that, i will be gratefull taking your advices.
Thanks
You could try to find the solutions recursively by looking always at the next letter. For example for the word DOMAIN
D - no
DO - is a word!
M - no
MA - no
MAI - no
MAIN - is a word!
No more letters --> DO + MAIN
DOM - is a word!
A - no
AI - no
AIN - no
Finished without result
DOMA - no
DOMAI - no
DOMAIN - is a word!
No more letters --> DOMAIN

Printing out a binary search tree with slashes

http://pastebin.com/dN9a9xfs
That's my code to print out the elements of a binary search tree. The goal is to display it in level order, with slashes connecting the parent to each child. So for instance, the sequence 15 3 16 2 1 4 19 17 28 31 12 14 11 0 would display after execution as:
15
/ \
3 16
/ \ \
2 4 19
/ \ / \
1 12 17 28
/ / \ \
0 11 14 31
I've been working on it for a long time now, but I just can't seem to get the spacing/indentation right. I know I wrote the proper algorithm for displaying the nodes in the proper order, but the slashes are just off. This is the result of my code as is: http://imgur.com/sz8l1
I know I'm so close to the answer, since my display is not that far off from what I need, and I have a feeling it's a really simple solution, but for some reason I just seem to get it right.
I'm out of time for now, but here's a quick version. I did not read your code (don't know C++), so I don't know how close our solutions are.
I changed the output format slightly. Instead of / for the left node, I used | so I didn't have to worry about left spacing at all.
15
| \
3 16
|\ \
2 4 19
| \ | \
1 | 17 28
| | \
0 12 31
| \
11 14
Here's the code. I hope you're able to take what you need from it. There are definitely some Pythonisms which I hope map to what you're using. The main idea is to treat each row of numbers as a map of position to node object, and at each level, sort the map by key and print them to the console iteratively based on their assigned position. Then generate a new map with positions relative to their parents in the previous level. If there's a collision, generate a fake node to bump the real node down a line.
from collections import namedtuple
# simple node representation. sorry for the mess, but it does represent the
# tree example you gave.
Node = namedtuple('Node', ('label', 'left', 'right'))
def makenode(n, left=None, right=None):
return Node(str(n), left, right)
root = makenode(
15,
makenode(
3,
makenode(2, makenode(1, makenode(0))),
makenode(4, None, makenode(12, makenode(11), makenode(14)))),
makenode(16, None, makenode(19, makenode(17),
makenode(28, None, makenode(31)))))
# takes a dict of {line position: node} and returns a list of lines to print
def print_levels(print_items, lines=None):
if lines is None:
lines = []
if not print_items:
return lines
# working position - where we are in the line
pos = 0
# line of text containing node labels
new_nodes_line = []
# line of text containing slashes
new_slashes_line = []
# args for recursive call
next_items = {}
# sort dictionary by key and put them in a list of pairs of (position,
# node)
sorted_pos_and_node = [
(k, print_items[k]) for k in sorted(print_items.keys())]
for position, node in sorted_pos_and_node:
# add leading whitespace
while len(new_nodes_line) < position:
new_nodes_line.append(' ')
while len(new_slashes_line) < position:
new_slashes_line.append(' ')
# update working position
pos = position
# add node label to string, as separate characters so list length
# matches string length
new_nodes_line.extend(list(node.label))
# add left child if any
if node.left is not None:
# if we're close to overlapping another node, push that node down
# by adding a parent with label '|' which will make it look like a
# line dropping down
for collision in [pos - i for i in range(3)]:
if collision in next_items:
next_items[collision] = makenode(
'|', next_items[collision])
# add the slash and the node to the appropriate places
new_slashes_line.append('|')
next_items[position] = node.left
else:
new_slashes_line.append(' ')
# update working position
len_num = len(node.label)
pos += len_num
# add some more whitespace
while len(new_slashes_line) < position + len_num:
new_slashes_line.append(' ')
# and take care of the right child
if node.right is not None:
new_slashes_line.append('\\')
next_items[position + len_num + 1] = node.right
else:
new_slashes_line.append(' ')
# concatenate each line's components and append them to the list
lines.append(''.join(new_nodes_line))
lines.append(''.join(new_slashes_line))
# do it again!
return print_levels(next_items, lines)
lines = print_levels({0: root})
print '\n'.join(lines)

How to display the numeric numbers

Here's the content of my DataGrid
id
1
2
3A
4
5
6A
..
...
10V1
I want to get the max number from the datagrid. Then, I want to
display the next number (In this case: 11) in the textbox beside the grid
Expected Output
id
1
2
3A
4
5
6A
..
...
10V1
11
I tried the following code:
textbox1.text = gridList.Rows(gridlist.RowCount() - 1).Cells(1).Value + 1
It works if the previous row values is entirely numeric. However, if the value is alpahnumeric, I am getting the following error:
Conversion from string "10V1" to type 'Double' is not valid.
Can someone help me solve this problem? I am looking for a solution in VB.Net
You may want to look into Regex to do that (based on what I understand from your question)
Here's a related question on this.
Regex.Match will return the part of the string that will match the expression... In your case, you want the first number in your string (Try "^\d+" as your expression, it will find any serie of numbers at the beginning of your string). You can then convert the result string into an int and add 1 to it.
Hope this helps!
Edit: Here's more info on regex expressions.

Adding a number with zero's

Using VB.Net
When i add a the number with zeros means, it is showing exact result without zero's
For Example
Dim a, b, c as int32
a = 001
b = 5
c = a + b
a = 009
b = 13
c = a + b
Showing output as 6 instead of 006, 22 instead of 022
Expected output
006
022
How to do this.
Need vb.net code help
You need to store a number as a string if you want to store the exact number of zeros. Then addition won't work though.
If you just want to display the number with 3 digits, you can store it as an integer and format the result when you print it.
c.ToString("D3")
zero is nothing.. If you do a regular mathematical calculation of 001 + 5 the result is still 6. I would suggest you check out string padding.