• 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

Tamanon

Banned
Python has been pretty good for me for an absolute beginner. Just starting to dive into the Object-Oriented side of things(classes/methods/objects and whatnot) but it helps that a lot of the cleanup is done natively.

I've started messing around with Ruby also, and it seems a really clean but effective language thus far. CodeAcademy has a decent Python tutorial, and Udacity has an alright class for it.
 
Sorry for the late reply! I forgot I posted in this thread.

I'm primarily using ImpactJS right now, I picked it up about a year ago and learned OOP and alot of other programming principles through that. I have to say it's really exciting to be working on games in a browser that I can show to anyone very easily.

Right now I'm I picked up a book from amazon to further my knowledge of HTML5 gamedev without using a framework like Impact.

I've made two games so far with Impact, a platformer/shooter that I'm going to be working on for a while, and a small vertical shooter I made for a contest.
 
A friend gave me a past exam and I still need some work on Big O and best case. Can anyone tell me if I'm correct? He got this problem all wrong so I don't know the correct answer.

This code sorts to linked lists and builds a new sorted linked list that contains all the items of both linked lists.
Code:
Node merge(Node L1, Node L2){
if (L1==null) { return L2;}
if(L2==null){ return L1;}
if (L1.data< L2.data){
Node temp=new Node(L1.data, null); temp.next=merge(L1.next, L2); return temp;
}
else{ Node temp=new Node(L2.data, null); temp.next=merge(L1, L2.next); return temp;}}
What is the worst case number of int-to-int comparison? Explain
Worst case would be n+m-1. Since both are sorted, you simply increment by one on the list if one is larger/smaller. When we reach the end, we don't have to traverse one of the list and just simply add it in the end. So n+m-1, or just O(n+m)

The best case of int-to-int comparison?
So would this just be O(m,n)? If m is smaller than n, and then n is smaller than m, it keep interchanging so O(m, n)?
 

usea

Member
A friend gave me a past exam and I still need some work on Big O and best case. Can anyone tell me if I'm correct? He got this problem all wrong so I don't know the correct answer.

This code sorts to linked lists and builds a new sorted linked list that contains all the items of both linked lists.
Are the two input lists sorted already? I have to assume so.

The code is difficult to read. There's no indenting and some of the lines have multiple statements on them, which is confusing. You're trying to communicate the code to other people, but the format is making it ineffective. Try this:
Code:
Node merge(Node L1, Node L2)
{
    if (L1 == null) {
        return L2;
    }
    if (L2 == null) {
        return L1;
    }
    if (L1.data < L2.data) {
        Node temp = new Node(L1.data, null);
        temp.next = merge(L1.next, L2);
        return temp;
    } else {
        Node temp = new Node(L2.data, null);
        temp.next = merge(L1, L2.next);
        return temp;
    }
}

What is the worst case number of int-to-int comparison? Explain
Worst case would be n+m-1. Since both are sorted, you simply increment by one on the list if one is larger/smaller. When we reach the end, we don't have to traverse one of the list and just simply add it in the end. So n+m-1, or just O(n+m)

The best case of int-to-int comparison?
So would this just be O(m,n)? If m is smaller than n, and then n is smaller than m, it keep interchanging so O(m, n)?
For the best case, I think it's if all the numbers in list A are smaller than the numbers in list B. In that case, it compares the first node in B with each node in A, adding all the elements in A to the output. Then it compares each element in B with null, adding the elements in B to the output. So the best case is two lists where one is entirely less than the other. The number of int comparisons is equal to the length of the shorter list.

It's kind of a dumb question though because I don't see why int-to-int comparisons should count while checking for null shouldn't.
 

ciridesu

Member
Hey guys. Just a quick inquire: how important is R in math/stat/similar fields? Just wondering how it compares to using Excel in practice
 

Onemic

Member
Well, I ordered the teach yourself C++ in an hour a day off Amazon, based primarily on the large number of very good reviews the book seems to be getting relative to other C++ books aimed at those new to programming.

Just a question, how important does math become when learning a language like C++?
 

Kalnos

Banned
Just a question, how important does math become when learning a language like C++?

