• Hey, guest user. Hope you're enjoying NeoGAF! Have you considered registering for an account? Come join us and add your take to the daily discourse.

Programming |OT| C is better than C++! No, C++ is better than C

Kansoku

Member
What do you know about the pieces? Based on the example data you show here, some pieces are missing. For instance, the same disk that had the "0111" piece should have had a "111" piece as well, but there's no "111" piece or smaller pieces that would together form "111". Do we have only one piece from each disk?
Do you know how many disks there were?
Do you know what the length of the result is?

Each string was split in exactly two substrings? Your example doesn't make sense in that case (the '11' string specifically).

If each string is split in two substrings:

-length of the string = shortest_substring.length + longest_substring.length

Okay, he gave us a random sequence generator, that would break it into pieces. I took another look at it, and it seems that it indeed give both pieces (Ex: 1011 and 110 for 1011110, as well as giving 10 and 11110, etc.) It was probably a typo =P

But everything is still random. I can't control the length of the final string, neither how many pieces will be there (I know now that it will always be even tho). and there's no way of me knowing whether a piece goes in front or in the back of another one (The code gave me both 1 / 010010 and 100101 / 0 for 0100101).
 

Hylian7

Member
Got some code snippets of my problem I mentioned. Here's an issue I was having with doing System.nanoTime()

Code:
long start = System.nanoTime();
		long end = System.nanoTime() + (time * 1000000000);
		int countdown = (int)time;
		while(System.nanoTime() != end) {
			if(end - System.nanoTime() % 1000000000 == 0) {
				System.out.println(countdown);
				countdown--;
			}
		}
		System.out.println("Time is up");

Lets say that time = 30, what I want to get is this.

Code:
30
29
28
27
26
...(so on and so fourth)
1
0
Time is up

Instead I get nothing for 30 seconds and then just "Time is up". Do I have something mathmatecially wrong or what? I'm just not seeing it. Am I blind?

Edit: I'M AN IDIOT!

Code:
long start = System.nanoTime();
		long end = System.nanoTime() + (time * 1000000000);
		int countdown = (int)time;
		while(System.nanoTime() < end) {
			if((end - System.nanoTime()) % 1000000000 == 0) {
				System.out.println(countdown);
				countdown--;
			}
		}
		System.out.println("Time is up");
 

Water

Member
But everything is still random. I can't control the length of the final string, neither how many pieces will be there (I know now that it will always be even tho).
Well, knowing all the pieces are there and that there are exactly two pieces per drive clears things up.

You have to divide all the strings into pairs such that every pair combines into the same string; that string will be the result string. You could do that by just trying all possible string pairings; if performance is an issue, there are some fairly obvious optimizations, such as only trying pairings with correct length.

It turns out you do actually know the amount of disks: it's half the amount of strings you get. And the length of the result string is the sum of the lengths of all strings divided by the amount of disks.
 
Got some code snippets of my problem I mentioned. Here's an issue I was having with doing System.nanoTime()


Lets say that time = 30, what I want to get is this.

Code:
30
29
28
27
26
...(so on and so fourth)
1
0
Time is up

Instead I get nothing for 30 seconds and then just "Time is up". Do I have something mathmatecially wrong or what? I'm just not seeing it. Am I blind?

Edit: I'M AN IDIOT!
Yeah, I tried out your code and for me it never finished. Here's a simple Timer class I made earlier.
https://gist.github.com/GyrosOfWar/e73523ee56d6d02a8250
 

Kansoku

Member
Well, knowing all the pieces are there and that there are exactly two pieces per drive clears things up.

You have to divide all the strings into pairs such that every pair combines into the same string; that string will be the result string. You could do that by just trying all possible string pairings; if performance is an issue, there are some fairly obvious optimizations, such as only trying pairings with correct length.

It turns out you do actually know the amount of disks: it's half the amount of strings you get. And the length of the result string is the sum of the lengths of all strings divided by the amount of disks.

