Function doesn't execute inside loop - haxe

I'm making a simple terminal calculator but for some reason a function isn't executing inside a while loop but executes outside the loop.
Given this input: ((1 + 2) + (3 + 4))
It should output:10
But gets stuck in an infinite loop because it doesn't replace the innermost expressions with their result.
The function that doesn't execute is s.replace(basicOp, answer);
Here is a snippet of the problem:
public static function processInput(s:String):String
{
var result:Null<Float> = parseNumber(s);
if (result != null)
{
return Std.string(result);
}
var closeParPos:Int = 0;
var openParPos:Int = 0;
var basicOp:String;
var answer:String = "";
// ERROR HERE
while (Std.string(answer) != s)
{
closeParPos = s.indexOf(")");
openParPos = s.lastIndexOf("(", closeParPos);
basicOp = s.substring(openParPos, closeParPos + 1);
answer = processBasicOp(basicOp);
// This isn't executed
s.replace(basicOp, answer);
trace("Input: " + s + " basicOp: " + basicOp + " Answer: " + answer);
}
return (result == null)? "": Std.string(result);
}
All the code is here just run make test
The input syntax is: ([number] [operator] [number]) or ([operator] [number])
There must be a single space between number and operators.
There shouldn't be any space between numbers and parenthesis
Supported operations:
+ - / *
% (remainder),
div (quotient),
sqr (square),
sqroot (square root),
sin cos tan (in degrees, bugged)
fact (factorial)
It isn't completed yet, there may be other problems, but this problem prevents me from advancing.
Can someone help me find the solution?
Thank you.

I can't actually get this to run, but StringTools.replace() doesn't modify the string in-place.
Try changing s.replace(basicOp, answer); to s = s.replace(basicOp, answer);

Related

Optimal algorithm for this string decompression