It's not very important in learning a language but it's extremely important depending on what you want to do. Making a game engine? Math is going to be really important. Making an application that logs phone calls? Math probably won't be that important. Although, when considering things like performance and complexity math is important.

If nothing else I think it's good to take math courses to help your problem solving ability. Things like Discrete Math are going to be way more important than things like Calculus, from my experience.
 

Onemic

Member
It's not very important in learning a language but it's extremely important depending on what you want to do. Making a game engine? Math is going to be really important. Making an application that logs phone calls? Math probably won't be that important. Although, when considering things like performance and complexity math is important.

If nothing else I think it's good to take math courses to help your problem solving ability. Things like Discrete Math are going to be way more important than things like Calculus, from my experience.

I was thinking about going back and learning math again starting through precalculus and working my way into calculus. So I'm guessing you wouldn't recommend that? What would be the best way to work my way up into discrete mathematics if that's more useful than calculus? And why exactly is discrete mathematics more useful than calculus?

I haven't done mathematics since grade 12(I'm 23 now) so what would be the best approach for me?
 

Kalnos

Banned
I was thinking about going back and learning math again starting through precalculus and working my way into calculus. So I'm guessing you wouldn't recommend that? What would be the best way to work my way up into discrete mathematics if that's more useful than calculus? And why exactly is discrete mathematics more useful than calculus?

I haven't done mathematics since grade 12(I'm 23 now) so what would be the best approach for me?

If you can learn both, then by all means I would learn both. Calculus certainly has its uses and I would 100% brush up on the pre-calc. Discrete Math has many more practical applications for the realm of Computer Science and I guarantee you that a lot of the information that you find in other CS topics can be traced back to a Discrete Math course.

Do you *need* this information to learn a programming language? No. Will you need it eventually? Probably.
 
Are the two input lists sorted already? I have to assume so.

The code is difficult to read. There's no indenting and some of the lines have multiple statements on them, which is confusing. You're trying to communicate the code to other people, but the format is making it ineffective. Try this:
Code:
Node merge(Node L1, Node L2)
{
    if (L1 == null) {
        return L2;
    }
    if (L2 == null) {
        return L1;
    }
    if (L1.data < L2.data) {
        Node temp = new Node(L1.data, null);
        temp.next = merge(L1.next, L2);
        return temp;
    } else {
        Node temp = new Node(L2.data, null);
        temp.next = merge(L1, L2.next);
        return temp;
    }
}


For the best case, I think it's if all the numbers in list A are smaller than the numbers in list B. In that case, it compares the first node in B with each node in A, adding all the elements in A to the output. Then it compares each element in B with null, adding the elements in B to the output. So the best case is two lists where one is entirely less than the other. The number of int comparisons is equal to the length of the shorter list.

It's kind of a dumb question though because I don't see why int-to-int comparisons should count while checking for null shouldn't.
Yeah, it says it's shorted. Sorry, I was copying the format directly from the exam.

I thought so too, it beingO(n or m) but then I looked at a similiar problem set and it said n,mO(n,m)...which I didn't really get what that means. But thanks, I'll go with what you said since that was my initial thought.

If it was checking for null, would that affect it? Wouldn't it just be the same, O(n or m) since you wouldn't really care about what ever comes after n(like m+n-1, the -1 isn't that important)?

Edit: But I just hope this stuff isn't worth much on the exam. lol Hopefully it's something simple but I doubt it...
 
Matlab folk in here? How do you organize larger projects with many functions? Do you use subfolders or packages or just dump everything in one folder?

The simplest answer is to stop using matlab and to use a non-idiotic scientific programming language like numpy/scipy or perhaps even sage or julia. :)

But to answer your question, I tend to organize things by folders and use addpath (you can tweak it to be recursive, which may help). Matlab's handling of namespace/path/packages/toolboxes is beyond atrocious, but that's the best I could find. I also have a sharedlib directory for a bunch of functions which I use all the time for a lot of projects which i add to the path at startup.

Seriously, learn python/scipy/numpy (use canopy if you like IDEs), you'll thank me later. :p
Unless you're stuck with matlab for horrible reasons (simulink, interface with shitty equipment which will only talk to matlab, a sadistic boss).
 