Hmm, yeah. Now the troublesome part is that I can't be certain of the end result.
I was toying with the generator and saw a small one with 4 pieces:
000
00010
10010
010

I was thinking that if I separate them and try every possible outcome, only pairing 1 with 3 and 2 with 4 would produce the same result: 1+3 == 2+4, but to do that it would very costly, especially since there's sequences with way more than 50 pieces. So I wonder if there's a more optimized way of checking that.
 

poweld

Member
The bottom one should work, at least it worked for me.

nice job. there's a lesson to be learned here: when you're watching some value until it hits a certain threshold, and it is only increasing or decreasing, it's almost always safer to check for >= <= (or < >) rather than ==
 

tokkun

Member
Hmm, yeah. Now the troublesome part is that I can't be certain of the end result.
I was toying with the generator and saw a small one with 4 pieces:
000
00010
10010
010

I was thinking that if I separate them and try every possible outcome, only pairing 1 with 3 and 2 with 4 would produce the same result: 1+3 == 2+4, but to do that it would very costly, especially since there's sequences with way more than 50 pieces. So I wonder if there's a more optimized way of checking that.

Here are a few things to consider that may help you to come up with a more efficient approach:

1. Because the original string is split into two pieces, every piece you get will either be a prefix or a suffix of the original string.
2. If you compare two strings and both of them are suffix pieces, then the smaller one will be a suffix of the larger one.
3. Conversely, if you compare two prefixes, the shorter one will be a prefix of the longer one.
4. On the other hand if one of them is a suffix and the other is a prefix, there is no guarantee (the shorter one might be a prefix of the longer one, a suffix, both, or neither).
5. At least half of the pieces will be prefixes of the original string and at least half will be suffixes.
6. Exactly half will be 'true' prefixes (i.e. they came from the beginning of the original string prior to being split) and half will be true suffixes.
7. A piece cannot be both a true prefix and a true suffix (unless it is the un-split original string).

Now try applying some of that logic to the 4-entry set you gave. Here are all the possible 3-character prefixes that appear in the pieces, with their frequency:

000 (2)
100 (1)
010 (1)

And all the suffixes:

000 (1)
010 (3)

How might you use that information to determine the original string? When you figure that out, think about any special cases you might encounter (hint: What would happen if you had an original string that was all zeroes?).
 