I have been working on an exercise from google's dev tech guide. It is called Compression and Decompression you can check the following link to get the description of the problem Challenge Description.
Here is my code for the solution:
public static String decompressV2 (String string, int start, int times) {
String result = "";
for (int i = 0; i < times; i++) {
inner:
{
for (int j = start; j < string.length(); j++) {
if (isNumeric(string.substring(j, j + 1))) {
String num = string.substring(j, j + 1);
int times2 = Integer.parseInt(num);
String temp = decompressV2(string, j + 2, times2);
result = result + temp;
int next_j = find_next(string, j + 2);
j = next_j;
continue;
}
if (string.substring(j, j + 1).equals("]")) { // Si es un bracket cerrado
break inner;
}
result = result + string.substring(j,j+1);
}
}
}
return result;
}
public static int find_next(String string, int start) {
int count = 0;
for (int i = start; i < string.length(); i++) {
if (string.substring(i, i+1).equals("[")) {
count= count + 1;
}
if (string.substring(i, i +1).equals("]") && count> 0) {
count = count- 1;
continue;
}
if (string.substring(i, i +1).equals("]") && count== 0) {
return i;
}
}
return -111111;
}
I will explain a little bit about the inner workings of my approach. It is a basic solution involves use of simple recursion and loops.
So, let's start from the beggining with a simple decompression:
DevTech.decompressV2("2[3[a]b]", 0, 1);
As you can see, the 0 indicates that it has to iterate over the string at index 0, and the 1 indicates that the string has to be evaluated only once: 1[ 2[3[a]b] ]
The core here is that everytime you encounter a number you call the algorithm again(recursively) and continue where the string insides its brackets ends, that's the find_next function for.
When it finds a close brackets, the inner loop breaks, that's the way I choose to make the stop sign.
I think that would be the main idea behind the algorithm, if you read the code closely you'll get the full picture.
So here are some of my concerns about the way I've written the solution:
I could not find a more clean solution to tell the algorithm were to go next if it finds a number. So I kind of hardcoded it with the find_next function. Is there a way to do this more clean inside the decompress func ?
About performance, It wastes a lot of time by doing the same thing again, when you have a number bigger than 1 at the begging of a bracket.
I am relatively to programming so maybe this code also needs an improvement not in the idea, but in the ways It's written. So would be very grateful to get some suggestions.
This is the approach I figure out but I am sure there are a couple more, I could not think of anyone but It would be great if you could tell your ideas.
In the description it tells you some things that you should be awared of when developing the solutions. They are: handling non-repeated strings, handling repetitions inside, not doing the same job twice, not copying too much. Are these covered by my approach ?
And the last point It's about tets cases, I know that confidence is very important when developing solutions, and the best way to give confidence to an algorithm is test cases. I tried a few and they all worked as expected. But what techniques do you recommend for developing test cases. Are there any softwares?
So that would be all guys, I am new to the community so I am open to suggestions about the how to improve the quality of the question. Cheers!
Your solution involves a lot of string copying that really slows it down. Instead of returning strings that you concatenate, you should pass a StringBuilder into every call and append substrings onto that.
That means you can use your return value to indicate the position to continue scanning from.
You're also parsing repeated parts of the source string more than once.
My solution looks like this:
public static String decompress(String src)
{
StringBuilder dest = new StringBuilder();
_decomp2(dest, src, 0);
return dest.toString();
}
private static int _decomp2(StringBuilder dest, String src, int pos)
{
int num=0;
while(pos < src.length()) {
char c = src.charAt(pos++);
if (c == ']') {
break;
}
if (c>='0' && c<='9') {
num = num*10 + (c-'0');
} else if (c=='[') {
int startlen = dest.length();
pos = _decomp2(dest, src, pos);
if (num<1) {
// 0 repetitions -- delete it
dest.setLength(startlen);
} else {
// copy output num-1 times
int copyEnd = startlen + (num-1) * (dest.length()-startlen);
for (int i=startlen; i<copyEnd; ++i) {
dest.append(dest.charAt(i));
}
}
num=0;
} else {
// regular char
dest.append(c);
num=0;
}
}
return pos;
}
I would try to return a tuple that also contains the next index where decompression should continue from. Then we can have a recursion that concatenates the current part with the rest of the block in the current recursion depth.
Here's JavaScript code. It takes some thought to encapsulate the order of operations that reflects the rules.
function f(s, i=0){
if (i == s.length)
return ['', i];
// We might start with a multiplier
let m = '';
while (!isNaN(s[i]))
m = m + s[i++];
// If we have a multiplier, we'll
// also have a nested expression
if (s[i] == '['){
let result = '';
const [word, nextIdx] = f(s, i + 1);
for (let j=0; j<Number(m); j++)
result = result + word;
const [rest, end] = f(s, nextIdx);
return [result + rest, end]
}
// Otherwise, we may have a word,
let word = '';
while (isNaN(s[i]) && s[i] != ']' && i < s.length)
word = word + s[i++];
// followed by either the end of an expression
// or another multiplier
const [rest, end] = s[i] == ']' ? ['', i + 1] : f(s, i);
return [word + rest, end];
}
var strs = [
'2[3[a]b]',
'10[a]',
'3[abc]4[ab]c',
'2[2[a]g2[r]]'
];
for (const s of strs){
console.log(s);
console.log(JSON.stringify(f(s)));
console.log('');
}

check if string of parenthesis is balanced by doing certain operation on string