Well, I ordered the teach yourself C++ in an hour a day off Amazon, based primarily on the large number of very good reviews the book seems to be getting relative to other C++ books aimed at those new to programming.

Just a question, how important does math become when learning a language like C++?
I hope that book works out for you. Just know that when you get frustrated with a concept it's OK. Take a small break, dive back in or ask for help if needed.

I know you've already gotten an answer for the math question but I'll also echo that math isn't necessary to learn a language. However, when you want to start utilizing that skill for something challenging or useful, math (and logic) become more important.
 

Feep

Banned
I have a random question.

I'm opening up a cross-process pipe...which you can basically just thing of as a stream...to send data to and fro.

I use a Read function, as detailed below:

Code:
public string ReadString()
{
    int len = 0;

    len = ioStream.ReadByte() * 256;
    len += ioStream.ReadByte();
    byte[] inBuffer = new byte[len];

    ioStream.Read(inBuffer, 0, len);

    return streamEncoding.GetString(inBuffer);
}

Which works, but apparently ReadByte() is a blocking call if the stream is empty, and only proceeds if something enters the stream.

All I want to do is NOT block if there's nothing in the stream, but there doesn't actually seem to be an easy way to do this. There's no way to see what's in the stream, and none of the read functionality (including those found in the .NET class StreamReader) seem to help, here.

Anyone with any ideas? I guess I can try putting it in a separate thread, or something, but that seems silly.
 

usea

Member
StreamReader has .Peek and NetworkStream has a DataAvailable flag. I assume you've seen these and they don't apply?

Stream and StreamReader have a ReadAsync method if you're using .net 4.5. This is the best solution I think.

If it's not built in, I think your next-best option is to use another thread (or a thread abstraction). Unfortunately the behavior will be "do something with what's eventually in the stream" instead of "tell me if something is in the stream." Even in .net 4 with Tasks it's not so bad.

There's lots of ways to do the multithreaded version. Callbacks, events, etc. Sorry if you know this already.

Short version:
Code:
Task.Factory.StartNew(() =>
{
    var incomingData = ReadString();
    //do something with the string (call something, trigger an event, etc)
    //it'll happen on another thread
    //(technically it will happen "concurrently" according to the task scheduler and not necessarily a different OS thread)
});

more complete version:
Code:
var pipeTask = Task.Factory.StartNew(() =>
{
    var incomingData = ReadString();
    //something
}).ContinueWith((t) =>
{
    //boilerplate exception handling.
    //if you don't handle an exception in a task
    //it brings down the whole app domain
    t.Exception.Handle((ex) =>
    {
        //handle exception ex
        return true;
    });
}, TaskContinuationOptions.OnlyOnFaulted);

If you want to wait on the task to finish, you can keep the pipeTask variable around and call its .Wait method. Otherwise just fire and forget. If you Wait on a task, exceptions during its execution bubble up to the Wait call.
 

Feep

Banned
Stream and StreamReader have a ReadAsync method if you're using .net 4.5. This is the best solution I think.
Huh. Even though I have .NET 4.5 installed, the libraries seem to be backdated to 4.0...ReadASync is not available in my environment. I tried manually locating 4.5 .dll's (Program Files(x86)/Reference Assemblies/Microsoft/Framework/.NETFramework/4.5) but there doesn't seem to be anything new. Any ideas?

The problem with the "do something eventually" approach is that I'm trying to use a cross-process pipe in a bidirectional fashion. However, even if I use another thread (and I did end up trying this, about an hour ago), having a blocking read call on the Stream prevents me from sending data through the other way. Since data could come through in either direction at any time, I need to have a way to not block.

I also tried setting up two streams based on one pipe (same problem), and two separate pipes, but I couldn't get that to work at all, oddly.
 

usea

Member
Huh. Even though I have .NET 4.5 installed, the libraries seem to be backdated to 4.0...ReadASync is not available in my environment. I tried manually locating 4.5 .dll's (Program Files(x86)/Reference Assemblies/Microsoft/Framework/.NETFramework/4.5) but there doesn't seem to be anything new. Any ideas?
Hm. If you're using visual studio -- or anything which uses a csproj file / msbuild --, maybe the project's target framework isn't 4.5 (project properties > application > target framework). If something else like Unity, I have no idea how that works.