I'm curious, has anybody here ever been asked in an interview what their favorite text editor is? It was the first question I was asked at one earlier this week. I thought it was an odd (and maybe irrelevant) question at first, but a friend of mine made a good point. They don't care what your favorite text editor is (unless it's Notepad) they just care that you have an opinion.

(For the record, I said Sublime Text and vim.)
 

Water

Member
I'm curious, has anybody here ever been asked in an interview what their favorite text editor is? It was the first question I was asked at one earlier this week. I thought it was an odd (and maybe irrelevant) question at first, but a friend of mine made a good point. They don't care what your favorite text editor is (unless it's Notepad) they just care that you have an opinion.
Good interviewers start with softballs to get the interviewee over any initial anxiety they might have. That's what this sounds like. I like the choice of question because while it's dead easy to answer, the answers would also show a bit about the interviewee's attitudes regarding selecting, learning and modifying tools.

Obviously, any answer that doesn't include vim should fail the candidate.
 
Good interviewers start with softballs to get the interviewee over any initial anxiety they might have. That's what this sounds like. I like the choice of question because while it's dead easy to answer, the answers would also show a bit about the interviewee's attitudes regarding selecting, learning and modifying tools.

Obviously, any answer that doesn't include vim should fail the candidate.

I would say it's actually a horrible interview question in this case, b/c people have such religious beliefs about these kind of things that it might affect them more than a candidate botching an actually relevant question.

Yea, if a candidate starts ranting about studies about how modal editing is bad, and emacs is great, he is out
 

Kansoku

Member
Here are a few things to consider that may help you to come up with a more efficient approach:

1. Because the original string is split into two pieces, every piece you get will either be a prefix or a suffix of the original string.
2. If you compare two strings and both of them are suffix pieces, then the smaller one will be a suffix of the larger one.
3. Conversely, if you compare two prefixes, the shorter one will be a prefix of the longer one.
4. On the other hand if one of them is a suffix and the other is a prefix, there is no guarantee (the shorter one might be a prefix of the longer one, a suffix, both, or neither).
5. At least half of the pieces will be prefixes of the original string and at least half will be suffixes.
6. Exactly half will be 'true' prefixes (i.e. they came from the beginning of the original string prior to being split) and half will be true suffixes.
7. A piece cannot be both a true prefix and a true suffix (unless it is the un-split original string).

Now try applying some of that logic to the 4-entry set you gave. Here are all the possible 3-character prefixes that appear in the pieces, with their frequency:

000 (2)
100 (1)
010 (1)

And all the suffixes:

000 (1)
010 (3)

How might you use that information to determine the original string? When you figure that out, think about any special cases you might encounter (hint: What would happen if you had an original string that was all zeroes?).

Hmm, I see. That gave me some ideas. Thanks for everyone who helped. :)
 

Granadier

Is currently on Stage 1: Denial regarding the service game future
(For the record, I said Sublime Text and vim.)

What are the differences/advantages to using a text editor like Sublime or vim over an IDE when writing programs?
It seems that a lot of experienced developers swear by using a text editor instead.

I'm very new, and so far I just utilize IntelliJ or another IDE for writing all my programs.
 
What are the differences/advantages to using a text editor like Sublime or vim over an IDE when writing programs?
It seems that a lot of experienced developers swear by using a text editor instead.

I'm very new, and so far I just utilize IntelliJ or another IDE for writing all my programs.

A lot of people have strong opinions both way on this. For me, it comes down to the fact that I feel IDE's are a bit bloated, and I prefer using a text editor in addition to other external tools. Text editors like vim and Sublime are REALLY good at just being text editors, whereas IDE's try be jack of all trades. (However, there are so many plugins for Sublime and vim that give you a lot of extra functionality if you want it. If not, the base products are great for editing.)

There are also plenty of benefits to using an IDE as well, especially for large projects. With something like vim or Sublime, you have a better way to edit text at the expense of having to learn some more external tools rather than having it built in. (Debuggers, etc.)

Good interviewers start with softballs to get the interviewee over any initial anxiety they might have. That's what this sounds like. I like the choice of question because while it's dead easy to answer, the answers would also show a bit about the interviewee's attitudes regarding selecting, learning and modifying tools.

Obviously, any answer that doesn't include vim should fail the candidate.

That's a good point. It was a good way to put me at ease at the start of the interview with an easy question, and something that the interviewer and I could discuss in order to get to know each other a bit. We talked a bit about what I like about Sublime and in what situations I would use that or vim.
 
What are the differences/advantages to using a text editor like Sublime or vim over an IDE when writing programs?
It seems that a lot of experienced developers swear by using a text editor instead.

I'm very new, and so far I just utilize IntelliJ or another IDE for writing all my programs.

It depends on multiple things.

1) What is the scale of project? Larger projects are a little bit easier to manage in an IDE.
2) What area of application development do you work in? IDEs can be great for WYSIWYG development so they make great tools for front-end development.
3) How important is it to have a plethora of tools immediately available? IDEs often come with functionality to do just about every development task. However, it also means they are memory intensive.
4) What kind of source control do you use? No IDE supports all forms of source control. If you end up having to swap between command line and IDE constantly, it's better to just go with vim.
5) What platform are you targeting for release? If you want to develop only windows applications, you should be using Visual Studio period.
6) Do you write make files, mavens tasks, ant task manager etc? If you do, you are pretty much free to do as you wish. If, however, you rely on IDE projects for project build settings (I'd suggest you stop), you don't really have much of a choice.
 

tokkun

Member
What are the differences/advantages to using a text editor like Sublime or vim over an IDE when writing programs?
It seems that a lot of experienced developers swear by using a text editor instead.

I'm very new, and so far I just utilize IntelliJ or another IDE for writing all my programs.

I have worked at a few places where we were not allowed to have copies of source code on our local machines for security reasons. Text editors have several advantages in that scenario:

-vim is pre-installed on almost any Linux system, and set up can be as simple as copying your .vimrc. If I need to edit the code from multiple different desktops or laptops, it's easy.
-vim can be used through an SSH session, even without X forwarding.
-vim peforms much better than a full GUI editor when used over a remote connection because it uses much less bandwidth.
 

Magni

Member
What are the differences/advantages to using a text editor like Sublime or vim over an IDE when writing programs?
It seems that a lot of experienced developers swear by using a text editor instead.

I'm very new, and so far I just utilize IntelliJ or another IDE for writing all my programs.

I prefer text editors to IDEs in general, but I'll use Xcode or Visual Studio for iOS/WP development. For Rails/Django or any frontend stuff, I'll use Sublime. And vim inside a terminal if I need to make quick changes on staging (never on production of course). It's all about what you're most comfortable with in the end.
 
So I'm using a ruby on rails to make a simple site but is their anyway I can learn css so the website doesn't look like ass?

Probably the quickest way is to use a CSS framework, like Bootstrap. That's really the easiest way to get a decent looking site up there quickly. It's really helpful if you don't have a lot of background in visual design (like me). If you just go with the default Bootstrap stylings, for example, you'll end up with a nice and responsive site, even if it does look a bit generic.
 

Granadier

Is currently on Stage 1: Denial regarding the service game future

Water

Member
Thanks for the well thought out answers guys. That was wonderful to read.
It's something I have thought about in the past when reading through peoples design processes and such, but I never understood the reasoning.
At the moment I don't think I am comfortable enough with the code to swap to a text editor, but I will continue working towards it.
The advantages and disadvantages of IDEs vs good text editors depend strongly on the languages, frameworks and tools you are working with. If the language syntax is bloated, if the language structure forces you to jump around a lot, if the language isn't very expressive so you need a large variety of standard library functionality to get things done, that kind of stuff gives an advantage to an IDE that has functionality for that specific environment to help you deal with all of that.

For instance, practically no one codes Java without an IDE, whereas Python, Ruby, Haskell etc. are typically written in just a text editor.
 

Granadier

Is currently on Stage 1: Denial regarding the service game future
The advantages and disadvantages of IDEs vs good text editors depend strongly on the languages, frameworks and tools you are working with. If the language syntax is bloated, if the language structure forces you to jump around a lot, if the language isn't very expressive so you need a large variety of standard library functionality to get things done, that kind of stuff gives an advantage to an IDE that has functionality for that specific environment to help you deal with all of that.

For instance, practically no one codes Java without an IDE, whereas Python, Ruby, Haskell etc. are typically written in just a text editor.

Makes sense that I have been using one than since Java has been pretty much the only language I have been using.
 

Kansoku

Member
I...I d-don't use a IDE with Java >.>

By the way, is there any good Java debugger that I can use it standalone, and possibly integrate it with Notepad++?
 

Jokab

Member
I...I d-don't use a IDE with Java >.>

By the way, is there any good Java debugger that I can use it standalone, and possibly integrate it with Notepad++?

Can I ask how come? Personally I couldn't see myself coding Java without Eclipse/IntelliJ because of all the connected classes and modules in a project, standard library functions that I need as well as external ones, referencing variables/functions from other modules etc. To me it seems like a pain to write anything that is more than one file in just a text editor.
 
For instance, practically no one codes Java without an IDE, whereas Python, Ruby, Haskell etc. are typically written in just a text editor.

That's not really true at all on either end. Whether I use an IDE or not depends on the task at hand, I'm almost assuredly going to use an IDE if I'm developing a business management application regardless of language especially if it's a complete turn-key solution.

Edit: On the other hand, I'm not going to use an IDE for a 2-3 file program that pulls down a file, parses it, and writes it out to a database or an internal file format.
 

Kansoku

Member
Can I ask how come? Personally I couldn't see myself coding Java without Eclipse/IntelliJ because of all the connected classes and modules in a project, standard library functions that I need as well as external ones, referencing variables/functions from other modules etc. To me it seems like a pain to write anything that is more than one file in just a text editor.

Well first because my projects aren't big enough, and are usually one file (since I have to deliver them trough my university's website and they only accept small files), and two because what I need, Notepad+++ offers me (except debugging, hence my question)