Given string of parenthesis we have to do 2 kinds of operation:
flip- changes the i-th parenthesis into the opposite one(left->right , right->left)
check- if the string is a balanced parenthesis expression
length of the string is at max 30000.
No of operation to be performed is at max
100000.
what kind of data structure should one use to solve this kind of problem?
Is Segment Tree a suitable data structure?
If yes how should one use it?
Example
string = ()((
no of operation=4
flip 4 {new string is ()()}
check {string is balanced}
flip 2{new string becomes ((()}
check{string is not balanced}
Let every ( be a +1 and every ) be a -1. Then a string of parenthesis is balanced iff sum for entire string is zero and sum for every range [0, k] is non-negative.
Let us define two functions for substring [i,j], sum and min. sum is obvious, and min(i,j) defined as minimum from all sum(i,k) where k <= j.
So
sum(i,k) = sum(i,j) + sum(j+1, k)
And
min(i,k) = MIN( min(i,j), sum(i,j) + min(j + 1, k) )
Now we can build a binary tree, where leafs are +1's and -1's, and root is an entire range [0, N-1]. For every node we keep min and sum.
Query for balance is obvious: we check for root.min >= 0 and root.sum == 0, so O(1).
Flip is done by updating leaf node and propagating changes to the root. No more than log(N)+1 nodes are updated, and every update is O(1), so O(logN).
A function that checks whether a string is balanced is easily made. Stepping through the string, increment a zero-initialized value if a "(" character is met and decrement it if ")" is met. If the result is 0 and it never went below 0 during the run, the string is balanced.
Flipping the parenthesis at nth position of the string is trivial.
Here's a simple implementation in javascript that flips a random character of the string in a loop and checks the validity of the resulting string after each flip.
http://jsbin.com/vagalijoca/edit?html,console
function checkbalanceness(str){
var res = 0;
for(i=0;i<str.length;i++) {
str[i]=="(" ? res++ : res--;
if (res < 0) break;
}
return res == 0;
}
function flipp(str, i){
if (i >= str.length) return str;
return str[i]=="(" ?
str.substr(0,i) + ")" + str.substr(i+1) :
str.substr(0,i) + "(" + str.substr(i+1) ;
}
//initial string
var curr = "()(())";
//operations to be executed
var ops = 40;
console.log('initial string: ' + curr + ' ' + checkbalanceness(curr));
console.log('operations: ' + ops);
console.log('start');
var ii;
var chartoflip;
for(ii=0;ii<ops;ii+=2){
chartoflip = (ii/2)%(curr.length);
curr = flipp(curr, chartoflip);
console.log((ii) + ' - flip char ' + chartoflip + ': ' + curr);
console.log((ii+1) + ' - checking ' + curr + ' ' + checkbalanceness(curr));
}
console.log('end');

Getting Depth of other objects Kinect

I'm a newbie in kinect programming, i am working on a ball tracking using kinect and opencv..we all know that kinect provides Depth data, and with the code below:
DepthImagePoint righthandDepthPoint =
sensor.CoordinateMapper.MapSkeletonPointToDepthPoint
(
me.Joints[JointType.HandRight].Position,
DepthImageFormat.Resolution640x480Fps30
);
double rightdepthmeters = (righthandDepthPoint.Depth);
using this, I am able to get the depth of a right hand, using the function MapSkeletonPointToDepthPoint() by specifing the jointtype..
Is it possible to get the depth of other objects by specifying in the image where?
given the coordinate..I want to get the depth of the object in that coordinate?
Pulling depth data from the Kinect SDK can be extracted from the DepthImagePixel structure.
The example code below loops through the entire DepthImageFrame to examine each of the pixels. If you have a specific coordinate you wish to look at, remove the for loop and set the x and y to a specific value.
// global variables
private const DepthImageFormat DepthFormat = DepthImageFormat.Resolution320x240Fps30;
private const ColorImageFormat ColorFormat = ColorImageFormat.RgbResolution640x480Fps30;
private DepthImagePixel[] depthPixels;
// defined in an initialization function
this.depthWidth = this.sensor.DepthStream.FrameWidth;
this.depthHeight = this.sensor.DepthStream.FrameHeight;
this.depthPixels = new DepthImagePixel[this.sensor.DepthStream.FramePixelDataLength];
private void SensorAllFramesReady(object sender, AllFramesReadyEventArgs e)
{
if (null == this.sensor)
return;
bool depthReceived = false;
using (DepthImageFrame depthFrame = e.OpenDepthImageFrame())
{
if (null != depthFrame)
{
// Copy the pixel data from the image to a temporary array
depthFrame.CopyDepthImagePixelDataTo(this.depthPixels);
depthReceived = true;
}
}
if (true == depthReceived)
{
// loop over each row and column of the depth
for (int y = 0; y < this.depthHeight; ++y)
{
for (int x = 0; x < this.depthWidth; ++x)
{
// calculate index into depth array
int depthIndex = x + (y * this.depthWidth);
// extract the given index
DepthImagePixel depthPixel = this.depthPixels[depthIndex];
Debug.WriteLine("Depth at [" + x + ", " + y + "] is: " + depthPixel.Depth);
}
}
}
}

Comparing #Now to a Date/Time field?

How do I compare #Now to a data / time value in a document? This is what I have
var ProjectActiveTo:NotesDateTime = doc.getItemValueDateTimeArray("ProjectActiveTo")[0];
var ProjectExpired;
var d1:Date = #Now();
if (d1 > ProjectActiveTo.toJavaDate())
{
dBar.info("Today: " + d1 + " > " + ProjectActiveTo.toJavaDate());
ProjectExpired = true;
}
else
{
dBar.info("Today: " + d1 + " < " + ProjectActiveTo.toJavaDate());
ProjectExpired = false;
}
But this always seems to return false. I printed out some diagnostic messages.
Today: 1/18/13 6:02 PM < 1/20/01 5:00 PM
Obviously today is greater than 1/20/01 but this is the result of my test. Why?
I have done some searching and saw that the compare member function might be used but it returns an error for me and compare is not in the intelisense (or whatever Lotus calls it) in the design editor.
Found this little snippet on line - it should point you in the right direction
var doc:NotesDocument = varRowView.getDocument();
var d:NotesDateTime = doc.getItemValue("BidDueDate")[0];
var t:NotesDateTime = session.createDateTime("Today");
if (d.timeDifference(t) > 0 ) {
return "Overdue";
}else{
return "";
}

Permission/Deny Mask in SharePoint

I have a question regarding SharePoint permission masks. In SharePoint it is possible to set the grant/deny rights using masks. Details are given the following article.
http://msdn.microsoft.com/en-us/library/dd304243(PROT.13).aspx
My question is when we have a permission/deny mask.
For example if you deny “ViewItem” permission using the central-admin, you will get 4611686844973976575 as the deny mask. This permission masks is computed by aping | to several individual permission masks.
So is it possible to extract individual permission masks which are used to calculate permission mask such as 4611686844973976575?
Thanks.
If you do a logical AND operation on a value such as 0x0000000000000001 for "ViewListItems" which is contained in the mask, then you will get the value itself (or 1). If you do a logical AND on a value not in that mask, like the "UseClientIntegration" value of 0x0000001000000000, then you will get a zero (0). This is something you can even test via the scientific mode of the Windows calculator app -- perhaps first converting the mask to hex, such as taking your example of 4611686844973976575 from base 10 to 400000C072040BFF in hex (base 16).
To extract all values from the mask, you would have to test the initial value against all possible values. If all known permission values are documented on that page, then the answer to your question is yes. I don't know which language you may want to accomplish this, but the basic idea in C# is:
bool CheckMask( long Mask, long TestPermission ) {
return (Mask && TestPermission) > 0;
}
long mask = 4611686844973976575;
const long ViewListItems = 0x0000000000000001;
bool HasPermission_ViewListItems = CheckMask(mask, ViewListItems);
// HasPermission_ViewListItems is true
const long UseClientIntegration = 0x0000001000000000;
bool HasPermission_UseClientIntegration = CheckMask(mask, UseClientIntegration);
// HasPermission_UseClientIntegration is false
I made this javascript sample thanks to #zanlok answer
I used JQuery, SPServices js (http://spservices.codeplex.com/)
and this link for the masks codes
http://msdn.microsoft.com/en-us/library/dd304243%28PROT.13%29.aspx
I Hope this helps you, I did this because I was needing it also, however it may also help others.
You need to replace the divid with the value of the control you want to place the html, and the LIST NAME HERE with the name of the list.
The script will spit everyone that has access to a list, and say if they can read, add, change and delete things. Hopes this helps you.
$('#divid').html('Working...').SPServices({
operation: "GetPermissionCollection",
objectName: 'LIST NAME HERE',
objectType: "List",
completefunc: function (xData, Status) {
var out = "<ul>";
$(xData.responseXML).find("Permission").each(function () {
if ($(this).attr("MemberIsUser") === "True") {
out += "<li>User: " + $(this).attr("UserLogin") + "</li>";
} else {
out += "<li>Group: " + $(this).attr("GroupName") + "</li>";
}
var readmask = 0x0000000000000001;
var addmask = 0x0000000000000002;
var editmask = 0x0000000000000004;
var deletemask = 0x0000000000000008;
out += "<li>Mask: " + $(this).attr("Mask") + "</li>";
var canread = readmask & $(this).attr("Mask").toString(16) > 0 ? "Yes" : "No";
var canadd = addmask & $(this).attr("Mask").toString(16) > 0 ? "Yes" : "No";
var canedit = editmask & $(this).attr("Mask").toString(16) > 0 ? "Yes" : "No";
var candelete = deletemask & $(this).attr("Mask").toString(16) > 0 ? "Yes" : "No";
out += "<li>Can Read: " + canread + "</li>";
out += "<li>Can Add: " + canadd + "</li>";
out += "<li>Can Edit: " + canedit + "</li>";
out += "<li>Can Delete: " + candelete + "</li>";
});
out += "</ul>";
$('divid').html(out);
}
});

Resources