The problem with the "do something eventually" approach is that I'm trying to use a cross-process pipe in a bidirectional fashion. However, even if I use another thread (and I did end up trying this, about an hour ago), having a blocking read call on the Stream prevents me from sending data through the other way. Since data could come through in either direction at any time, I need to have a way to not block.
Ohhhhh ok. Well the ReadAsync probably isn't going to solve the problem then. It's still going to call a blocking Read eventually, just with a fancy state machine in front of it so your code doesn't wait on it. If there's no flag available for when data is available to be read, and you have to use the same pipe for both directions, your only other option may be establishing a communications protocol. So that the sides would know when to expect data, or when it's free to send data. :\

Sorry, I know very little about the topic.
 

Feep

Banned
Hm. If you're using visual studio -- or anything which uses a csproj file / msbuild --, maybe the project's target framework isn't 4.5 (project properties > application > target framework). If something else like Unity, I have no idea how that works.

Ohhhhh ok. Well the ReadAsync probably isn't going to solve the problem then. It's still going to call a blocking Read eventually, just with a fancy state machine in front of it so your code doesn't wait on it. If there's no flag available for when data is available to be read, and you have to use the same pipe for both directions, your only other option may be establishing a communications protocol. So that the sides would know when to expect data, or when it's free to send data. :\

Sorry, I know very little about the topic.
I managed to get it working...Visual Studio 2010 simply doesn't support the .NET 4.5 framework. Silly me.

But by get it working, I mean "able to use .ReadASync()", which as you surmised, does not help in any way.

If anyone has any ideas, definitely let me know...but I'm gonna have to try tearing everything down and starting again, I think. = (
 

usea

Member
I managed to get it working...Visual Studio 2010 simply doesn't support the .NET 4.5 framework. Silly me.

But by get it working, I mean "able to use .ReadASync()", which as you surmised, does not help in any way.

If anyone has any ideas, definitely let me know...but I'm gonna have to try tearing everything down and starting again, I think. = (
What happens when you try to send data over the pipe when there's data waiting to be read from it (from the other side)? Do you lose that data, or does the send fail, or does it work just fine?

If that doesn't work, you're going to have problems no matter what. Because even if you could peek at the stream to see if it was empty, that doesn't guarantee it'd be empty immediately after the peek when you try to send.
 

defel

Member
I need some MATLAB help, heres the problem:

I want to create a kxk matrix for n different observations. I then want to add all n of these kxk matrices together to create a single kxk matrix which is the sum of all the others. Here is what I have been trying to do:

I initially tried to generate n separate matrices in MATLAB through a loop but that didnt work and given that in this case n=700 it wouldnt be practical. I did read about storing data like that in cell arrays so I tried...

Code:
B = the function creating the kxk matrix for each i=1,...,n observation 

A = cell(k,k,n);                 % A is just a k x k x n 3-dimensional matrix

for i=1:n;
      A( : , : , i ) = B(i)
end;

So my thinking was that on each iteration of the loop it generate the matrix B and adds it to the ith plane in the third dimension. Im kinda winging it so im not sure if this is the best way to do it. Unfortunately its giving me an error along the lines of "Conversion to cell from double is not possible." What is the correct way to solve a problem like this?
 

Feep

Banned
What happens when you try to send data over the pipe when there's data waiting to be read from it (from the other side)? Do you lose that data, or does the send fail, or does it work just fine?

If that doesn't work, you're going to have problems no matter what. Because even if you could peek at the stream to see if it was empty, that doesn't guarantee it'd be empty immediately after the peek when you try to send.
So I basically gave up and said screw pipes. After some research, though, I actually learned that when you spawn processes from inside C#/.NET, you can redirect their standard output and input streams and pick them up manually via asynchronous read calls. It took me awhile, but now I have a far cleaner and far more reliable method of data transmission. I did have to deal with some junk in the first couple strings, but nothing a little helper function couldn't fix. ^^

Yay!
 