Also, there was this one class that my teacher forced us to use linux and vim, so compared to that, N++ is god sent.
 

harSon

Banned
I'm trying to figure out why the variable roll in my program outputs with the value 2686712:
Code:
#include <iostream>
#include <iomanip>
#include <time.h>
#include <stdlib.h>

using namespace std;

int roll2Dice(int&);

int main()
{
    int total = 0, roll;
    srand(time(0));

    cout << setw(10) << "Roll" << setw(10) << "Total" << endl;
    cout << setw(10) << "----" << setw(10) << "-----" << endl;
    while (total < 25)
    {
        roll = roll2Dice(total);
        cout << setw(10) << roll << setw(10) << total << endl;
    }
    return 0;
}

int roll2Dice(int& sum) {

    int dice1 = rand()% (6 - 1 + 1) + 1;
    int dice2 = rand()% (6 - 1 + 1) + 1;

    int add = dice1 + dice2;

    if (add % 2 == 0) {
        sum = sum + add;
    }
    else {
        sum = sum - add;
    }
}

Any ideas?
 

usea

Member
You never assign roll to anything.
Code:
int total = 0, roll;
This declares a variable roll, but it doesn't assign it any value.

Code:
roll = roll2Dice(total);
This looks like it assigns roll the value returned by the function roll2Dice. But looking at the code for roll2Dice, it doesn't return anything. So I have no idea what happens there. I don't really know that language well enough. It's sad the language doesn't say that should be a compiler error.
 
