use a binary tree to encode infix arithmetic expressions on integers - function

This is a question from aws educate. I have been thinking about this for a long time and I am not really getting anywhere.
You want to use a binary tree to encode infix arithmetic expressions on integers. Operations are addition and multiplication
Draw a picture of what the tree looks like.
Write a class definition.
Write an evaluate() member function.
How would you make your evaluate() iterative instead of recursive
If I could get an explanation that would be fine or some example too

Illustration - binary tree to encode infix arithmetic expressions on integers
As you can see, the leafs are the value (or literal) and the other nodes contain arithmetic operators (+, - , /, *)
Some Code - recusion
In Java, you could use the recursion to solve this problem (under the condition that the tree's height is not to big)
public class Main {
public static void main(String[] args) {
// op1=(1 + 2)
Node op1 = new Node(1, "+", 2);
System.out.println("op1="+op1.evaluate()); // op1=3
// op2=(1 + 2) + 3
Node op2 = new Node(op1, "+", 3);
System.out.println("op2="+op2.evaluate()); // op2=6
// op3=(4 * 5)
Node op3 = new Node(4, "*", 5);
System.out.println("op3="+op3.evaluate()); // op3=20
// op4=((1+2)+3)*(4*5)
Node op4 = new Node(op2, "*", op3);
System.out.println("op4="+op4.evaluate()); // op4=120
}
}
class Node {
private Node left;
private Node right;
private String operatorOrLiteral;
public Node(String value){
this.operatorOrLiteral = value;
}
public Node(Node left, String operation, Node right){
this.operatorOrLiteral = operation;
this.left = left;
this.right = right;
}
public Node(int literal1, String operation, int literal2){
this(new Node(Integer.toString(literal1)), operation, new Node(Integer.toString(literal2)));
}
public Node(Node left, String operation, int literal2) {
this(left, operation, new Node(Integer.toString(literal2)));
}
public Node(int literal1, String operation, Node right) {
this(new Node(Integer.toString(literal1)), operation, right);
}
public int evaluate(){
if(isLiteral()) {
return Integer.parseInt(operatorOrLiteral);
}
switch (operatorOrLiteral) {
case "*": return left.evaluate() * right.evaluate();
case "/": return left.evaluate() / right.evaluate();
case "-": return left.evaluate() - right.evaluate();
case "+": return left.evaluate() + right.evaluate();
default: throw new IllegalArgumentException(operatorOrLiteral + " is not recognised");
}
}
private boolean isLiteral() {
return left == null && right == null;
}
public String toString() {
if(isLiteral()) {
return operatorOrLiteral;
}
return "(" + left.toString() + operatorOrLiteral + right.toString() + ")";
}
}
Some Code - iterative
Or as #David Sanders as mentioned, you can work with tree traversal.

The question is asking you to write a tree class which can represent expressions like "2 + 2" or "3 * 1 + 5". So the class represents a tree which has a root and internal nodes which correspond with applications of the "*" or "+" operators. The leaf nodes will correspond to integer values like "5" or "2" which are being operated upon. A typical evaluation function which would produce a result from such a tree might be recursive. They're asking you to also consider how you can arrive at a result iteratively. Such an iterative approach might involve adding nodes successively to a queue or stack data structure and popping them off one-by-one to be handled somehow.
See here: https://en.wikipedia.org/wiki/Tree_traversal

Related

Is this a good case for the Strategy Pattern

I have the following inputs:
A CSV File
An array of grammar rules. The grammar rules are
basically metadata that tells me what which each column datatype
should be.
The output would return back to me a list of records that had any errors. So if column should be a date but I'm given the wrong format. I would return those rows.
The csv file would be something like this:
first_name,last_name,dob,age,
john,doe,2001/05/02
mary,jane,1968/04/01
Metadata:
column:first_name
type:string
column:dob
type:date
I was wondering if the strategy pattern would be the right choice. I was thinking of injecting the proper grammar (metadata) depending upon the file. I have multiple files I want to validate.
This problem needs the Validation Handlers (for your grammar rule). Looking at lower complexity level and expected extensions, I do not feel the need of any specific design pattern. I would suggest following simple OO approach. Alternatively depending upon expected dynamic behavior, COR can be incorporated by putting each Concrete Handler in a chain (COR). Pass each token in a chain so as to give opportunity to handlers in a chain till it gets handled.
public class Extractor {
public static void main(String[] args) {
// PREPARE TEMP_MAP_HANDLERS<Type,Handler>
Map<String, Handler> handlers = new HashMap<>();
handlers.put("FIRST_NAME",new NAMEHandler());
handlers.put("LAST_NAME",new NAMEHandler());
handlers.put("DOB",new DOBHandler());
handlers.put("AGE",new AGEHandler());
// READ THE HEADER
String header = "first_name,last_name,dob,age";// SAMPLE READ HEADER
// PREPARE LOOKUP<COL_INDEX, TYPE_HANDLER>
Map<Integer, Handler> metaHandlers = new HashMap<>();
String[] headerTokens = header.split(",");
for (int i = 0; i < headerTokens.length; i++) {
metaHandlers.put(i, handlers.get(headerTokens[i].toUpperCase()));
}
// DONE WITH TEMP HANDLER LOOKUP
// READ ACTUAL ROWS
// FOR EACH ROW IN FILE
String row = "joh*n,doe,2001/05/02";
String[] rowTokens = row.split(",");
for (int i = 0; i < rowTokens.length;i++) {
System.out.println(rowTokens[i]);
Handler handler = metaHandlers.get(i);
if (!handler.validate(rowTokens[i])){
// REPORT WRONG DATA
System.out.println("Wrong Token" + rowTokens[i]);
}
}
}
}
abstract class Handler {
abstract boolean validate (String field);
}
class NAMEHandler extends Handler{
#Override
boolean validate(String field) {
// Arbitrary rule - name should not contain *
return !field.contains("*");
}
}
class DOBHandler extends Handler{
#Override
boolean validate(String field) {
// Arbitrary rule - contains /
return field.contains("/");
}
}
class AGEHandler extends Handler{
#Override
boolean validate(String field) {
// TODO validate AGE
return true;
}
}

Return multiple values from function

Is there a way to return several values in a function return statement (other than returning an object) like we can do in Go (or some other languages)?
For example, in Go we can do:
func vals() (int, int) {
return 3, 7
}
Can this be done in Dart? Something like this:
int, String foo() {
return 42, "foobar";
}
Dart doesn't support multiple return values.
You can return an array,
List foo() {
return [42, "foobar"];
}
or if you want the values be typed use a Tuple class like the package https://pub.dartlang.org/packages/tuple provides.
See also either for a way to return a value or an error.
I'd like to add that one of the main use-cases for multiple return values in Go is error handling which Dart handle's in its own way with Exceptions and failed promises.
Of course this leaves a few other use-cases, so let's see how code looks when using explicit tuples:
import 'package:tuple/tuple.dart';
Tuple2<int, String> demo() {
return new Tuple2(42, "life is good");
}
void main() {
final result = demo();
if (result.item1 > 20) {
print(result.item2);
}
}
Not quite as concise, but it's clean and expressive code. What I like most about it is that it doesn't need to change much once your quick experimental project really takes off and you start adding features and need to add more structure to keep on top of things.
class FormatResult {
bool changed;
String result;
FormatResult(this.changed, this.result);
}
FormatResult powerFormatter(String text) {
bool changed = false;
String result = text;
// secret implementation magic
// ...
return new FormatResult(changed, result);
}
void main() {
String draftCode = "print('Hello World.');";
final reformatted = powerFormatter(draftCode);
if (reformatted.changed) {
// some expensive operation involving servers in the cloud.
}
}
So, yes, it's not much of an improvement over Java, but it works, it is clear, and reasonably efficient for building UIs. And I really like how I can quickly hack things together (sometimes starting on DartPad in a break at work) and then add structure later when I know that the project will live on and grow.
Create a class:
import 'dart:core';
class Tuple<T1, T2> {
final T1 item1;
final T2 item2;
Tuple({
this.item1,
this.item2,
});
factory Tuple.fromJson(Map<String, dynamic> json) {
return Tuple(
item1: json['item1'],
item2: json['item2'],
);
}
}
Call it however you want!
Tuple<double, double>(i1, i2);
or
Tuple<double, double>.fromJson(jsonData);
You can create a class to return multiple values
Ej:
class NewClass {
final int number;
final String text;
NewClass(this.number, this.text);
}
Function that generates the values:
NewClass buildValues() {
return NewClass(42, 'foobar');
}
Print:
void printValues() {
print('${this.buildValues().number} ${this.buildValues().text}');
// 42 foobar
}
The proper way to return multiple values would be to store those values in a class, whether your own custom class or a Tuple. However, defining a separate class for every function is very inconvenient, and using Tuples can be error-prone since the members won't have meaningful names.
Another (admittedly gross and not very Dart-istic) approach is try to mimic the output-parameter approach typically used by C and C++. For example:
class OutputParameter<T> {
T value;
OutputParameter(this.value);
}
void foo(
OutputParameter<int> intOut,
OutputParameter<String>? optionalStringOut,
) {
intOut.value = 42;
optionalStringOut?.value = 'foobar';
}
void main() {
var theInt = OutputParameter(0);
var theString = OutputParameter('');
foo(theInt, theString);
print(theInt.value); // Prints: 42
print(theString.value); // Prints: foobar
}
It certainly can be a bit inconvenient for callers to have to use variable.value everywhere, but in some cases it might be worth the trade-off.
Dart is finalizing records, a fancier tuple essentially.
Should be in a stable release a month from the time of writing.
I'll try to update, it's already available with experiments flags.
you can use dartz package for Returning multiple data types
https://www.youtube.com/watch?v=8yMXUC4W1cc&t=110s
you can use Set<Object> for returning multiple values,
Set<object> foo() {
return {'my string',0}
}
print(foo().first) //prints 'my string'
print(foo().last) //prints 0
In this type of situation in Dart, an easy solution could return a list then accessing the returned list as per your requirement. You can access the specific value by the index or the whole list by a simple for loop.
List func() {
return [false, 30, "Ashraful"];
}
void main() {
final list = func();
// to access specific list item
var item = list[2];
// to check runtime type
print(item.runtimeType);
// to access the whole list
for(int i=0; i<list.length; i++) {
print(list[i]);
}
}

Graphhopper - calculating travel time

I'm developing a project using Graphhopper core to calculate optimal routes. I incorporated some real traffic data by modifying speed assigned to edges and calculated optimal routes in two ways: the "default" way and the way, which considers traffic.
Now, I try to compare those routes and investigate how travel time changes. What I would like to do is to calculate travel time on the optimal route, which was found using default speed assigned to edges, but travel time should be calculated using custom speed values (those, which take into account real traffic). In other words, is it possible to use Graphhopper to calculate travel time on a specific route (not optimal one)?
A solution, which came to my mind, is to implement custom FlagEncoder (as described here), extend Path class and use them to calculate travel time using speed values, which considers traffic. However, maybe you, guys, know simpler way to achieve this.
I finally managed to solve the problem so I share my solution.
To store custom speed as an extra value I extended class CarFlagEncoder.
public class CustomCarFlagEncoder extends CarFlagEncoder {
public static final int CUSTOM_SPEED_KEY = 12345;
private EncodedDoubleValue customSpeedEncoder;
public CustomCarFlagEncoder() {
super();
}
public CustomCarFlagEncoder(PMap properties) {
super(properties);
}
public CustomCarFlagEncoder(String propertiesStr) {
super(propertiesStr);
}
public CustomCarFlagEncoder(int speedBits, double speedFactor, int maxTurnCosts) {
super(speedBits, speedFactor, maxTurnCosts);
}
#Override
public int defineWayBits(int index, int shift) {
shift = super.defineWayBits(index, shift);
customSpeedEncoder = new EncodedDoubleValue("Custom speed", shift, speedBits, speedFactor,
defaultSpeedMap.get("secondary"), maxPossibleSpeed);
shift += customSpeedEncoder.getBits();
return shift;
}
#Override
public double getDouble(long flags, int key) {
switch (key) {
case CUSTOM_SPEED_KEY:
return customSpeedEncoder.getDoubleValue(flags);
default:
return super.getDouble(flags, key);
}
}
#Override
public long setDouble(long flags, int key, double value) {
switch (key) {
case CUSTOM_SPEED_KEY:
if (value < 0 || Double.isNaN(value))
throw new IllegalArgumentException("Speed cannot be negative or NaN: " + value
+ ", flags:" + BitUtil.LITTLE.toBitString(flags));
if (value > getMaxSpeed())
value = getMaxSpeed();
return customSpeedEncoder.setDoubleValue(flags, value);
default:
return super.setDouble(flags, key, value);
}
}
#Override
public String toString() {
return CustomEncodingManager.CUSTOM_CAR;
}
}
In order to be able to use custom FlagEncoder, I created CustomEncodingManager, which extends EncodingManager and handles CustomCarFlagEncoder.
public class CustomEncodingManager extends EncodingManager {
public static final String CUSTOM_CAR = "custom_car";
public CustomEncodingManager(String flagEncodersStr) {
this(flagEncodersStr, 4);
}
public CustomEncodingManager(String flagEncodersStr, int bytesForFlags )
{
this(parseEncoderString(flagEncodersStr), bytesForFlags);
}
public CustomEncodingManager(FlagEncoder... flagEncoders) {
super(flagEncoders);
}
public CustomEncodingManager(List<? extends FlagEncoder> flagEncoders) {
super(flagEncoders);
}
public CustomEncodingManager(List<? extends FlagEncoder> flagEncoders, int bytesForEdgeFlags) {
super(flagEncoders, bytesForEdgeFlags);
}
static List<FlagEncoder> parseEncoderString(String encoderList )
{
if (encoderList.contains(":"))
throw new IllegalArgumentException("EncodingManager does no longer use reflection instantiate encoders directly.");
String[] entries = encoderList.split(",");
List<FlagEncoder> resultEncoders = new ArrayList<FlagEncoder>();
for (String entry : entries)
{
entry = entry.trim().toLowerCase();
if (entry.isEmpty())
continue;
String entryVal = "";
if (entry.contains("|"))
{
entryVal = entry;
entry = entry.split("\\|")[0];
}
PMap configuration = new PMap(entryVal);
AbstractFlagEncoder fe;
if (entry.equals(CAR))
fe = new CarFlagEncoder(configuration);
else if (entry.equals(BIKE))
fe = new BikeFlagEncoder(configuration);
else if (entry.equals(BIKE2))
fe = new Bike2WeightFlagEncoder(configuration);
else if (entry.equals(RACINGBIKE))
fe = new RacingBikeFlagEncoder(configuration);
else if (entry.equals(MOUNTAINBIKE))
fe = new MountainBikeFlagEncoder(configuration);
else if (entry.equals(FOOT))
fe = new FootFlagEncoder(configuration);
else if (entry.equals(MOTORCYCLE))
fe = new MotorcycleFlagEncoder(configuration);
else if (entry.equals(CUSTOM_CAR)) {
fe = new CustomCarFlagEncoder(configuration);
}
else
throw new IllegalArgumentException("entry in encoder list not supported " + entry);
if (configuration.has("version"))
{
if (fe.getVersion() != configuration.getInt("version", -1))
{
throw new IllegalArgumentException("Encoder " + entry + " was used in version "
+ configuration.getLong("version", -1) + ", but current version is " + fe.getVersion());
}
}
resultEncoders.add(fe);
}
return resultEncoders;
}
}
Then, I set the custom EncodingManager to GraphHopper object hopper.setEncodingManager(new CustomEncodingManager(CustomEncodingManager.CUSTOM_CAR));
I assign custom speed to an edge as an extra value edge.setFlags(customCarEncoder.setDouble(existingFlags, CustomCarFlagEncoder.CUSTOM_SPEED_KEY,
newSpeed));
Finally, to use custom speed while calculating travel time, I slightly modified method clacMillis form class Path from package com.graphhoper.routing.
protected long calcMillis( double distance, long flags, boolean revert )
{
if (revert && !encoder.isBackward(flags)
|| !revert && !encoder.isForward(flags))
throw new IllegalStateException("Calculating time should not require to read speed from edge in wrong direction. "
+ "Reverse:" + revert + ", fwd:" + encoder.isForward(flags) + ", bwd:" + encoder.isBackward(flags));
double speed = revert ? encoder.getReverseSpeed(flags) : encoder.getSpeed(flags);
double customSpeed = encoder.getDouble(flags, 12345);
if (customSpeed > 0) {
speed = customSpeed;
}
if (Double.isInfinite(speed) || Double.isNaN(speed) || speed < 0)
throw new IllegalStateException("Invalid speed stored in edge! " + speed);
if (speed == 0)
throw new IllegalStateException("Speed cannot be 0 for unblocked edge, use access properties to mark edge blocked! Should only occur for shortest path calculation. See #242.");
return (long) (distance * 3600 / speed);
}

appropriate term for a predicate that has state

A predicate (an object that is a boolean-valued function which tests its input for a condition) is generally assumed to be stateless.
What's the most appropriate name for an object which has a testing function with state?
e.g. in Java, the CountTrigger class below returns true only on the Nth time it is tested against a value that matches a desired value, and false otherwise.
interface QuasiPredicate<T> // what should this be renamed to?
{
public boolean test(T value);
}
class CountTrigger<T> implements QuasiPredicate<T>
{
// for simplicity, ignore synchronization + null-value issues
private int remainingTriggers = 0;
final private T testValue;
public CountTrigger(T testValue, int count)
{
this.remainingTriggers = count;
this.testValue = testValue;
}
#Override public boolean test(T value)
{
if (!this.testValue.equals(value))
return false;
if (this.remainingTriggers == 0)
return false;
if (--this.remainingTriggers == 0)
return true;
}
}
Considering it's an interface and interfaces are implemented and not extended then I don't see the problem in your object implementing a predicate.
If you're going to put public CountTrigger(T testValue, int count) in the interface as well then maybe you need a different name. Perhaps IFiniteRule or another suitable synonym. Maybe ask at https://english.stackexchange.com/ ;-)

AS3: Optimizing Object Memory Size

I have have a class that I wrote, and it seems bigger than it should be. It doesn't extend anything, and has very little going on - or so I thought - but each one is taking up just under 100k100 bytes ( thanks back2dos ). I guess that I don't have a very good understanding of what really affects how much memory an object takes up in AS3.
If anyone can point me to some reading on the subject that might be helpful, or perhaps explain some insight into how to think about this, that would be awesome.
I would like to keep a LOT of these objects in memory - and I thought I could until now, but at this size I'm going to have to create them or use an object pooling technique of some kind.
Thanks for the assistance.
Edit: Although I've got this in order, I'm keeping the code I posted here for completeness. The class has been heavily modified from the original version. Values that were referencing other files have been made static as to allow the code to run for someone else ( in theory hehehe... ).
Although my situation is sorted out, I'll give the answer to a good reference for information on classes and memory.
In this case the class has 15 variables. I'm only using a single String and a bunch of ints, Numbers, and Booleans with some references to more of the same in globally available XML data. It also imports Point for the constructor, though no points are stored. In testing, even without the global XML references or Point class it's still around a ~84k each. There are getters for 7 of the variables and a couple methods in addition to the constructor. All of which are less than 20 lines ( and I have a very sparse coding style ).
The class mentioned for reference, but feel free to generalize:
package
{
public class AObject
{
private var _counter:int;
private var _frames:int;
private var _speed:int;
private var _currentState:String;
private var _currentFrame:int;
private var _offset:int;
private var _endFrame:int;
private var _type:int;
private var _object:int;
private var _state:int;
private var _x:Number;
private var _y:Number;
private var _w:int;
private var _h:int;
private var _update:Boolean;
public function AObject( targetX : int, targetY : int, state : int, object : int, type : int )
{
_x = targetX;
_y = targetY;
_type = type;
_object = object;
_state = state;
_counter = 0;
_w = 32;
_h = 32
_update = true;
setState( state );
}
public function setState( state:int ) : void
{
_currentState = "bob";
var frameCounter : int = 0;
var stateCounter : int = state - 1;
while ( state > 0 )
{
frameCounter += 4;
--stateCounter;
}
_offset = frameCounter;
_currentFrame = _offset;
_speed = 10;
_frames = 4;
_endFrame = _offset + _frames - 1;
}
public function get state() : int
{
return _state;
}
public function animate() : Boolean
{
if ( count() )
{
if( _currentFrame < _endFrame )
{
++_currentFrame;
}
else
{
_currentFrame = _offset;
}
_speed = 10;
return true;
}
else
{
return false;
}
}
private var adder: Number = 0;
private function count():Boolean
{
_counter++;
if ( _counter == _speed )
{
_counter = 0;
return true;
}
else
{
return false;
}
}
public function get x():int
{
return _x;
}
public function get y():int
{
return _y;
}
public function get type():int
{
return _type;
}
public function get object():int
{
return _object;
}
public function get currentFrame():int
{
return _currentFrame;
}
public function get w():int
{
return _w;
}
public function get h():int
{
return _h;
}
}
}
i am amazed, this compiles at all ... when i try to compile it with the flex SDK, it creates an enormous collision with the built-in class Object, which is the base class of any class, making my trace output overflow ...
other than that, this is an infinite loop if you pass a value for state bigger than 0
while ( state > 0 )
{
frameCounter += 4;
--stateCounter;
}
but it seems really strange these objects are so big ... after renaming and taking care not to pass in 0 for the state, i ran a test:
package {
import flash.display.Sprite;
import flash.sampler.getSize;
import flash.system.System;
public class Main extends Sprite {
public function Main():void {
const count:int = 100000;
var start:uint = System.totalMemory;
var a:Array = [];
for (var i:int = 0; i < count; i++) {
a.push(new MyObject(1, 2, 0, 4, 5));
}
var mem:uint = System.totalMemory - start - getSize(a);
trace("total of "+mem+" B for "+count+" objects, aprox. avg. size per object: "+(mem/count));
}
}
}
it yields:
total of 10982744 B for 100000 objects, aprox. avg. size per object: 109.82744
so that's quite ok ... i think the actual size should be 4 (for the bool) + 4 * 11 (for the ints) + 4 (for the reference to the string) + 8 * 3 (for the three floats (you have the adder somewhere over the count) + 8 for an empty class (reference to the traits objects + something else), giving you a total of 88 bytes ... which is, what you get, if you getSize the object ... please note however, that getSize will only give you the size of the object itself (as calculated here) ignoring the size of what strings or other objects your object references ...
so yeah, apart from that name you definitely should change, the problem must be somewhere else ...
greetz
back2dos
If you really want to save on space, you can fake shorts by using unsigned integers, and using upper/lower bits for one thing or another.
ints are 4 bytes by nature, you can reuse that int on anything less than 2^8.
width height
0xFFFF + 0xFFFF
offset endframe
0xFFFF + 0xFFFF
This though gets ugly when you want to write anything or read anything, as to write width or height you'd have to:
writing:
size = (width & 0x0000FFFF) << 16 | (height & 0x0000FFFF);
reading:
get width():uint { return (size & 0xFFFF0000) >> 16 };
That's ugly. Since you're using getters anyways, and assuming computation speed is not an issue, you could use internal byte arrays which could give you even more granularity for how you want to store your information. Assuming your strings are more than 4 bytes, makes more sense to use a number rather than a string.
Also, I believe you will actually get some memory increase by declaring the class as final, as I believe final functions get placed into the traits object, rather than