I need some MATLAB help, heres the problem:

I want to create a kxk matrix for n different observations. I then want to add all n of these kxk matrices together to create a single kxk matrix which is the sum of all the others. Here is what I have been trying to do:

I initially tried to generate n separate matrices in MATLAB through a loop but that didnt work and given that in this case n=700 it wouldnt be practical. I did read about storing data like that in cell arrays so I tried...

Code:
B = the function creating the kxk matrix for each i=1,...,n observation 

A = cell(k,k,n);                 % A is just a k x k x n 3-dimensional matrix

for i=1:n;
      A( : , : , i ) = B(i)
end;

So my thinking was that on each iteration of the loop it generate the matrix B and adds it to the ith plane in the third dimension. Im kinda winging it so im not sure if this is the best way to do it. Unfortunately its giving me an error along the lines of "Conversion to cell from double is not possible." What is the correct way to solve a problem like this?

Try this:
Code:
B = some K x K x N matrix
s = sum(B, 3)
The sum function takes a matrix or a vector as argument and an optional argument that says along which dimension you want to sum. Unless I don't understand you correctly, you want to sum the contents of the "stack" of matrices into one matrix, so this should do the trick.

edit: Oh, and for concatenating matrices, try cat().
 
Why can't I code with some current hipster p-lang or something instead of AS3/Flex, WHYY.

/vent

I just spent like 40 hours (7 hours today, the rest some months ago) trying to find a solution for a bug. Bug of items duplicating after dragging.

Today I traced every possible solution, tried everything I could but "move" event always launched "copy" event. Hell, even if I removed all my custom Drag/Drop event handlers, it still did the same behavior: items didn't move, items duplicated.

I go and try to understand this post again and again, which is the same bug as mine:
http://forums.adobe.com/message/3450068#3450068 and what his fix was.

I scroll a bit up and see this:
If you are looking to drag things within a List without copying you will need to set the dragMoveEnabled flag to true, for example:

What? But I have dragMoveEnabled.

I go to look at my code:

Code:
slideBrowser.dragEnabled = true;
slideBrowser.dropEnabled= true;

I type slideBrowser.drag and press CTRL+Space and IDE shows me this

Code:
slideBrowser.dragEnabled
slideBrowser.dragMoveEnabled

I set dragMoveEnabled to true and now it works properly. If you set dragEnabled to false, drag is disabled, both copy and move. It's not a bug. It's EXPECTED BEHAVIOUR. The bug is that dragDrop changes the class so the bindable propertys get screwed. Dropping an object with class "object SomeClass" is SomeClass until some X point that can't be traced, but sometime after dragDrop-event completes but it changes SomeClass to "object Object" and thus the bindings don't work.

I understand that they are named that way so you can't have dragCopy and dragMove enabled at the same time, but whoever thought that naming them that way was a good idea, FUCK. YOU.


edit: Oh course it's my fault for not reading the full forum post line by line when I first found it but still
 

usea

Member
What's a hipster language? I think you'd find a lot of people would say AS3 is definitely a hipster language (along with haxe). This is because hipster is a non-word that people use without any real meaning.
 

Natural

Member
Having not really touched programming since finishing my degree two years ago, I decided its time to really get into it again so I can get a job in the IT industry.

I studied Java, C++, XNA among others; primarily using C++ and XNA.

Since I was quite good at XNA I'm touching some C# to get me into it again, when I touched it at Uni it was only briefly when compared to C++.

Anyway, website I'm using is http://www.csharp-station.com/ which I think I got from here or a similar thread on GAF.

So far, so good, hopefully i'll be done with all 23/24 sections by end of the week.
 

usea

Member
Holy shit, this is amazing. Thanks for posting! My company brought in a instructor to teach an on-site class to teach us advanced C# concepts. He did a very poor job covering threading concepts in C#. This is exactly what I was looking for.
No problem. It's the best page I've seen that covers those topics. I think it does a really great job. Recommended to anybody who wants to learn about threading, concurrency, etc.
 

luoapp

Member
Code:
B = the function creating the kxk matrix for each i=1,...,n observation 