Code:
roll = roll2Dice(total);
This looks like it assigns roll the value returned by the function roll2Dice. But looking at the code for roll2Dice, it doesn't return anything. So I have no idea what happens there. I don't really know that language well enough. It's sad the language doesn't say that should be a compiler error.

It returns whatever random value is on the stack for the return.
 

harSon

Banned
You never assign roll to anything.
Code:
int total = 0, roll;
This declares a variable roll, but it doesn't assign it any value.

Code:
roll = roll2Dice(total);
This looks like it assigns roll the value returned by the function roll2Dice. But looking at the code for roll2Dice, it doesn't return anything. So I have no idea what happens there. I don't really know that language well enough. It's sad the language doesn't say that should be a compiler error.

Roll is assigned the return value of the function. While the variable total in the Main function takes on the value of its reference variable in the roll2Dice function. You were right though, I wasn't actually returning anything within the function, so no value was ever being passed to roll.

Thanks for the help though!
 

cyborg009

Banned
Probably the quickest way is to use a CSS framework, like Bootstrap. That's really the easiest way to get a decent looking site up there quickly. It's really helpful if you don't have a lot of background in visual design (like me). If you just go with the default Bootstrap stylings, for example, you'll end up with a nice and responsive site, even if it does look a bit generic.

Thanks I just notice I did have bootstrap

'bootstrap-sass', '2.3.2.0'

But I'm having troubles getting my desired layout table do you know any good tutorials to understand the syntax?
 

neemmss

Member
Hey guys, I want to create a info app for my school club. It's going to have updates for the latest happenings, information, meetings, etc. I am trying to make it available for iOS, Android, and WP phones, but I have a couple of questions.