A = cell(k,k,n);                 % A is just a k x k x n 3-dimensional matrix

for i=1:n;
      A( : , : , i ) = B(i)
end;

So my thinking was that on each iteration of the loop it generate the matrix B and adds it to the ith plane in the third dimension. Im kinda winging it so im not sure if this is the best way to do it. Unfortunately its giving me an error along the lines of "Conversion to cell from double is not possible." What is the correct way to solve a problem like this?

zeros(k,k,n) or nan(k,k,n)

also, what "close to the edge" says, sum(A,3)
 
I was thinking about going back and learning math again starting through precalculus and working my way into calculus. So I'm guessing you wouldn't recommend that? What would be the best way to work my way up into discrete mathematics if that's more useful than calculus? And why exactly is discrete mathematics more useful than calculus?

I haven't done mathematics since grade 12(I'm 23 now) so what would be the best approach for me?

Two things. First, the best C++ book for beginners IMO is Accelerated C++. It's the shortest programming book that teaches you how to be productive with modern C++ i.e. using the STL library from the start.

Second, discrete math is much better for Computer Science because computers themselves are discrete machines. Just think about it for a second, how do you represent a continous range of numbers in a computer. Calculus deals with limits and continuous numbers. Discrete Math deals with a lot of topics that are the foundation of how computers works. The best way to learn discrete math by yourself is probably to get a good textbook. I used Rosen in college, but it's not an easy book to read, especially for someone with a decent amount of rust in their mathematical ability. You should also check MIT Opencourseware classes called "Mathematics for Computer Science." The website has class materials for several semesters. Pick one and try to follow it on your own. Good luck!

http://courses.csail.mit.edu/6.042/spring13/class-material.shtml
 

Kalnos

Banned
Two things. First, the best C++ book for beginners IMO is Accelerated C++. It's the shortest programming book that teaches you how to be productive with modern C++ i.e. using the STL library from the start.

Great post overall. I'm not sure about Accelerated C++ though. When I started programming many years ago that is the book that I was recommended and I don't think it was very good for me as a new programmer. It's a great book for a programmer new to C++ for sure but I'm just not convinced it's a good book for someone without any prior programming experience.
 

usea

Member
Why the hell is VB.NET considered a bad language? I can build stuff with it pretty damn quickly and it runs at the same speed as a similar C# app. What's the deal with the VB hate? I am currently self-teaching C# (good book! http://www.amazon.com/dp/1430242337/?tag=neogaf0e-20 ) but I am not noticing a big deal so far. Hmm.....
http://stackoverflow.com/questions/66130/whats-so-bad-about-vb-net
http://blogbybob.com/post/2009/11/03/Why-VBNET-is-a-Bad-choice.aspx
http://www.dreamincode.net/forums/topic/146987-is-vbnet-really-that-bad/
http://discuss.fogcreek.com/joelonsoftware/default.asp?cmd=show&ixPost=133684
http://weblogs.asp.net/fbouma/archive/2003/11/12/37199.aspx
Some of the above links are super old, fyi.

Draw your own conclusion. But I think you're going to be dissatisfied no matter what, since you're arguing with nobody in particular.

My answer: the differences between most languages are not that huge, all things considered. Since programmers are often working with their head down in the trenches, and they're human beings, they tend to magnify small differences and become attached to insignificant things. It's religious.

People naturally make judgments about things when they have a limited amount of information. For example, this guy walking down the street is dressed a certain way, so I'm going to avoid him because he might be crazy. But just because you've perceived a correlation between a certain dress and mental illness doesn't 't make it reasonable. Yet, this is how the human brain works when on autopilot. People do this a hundred times a day, and programming is no exception. People judge VB.NET and its programmers based on perceived, correlated information like poor skills, weird syntax, second-hand information they heard somebody says once, etc. Because they're humans and they're not being mindful.

IMO I think programming languages are mostly evolving in great directions these days. People are starting to embrace lots of different and useful paradigms like functional programming and declarative programming, and they're rejecting things that haven't worked that well in the past. If you look at C# in .NET 1.0 vs C# 5 (.NET 4.5) they've added tons of great stuff like parametric polymorphism, closures, type inference, lambda expressions, first class function objects, creating types on-demand, etc. Newer languages come with a lot of this stuff out of the box, and they often also include things like first class tuples, pattern matching, destructuring, option/maybe/either types, etc.