What is the best way to have the sections and pages of the app editable, on let's say my computer, and have it update automatically on the apps? How about if a user updates it on an iOS device? How can I have it automatically input the new or changed information onto all the other platforms? Is MySQL the best option for this?

I know that the front-end of all these apps are going to be different, but I want the back-end information to be stored and saved in an organized manner and editable anywhere (ex. OneNote).
 

wario

Member
Thanks I just notice I did have bootstrap

'bootstrap-sass', '2.3.2.0'

But I'm having troubles getting my desired layout table do you know any good tutorials to understand the syntax?

i found the official bootstrap documentation to be really informative. the part pertaining to grid layout is here.

also, any reason you're not using 3.0 or above?
 

Hylian7

Member
Maybe it's just late and I'm getting stupider, but what am I missing here about this switch case in my Java program.

Code:
public void draft() {

		for (int i = 0; i < order.length; i++) {
			setTurn(order, i);
		}
		done = true;
	}
	
	public void setTurn(int[] order, int i) {
		switch(order[i]) {
		case 0:
			System.out.println("It ran");
			turn = true;
			type = false;
			time();
			break;
		case 1:
			turn = false;
			type = false;
			time();
			break;
		case 2:
			turn = true;
			type = true;
			time();
			break;
		case 3:
			turn = false;
			type = true;
			time();
			break;
		}
	}

Basically what should happen is when I hit something, it should only be printing "It ran" once until I click something else. Am I hardcore derping here or what? Instead it just prints all the instances of it the second time.
 

usea

Member
Maybe it's just late and I'm getting stupider, but what am I missing here about this switch case in my Java program.

Basically what should happen is when I hit something, it should only be printing "It ran" once until I click something else. Am I hardcore derping here or what? Instead it just prints all the instances of it the second time.

I don't think there's enough information in the code to see what's wrong. You're getting Case 0 every time? Well, what's in the array? Are all the elements 0? Print order before the case statement, or better yet put a breakpoint and look at the contents of order.

Also I don't know where order comes from or where it's scoped, but it's not being changed inside of time() is it?

Also it seems weird to me to pass the array and an index to setTurn. Why not just call setTurn(order) and have it only take the int? Anyway that's a minor complaint.
 

Hylian7

Member
I don't think there's enough information in the code to see what's wrong. You're getting Case 0 every time? Well, what's in the array? Are all the elements 0? Print order before the case statement, or better yet put a breakpoint and look at the contents of order.

Also it seems weird to me to pass the array and an index to setTurn. Why not just call setTurn(order) and have it only take the int? Anyway that's a minor complaint.


Because it's starting to get late and I sometimes write stupid things in my code and not think about them.

Anyway I did try what you mentioned above. Here's what's in the array, and it does print this every time:

Code:
0
1
0
1
2
3
3
2
0
1
0
1
3
2
3
2
1
0
3
2

Also time() has nothing to do with what this does and it doesn't even touch order[] at all.
 

usea

Member
Because it's starting to get late and I sometimes write stupid things in my code and not think about them.
We all do. In fact I'm doing it right now in another window! wheee

Anyway I did try what you mentioned above. Here's what's in the array, and it does print this every time:

Also time() has nothing to do with what this does and it doesn't even touch order[] at all.
I copied your code and made only minor changes and it works fine. Add a breakpoint and check the value of everything as you step through it. Or add a ton of print statements everywhere if debugging isn't convenient. order[] probably doesn't have what you think.

edit: actually I think I'm misunderstanding your problem. What's wrong, exactly?
Basically what should happen is when I hit something, it should only be printing "It ran" once until I click something else. Am I hardcore derping here or what? Instead it just prints all the instances of it the second time.
What does "I hit something" mean? What are you clicking? Your code has nothing to do with clicks or hitting. Your code goes through the entire order array every time draft() is called. It should print "It ran" once for each 0 in order[], which you've said is like 5 times.
 

Hylian7

Member
We all do. In fact I'm doing it right now in another window! wheee