There's nothing "wrong" with languages that are missing some of these features, but I will tell you that it's hard going back once you've started using some better tools. Not to say VB.NET is necessarily missing a lot of this stuff; I'm just going off on a tangent.

I think languages like haskell, scala, rust, and go have bright futures, and exposing yourself to some of the alternative ways of programming that are out there makes you a far better programmer.
 

jon bones

hot hot hanuman-on-man action
hmm anyone use linq queries? or maybe if you know SQL, you can help me out.

i've got a table of X rows, all rows have a bool key (let's call it "top") set to false, except for one. i want to return the top 4 results so that the 1st result is the one with top set to true, and the remainder are in alphabetical order... how do i do that?

1) top == true
2) aa
3) bb
4) cc

i tried using "take(1) where top == true, take (3) order by alphabetical" but that's totally wrong... anyone got any ideas?

thanks!
 
Is this in a DB or in memory?

Regardless, you might try something like

Code:
var query = table.Where(item => item.Top).Take(1).Union(table.Where(item => !item.Top).OrderBy(item => item.Whatever).Take(3));

If you know for certain that you have precisely 1 true and the rest false, you might also try

Code:
var query = table.OrderByDescending(item => item.Top).ThenBy(item => item.Whatever).Take(4);
 

jon bones

hot hot hanuman-on-man action
Is this in a DB or in memory?

Regardless, you might try something like

Code:
var query = table.Where(item => item.Top).Take(1).Union(table.Where(item => !item.Top).OrderBy(item => item.Whatever).Take(3));

If you know for certain that you have precisely 1 true and the rest false, you might also try

Code:
var query = table.OrderByDescending(item => item.Top).ThenBy(item => item.Whatever).Take(4);

thanks, b - that second one looks like it should do the trick!

i'm pulling this from a sql server
 
I need to write a code that will spell out the digit located in the hundred position of an integer that I type in a textbox. In other words if I type 323 in the textbox then the digit in the label will display "three". Similarly if I did 4563 the label would display "five".

I have been looking all over the internet for this and using my book but I can't find anything on it at all.

What's the simplest way to do this?
 

Tamanon

Banned
I need to write a code that will spell out the digit located in the hundred position of an integer that I type in a textbox. In other words if I type 323 in the textbox then the digit in the label will display "three". Similarly if I did 4563 the label would display "five".

I have been looking all over the internet for this and using my book but I can't find anything on it at all.

What's the simplest way to do this?

String it and slice it
like in Python it'd be:

num1 = input("What is the number you're entering?")
hundreds = str(num1)[-3]
if hundreds == "0":
print "zero"
elif hundreds == "1":
print "one"
elif hundreds == "2":
print "two"

And so on.It's super simple if you don't have to spell it out, because that chops off the big if/then tree.
 

Jokab

Member
I need to write a code that will spell out the digit located in the hundred position of an integer that I type in a textbox. In other words if I type 323 in the textbox then the digit in the label will display "three". Similarly if I did 4563 the label would display "five".

I have been looking all over the internet for this and using my book but I can't find anything on it at all.

What's the simplest way to do this?

I would just divide by 100 and then get modulo 10 (% operator) to get the remainder, that'll give you the number.

Of course assumes that it's not a decimal number, so you might want to round off to begin with to eliminate that possibility.
 

iapetus

Scary Euro Man
String it and slice it
like in Python it'd be:

num1 = input("What is the number you're entering?")
hundreds = str(num1)[-3]
if hundreds == "0":
print "zero"
elif hundreds == "1":
print "one"
elif hundreds == "2":
print "two"

And so on.It's super simple if you don't have to spell it out, because that chops off the big if/then tree.

If you can get the value as a number, you can do this trivially with an array, of course.

If you use the language's built-in libraries to parse the entered string as an integer, you get all the validation of the data entry, and you can then get the hundreds digit trivially as Jokab points out. In something like Java:

Code:
public class NumberConverter {
  public static final String INVALID_NUMBER = "WTF?";
  public static final String[] NUMBERS = {
    "zero",
    "one",
    "two",
    "three",
    "four",
    "five",
    "six",
    "seven",
    "eight",
    "nine",
  }

  public String getHundredsDigit(String text) {
    String textDigit = INVALID_NUMBER;
    try {
      int value = Integer.valueOf(text);
      int hundredsDigit = (value / 100) % 10;
      textDigit = NUMBERS[hundredsDigit];
    } catch (NumberFormatException nfe) {
      // Couldn't parse number - stick with the default error message
    }
    return textDigit;
  }
}

If you want to do it by string manipulation you can, but you'll probably need to be more careful with error checking - most languages will explode if you ask them for a character that doesn't exist in the string, so a simple implementation might crash with "43" as input, and might give unexpected results with non-numeric entries, or ones with extra leading/trailing spaces.
 

Onemic

Member
Im doing the very first lesson in the book, "learning c++ in an hour a day" and I can't seem to get past first example which is just a log of "Hello World!" I really don't know what I'm doing wrong. If anyone can help me it would be very much appreciated.

Below is my code which is copied word for word from the book.

Code:
#include <iostream>

int main()
{
	std::cout << "Hello World!" << std::end1;
	return 0;
}

I get this error log:

1>------ Build started: Project: Hello, Configuration: Debug Win32 ------
1> Hello.cpp
1>c:\users\karsius\documents\visual studio 2012\projects\hello\hello\hello.cpp(7): error C2039: 'end1' : is not a member of 'std'
1>c:\users\karsius\documents\visual studio 2012\projects\hello\hello\hello.cpp(7): error C2065: 'end1' : undeclared identifier
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

I'm using Visual Express Studio 2012 btw. The example picture in the book is running Visual C++ 2010 Express.
 

Onemic

Member
You should probably use a better code font. :p

Consolas is usually sufficient.

how do you change the font?

Also is there any way to make each line numbered?

Lastly, whenever I want to run my code it keeps telling me that my project is out of date before allowing me to run it anyway. Is there any way to solve this?
 
how do you change the font?

Also is there any way to make each line numbered?

Lastly, whenever I want to run my code it keeps telling me that my project is out of date before allowing me to run it anyway. Is there any way to solve this?

Both are in Tools -> Options. The font settings are at Environment -> Fonts and Colors and you can enable line numbers in Text Editor -> C/C++ (it's at the bottom).
I think Consolas is the default font for Visual Studio, but I could be wrong. There's also Source Code Pro which I use, but it's just a matter of taste, both are fine.

As for your last problem, I haven't had that issue before. Try doing Build -> Build Solution before you run, that might fix it. Normally, VS should build (compile) your project before you run it. If you run it anyways, do you get the latest version of your code? Try changing the value that you print out to your console.

If you're looking for something in VS, you can search for it by pressing Ctrl+Q (unless that feature is not in Express Edition, which would be weird). For instance, you can enter Font and it'll take you directly to the font settings as the first suggestion.
 
Had a somewhat bad interview experience. I was about to take a bus, when I received an unexpected call from a company. The guy told me it was a technical interview to filtrate candidates so I thought it would be just CS concepts, there was some car noise around, but I still accepted to take it at that moment.

He started asking (simple) algorithm questions and some puzzles, and everything went well except two questions where I really struggled. He gave me a few minutes to think about the answer but I still couldn't come up with anything better (and to be honest that wasn't the best place to think, especially with no paper and pencil).

Now I fear that those questions are gonna shadow the rest of the questions that I answered with confidence. I should have had declined the interview at that time...
 

Kalnos

Banned
It's pretty weird that he called you and asked to interview on the spot... most places I have interviewed with schedule it in advance. Was it a small company?
 

leroidys

Member
I need to write a code that will spell out the digit located in the hundred position of an integer that I type in a textbox. In other words if I type 323 in the textbox then the digit in the label will display "three". Similarly if I did 4563 the label would display "five".

I have been looking all over the internet for this and using my book but I can't find anything on it at all.

What's the simplest way to do this?

What language?
 
Top Bottom