I copied your code and made only minor changes and it works fine. Add a breakpoint and check the value of everything as you step through it. Or add a ton of print statements everywhere if debugging isn't convenient. order[] probably doesn't have what you think.

edit: actually I think I'm misunderstanding your problem. What's wrong, exactly?
What does "I hit something" mean? What are you clicking? Your code has nothing to do with clicks or hitting. Your code goes through the entire order array every time draft() is called. It should print "It ran" once for each 0 in order[], which you've said is like 5 times.

Nothing, I'm an idiot and realized the problem was somewhere else completely. Thanks though.
 

hateradio

The Most Dangerous Yes Man
Since there's a discussion on text editors, does anyone know of a good plugin for Notepad++ that detects JavaScript errors related to custom objects and missing members, in particular methods.

Eg:

Code:
var gaf = {
	neo: true,
	gif: true,
	ban: function () {
		this.doesNotExist(); // Something that would give a warning about this missing method
	}
};
 

Magni

Member
Hey guys, I want to create a info app for my school club. It's going to have updates for the latest happenings, information, meetings, etc. I am trying to make it available for iOS, Android, and WP phones, but I have a couple of questions.

What is the best way to have the sections and pages of the app editable, on let's say my computer, and have it update automatically on the apps? How about if a user updates it on an iOS device? How can I have it automatically input the new or changed information onto all the other platforms? Is MySQL the best option for this?

I know that the front-end of all these apps are going to be different, but I want the back-end information to be stored and saved in an organized manner and editable anywhere (ex. OneNote).

You want a server with some kind of persistent storage (like MySQL), with an API that your different clients (the iOS, Android, and Windows Phone apps) will call. You want to create all this (the backend and three clients) by yourself?
 

Nesotenso

Member
I was hoping to get some help or advise from people experienced with network programming.

I am taking a network architecture course this semester and the project this semester has us writing code in c/c++ or python. I wanted help with choosing a project topic. Some possible topic suggested by the professor include implementing transport layer protocols like UDP/TCP and doing comparisions with network parameters like delay, throughput etc. The class also gives us access to emulab, https://www.emulab.net to test our network topology.

some examples the professor gave include, UDP-based reliable data transfer protocol design and implementation, performance comparison of UDT and 2-3 high speed TCP versions etc.

I was hoping someone who has experience with network programming could suggest something keeping in mind while I do have experience with C/C++ and python it is not extensive.
 

Linkhero1

Member
I'm sort of stuck working with text fields in javascript. I want to limit the number a user can enter to three places before a decimal point and two places after and I'm not sure how to do that. I've tried using regexp but I'm a bit lost since I've never used regexp before. Can someone point the right way?

Edit:

I tried being clever about it but obviously it didn't work. Here's what I've tried so far.

Code:
function doThis(obj) {
     var value = obj.value.toString().indexOf(".");

     if (value != -1) {
           obj.maxLength = value + 3; // increases maxLength according to the position of the decimal point. e.g. if 12.00, value is 2, maxLength would be 2+3.
     } else {
           obj.maxLength = 4;
     }

}

The problem is that the user can still enter numbers before the decimal and it will cause this to fail entirely.
 

Tristam

Member
I'm sort of stuck working with text fields in javascript. I want to limit the number a user can enter to three places before a decimal point and two places after and I'm not sure how to do that. I've tried using regexp but I'm a bit lost since I've never used regexp before. Can someone point the right way?

The regex pattern would basically be: ^\d{1,3}$|^\d{1,3}\.\d{1,2}$

This makes a couple of assumptions that you didn't explicitly state, but to break it down:

  • ^ -- a boundary marker that says "the character following this must be at the start of the expression"
  • \d{1,3} -- a digit character (\d) occurs at least one time and at most three times
  • $ -- a boundary marker that says "the character preceding this must be at the end of the expression"
  • | -- logical OR part of expression. This is an assumption that I made -- that a user can enter just a whole number without anything after a decimal... OR, if they *do* enter a decimal, then abide by the pattern to the right of the |
  • ^ -- see above
  • \d{1,3} -- see above
  • \. -- a decimal point (it has a \ in front of it because . is a special character and must be escaped)
  • \d{1,2} -- a digit character that occurs at least once and at most twice
  • $ -- see above

EDITED expression to include boundary (^ and $) characters. Feel free to run tests by changing mystr:

Code:
var re = new RegExp(/^\d{1,3}$|^\d{1,3}\.\d{1,2}$/);
var mystr = "212.93";
if (re.test(mystr) == true) {
	document.write("matches!");
} else {
	document.write("doesn't match!");
}

So 123, 3.45, 123.45, 1.2, etc. will match, but 1234.5, 123.456, 1., etc. will not match.

Mozilla Developer Network has a good writeup on Regex in JavaScript: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

It's more of a handy rule reference rather than tutorial, but I think the best tutorial is playing with the rules yourself.

I tried being clever about it but obviously it didn't work. Here's what I've tried so far.

.....

The problem is that the user can still enter numbers before the decimal and it will cause this to fail entirely.

Edit: If you go the non-regex route, IMO you should be separately enforcing a maxLength restriction on both sides of the decimal point.
 

Linkhero1

Member
The regex pattern would basically be: \d{1,3}|d{1,3}\.\d{1,2}

This makes a couple of assumptions that you didn't explicitly state, but to break it down:

  • \d{1,3} -- a digit character (\d) occurs at least one time and at most three times
  • | -- logical OR part of expression. This is an assumption that I made -- that a user can enter just a whole number without anything after a decimal... OR, if they *do* enter a decimal, then abide by the pattern to the right of the |
  • \d{1,3} -- see above
  • \. -- a decimal point (it has a \ in front of it because . is a special character and must be escaped)
  • \d{1,2} -- a digit character that occurs at least once and at most twice

So 123, 3.45, 123.45, 1.2, etc. will match, but 1234.5, 123.456, 1., etc. will not match.

Mozilla Developer Network has a good writeup on Regex in JavaScript: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

It's more of a handy rule reference rather than tutorial, but I think the best tutorial is playing with the rules yourself.



Edit: If you go the non-regex route, IMO you should be separately enforcing a maxLength restriction on both sides of the decimal point.
Thanks for the quick reply. I'm trying to use the Regex solution but it's not working in my case. How would I enforce maxLength on both sides?
 

Tristam

Member
Thanks for the quick reply. I'm trying to use the Regex solution but it's not working in my case. How would I enforce maxLength on both sides?

Sorry, just realized my Regex doesn't enforce any boundaries, so, for example, asdf123.45asdf would match, as would 999123.45999. I'll toy with it a bit more to ensure my boundaries are correct.

But to enforce maxLength on both sides, just do a string split on the decimal (assuming that the user does enter a decimal -- if not, you can just use a conditional to ensure that they've entered at most 3 digit characters and at least one), and then test whether the length of characters on the left (i.e., the array component at index 0 that resulted from the string split) exceeds 3 and whether the length on the right (i.e., the array component at index 1 that resulted from the string split) exceeds 2. If so, return an error / don't process the request / whatever you would like to do.

EDIT: I just edited my initial reply; I tested the regex and everything seems to check out.
 

Linkhero1

Member
It works. Another solution which is very crappy compared to the regex

Code:
var value = obj.value;
			 
 if (value > 999.99) {
     obj.value = 999.99;
 } else if (value < 0.00) {
     obj.value = 0.00;
 } else {
     obj.value = parseFloat(value).toFixed(2);
 }

basically just check the value itself and see if it exceeds the range I want for my text field. I'll add javascript client-side validation messages as well but I think I'm going to use the regex instead since it's a lot cleaner.
 
that feel when you add something in an abstract class, that then requires you to handle that one exception in about 40 device classes methods.

i wonder if eclipse refactoring could do something, but probably not worth the risk.
 
Top Bottom