• 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

Onemic

Member
Definitely go with IntelliJ, have quoted my above post above about why it's so awesome.

Some books that I'd recommend:



Thanks for the suggestions. I was looking at Head First Java and Effective Java, but noticed that Head First Java doesnt include Java 8 features.

Do you know of any good intro books that include Java 8 features? In particular lambdas, reg expressions, and Java FX? My class will be going over these concepts:





Classes and Objects - 10%
  • primitive types and references to objects
  • programming with types and packages
  • generics and annotations
Interface, Nested Classes, Functional Concepts - 20%
  • working with interface
  • static nested classes
  • inner classes
  • anonymous inner classes
  • lambda expressions
  • functional interfacaes
Exceptions - 5%
  • exception handlers, transfer of control
  • asynchronous exceptions
  • try, catch, finally blocks
Threads - 15%
  • creating threads using Thread class/Runnable interface
  • synchronization design, wait / notify
  • thread scheduling, management and thread group
Standard Java Packages - 10%
  • java.io - Input/Output Stream, Reader/Writer and serialization
  • java.net - Sockets
  • java.util - Collections: Set, List, Queue, Map
Networking - 10%
  • InetAddress class
  • socket and server socket
  • uniform resource locator - URLConnection class
Java FX - 10%
  • build-in UI controls
  • Webview and Swing interoperability
  • self-contained application development model
Remote Method Invocation - 10%
  • RMI specifications
  • RMI client and RMI server
  • RMI tools: rmic, rmiregistry
Introduction to Java Enterprise Edition - 10%
  • JDBC - Data Access APIs
  • servlets
 
Kernel development
OS development
Embedded systems
Robotics?
Games
Application level development
Web development
Mobile Development
Scientific Programming
Artificial Intelligence / Neural net

There is a lot out there...
I would add systems programming, database programming, security engineering, ui / client development, and maybe others.

I would combine some of these, focusing on the skill sets required and the languages that end up being used:

1. systems programming (kernel, os) -- C, maybe C++
2. embedded programming -- ???
3. high performance computing (stock trading, simulations, videogames...) -- C, C++
4. scientific programming (AI, life sciences, robotics) -- python, perl, R, etc
5. backend web development -- ruby (rails), java (spring), python, php, sql, etc
6. frontend web + mobile app development -- javascript, obj C (iOS), java (android)
7. desktop application development -- C# (.NET), C++ (mostly legacy, python would be the current hotness in linux land), a million other things
8. random scripts that may or may not count as "real programming" -- every language, but bash, perl, python, ruby, etc
9. security programming -- no worries, this field doesn't actually exist

That feels roughly comprehensive.
 

Roflobear

Member
Thanks for the suggestions. I was looking at Head First Java and Effective Java, but noticed that Head First Java doesnt include Java 8 features.

Do you know of any good intro books that include Java 8 features? In particular lambdas, reg expressions, and Java FX? My class will be going over these concepts:

I'd recommend Introduction to Java Programming. Aside from the RMI stuff you mentioned, I think it covers every topic you listed. I had the 9th edition when I was learning Java and it was an amazing resource. I found it to be very well written.

Also are you gonna learn all of that in one semester? Seems like a hefty intro course haha
 

Onemic

Member
I'd recommend Introduction to Java Programming. Aside from the RMI stuff you mentioned, I think it covers every topic you listed. I had the 9th edition when I was learning Java and it was an amazing resource. I found it to be very well written.

Also are you gonna learn all of that in one semester? Seems like a hefty intro course haha

Yup, from January to April. I've heard horror stories about this class being really hard, so I want to get as ahead of the pack as possible lol.
 
1. systems programming (kernel, os) -- C, maybe C++
2. embedded programming -- ???
3. high performance computing (stock trading, simulations, videogames...) -- C, C++
4. scientific programming (AI, life sciences, robotics) -- python, perl, R, etc
5. backend web development -- ruby (rails), java (spring), python, php, sql, etc
6. frontend web + mobile app development -- javascript, obj C (iOS), java (android)
7. desktop application development -- C# (.NET), C++ (mostly legacy, python would be the current hotness in linux land), a million other things
8. random scripts that may or may not count as "real programming" -- every language, but bash, perl, python, ruby, etc
9. security programming -- no worries, this field doesn't actually exist

That feels roughly comprehensive.

Embedded is basically C or C++. It has traditionally been more C heavy but you can find C++ popping up these days as embedded devices get more memory.
 
Lol, it very much does. The fact that you say that, however, is a testament to the sad state of internet security.
I'm being a little facetious. Everybody says they want security, but it's almost never prioritized. Actions speak louder than words.

So all those other types of programming (using this interchangeably with "software engineering", if you haven't noticed) end up half-heartedly worrying about security themselves, which is how we get the super-secure software we have today!
 

soultron

Banned
Fell off in 2014 after having completed several chapters of Accelerated C++ (Moo, Koenig). Gotta get back into it 2015. I will finish the book in 2015.
I must.
 

Massa

Member
Just wanted to recommend this book. It's a must read for every programmer imo. It's short and easy to read, and by far the best read I've found on the subject.

cover.jpg
 

Granadier

Is currently on Stage 1: Denial regarding the service game future
Fell off in 2014 after having completed several chapters of Accelerated C++ (Moo, Koenig). Gotta get back into it 2015. I will finish the book in 2015.
I must.

I have three books to finish as well. 2015 will be my year of finishing books.
 
Where the heck was this buried and why have I never seen this thread before? Consulting the infinite wisdom of NeoGAF would've been better than combing through stackoverflow.

Anyway, a question regarding IDEs: I'm currently working on a Java-based enterprise server web application (meaning lots of JAR and WAR projects), using Maven to build and Git as source control. Our team primarily uses eclipse right now, but we've been hitting some serious problems with m2e stalling progress whenever we need to work on other branches. Any advice on how to alleviate this for eclipse or suggestions on other IDEs to use instead?
 

MNC

Member
Where the heck was this buried and why have I never seen this thread before? Consulting the infinite wisdom of NeoGAF would've been better than combing through stackoverflow.

Anyway, a question regarding IDEs: I'm currently working on a Java-based enterprise server web application (meaning lots of JAR and WAR projects), using Maven to build and Git as source control. Our team primarily uses eclipse right now, but we've been hitting some serious problems with m2e stalling progress whenever we need to work on other branches. Any advice on how to alleviate this for eclipse or suggestions on other IDEs to use instead?
We used intellij for our java ee application with tomcat. So many configurations and options, it's insane. Seriously, I cannot believe I primarily used eclipse and netbeans for java products. Jetbrains is my god. Intellij has great VCS support.
 
So I am doing the MIT course for intro to computer science. I am working on a problem set where I have to do:

Implement the evaluate_poly function. This function evaluates a polynomial function for the given x value. It takes in a tuple of numbers poly and a number x. By number, we mean that x and each element of poly is a float. evaluate_poly takes the polynomial represented by poly and computes its value at x. It returns this value as a float.

Code:
def evaluate_poly(poly, x): 
   
  
       
""" Computes the polynomial function for a given value x. Returns that value. 
Example: >>> poly = (0.0, 0.0, 5.0, 9.3, 7.0) # f(x) = 7.0x4 + 9.3x3 + 5.0x2 >>> x = -13
>>> print evaluate_poly(poly, x) # f(-13) = 7.0(-13)4 + 9.3(-13)3 + 5.0(-13)2 180339.9
poly: tuple of numbers, length > 0 x: number returns: float """ 
# TO DO ...

My code (below) ends up giving the correct answer. I'm just not sure if my code has any problems that I'm not noticing. Any glaring bugs or issues? Also the language of the problem implies that I need to do this in one function. I've split it into two functions, though that's because the first function turns a tupple into a list since I don't know how to retrieve individual values from tupples which I think I need to do in order to do the required math? Is that actually necessary? Is there a way to combine these two into a single function?

Code:
#this function takes list we generate and then computes a polynomial function using values in the list 
def stuff(s, y): 
	x = 0
	b = 0
	for i in s:
		b += (float(i)) * (y**x) #in this case we are taking 7*y^4 + 9.3*y^3 + 5.0*y^2 + etc... where y = -13
		x += 1
	c = b 
	print c #correctly gives 180339.9
	return c  
		
#this function should take poly (a tuple) and converts it into a list. 
def evaluate_poly(poly, y):
	s = list(poly) 
	stuff(s,y)
	
x = 0.0, 0.0, 5.0, 9.3, 7.0
y = -13
evaluate_poly(x, y)
 
We used intellij for our java ee application with tomcat. So many configurations and options, it's insane. Seriously, I cannot believe I primarily used eclipse and netbeans for java products. Jetbrains is my god. Intellij has great VCS support.

I've got it installed right now but haven't had the time to give it a test run. Suppose that's good enough reason to give it a go during this holiday lull.

How easy is it to get Tomcat 7 deployed in it? One of the nice things about Eclipse was how simple it was to set up a server environment.
 

survivor

Banned
So I am doing the MIT course for intro to computer science. I am working on a problem set where I have to do:



My code (below) ends up giving the correct answer. I'm just not sure if my code has any problems that I'm not noticing. Any glaring bugs or issues? Also the language of the problem implies that I need to do this in one function. I've split it into two functions, though that's because the first function turns a tupple into a list since I don't know how to retrieve individual values from tupples which I think I need to do in order to do the required math? Is that actually necessary? Is there a way to combine these two into a single function?

Code:
#this function takes list we generate and then computes a polynomial function using values in the list 
def stuff(s, y): 
	x = 0
	b = 0
	for i in s:
		b += (float(i)) * (y**x) #in this case we are taking 7*y^4 + 9.3*y^3 + 5.0*y^2 + etc... where y = -13
		x += 1
	c = b 
	print c #correctly gives 180339.9
	return c  
		
#this function should take poly (a tuple) and converts it into a list. 
def evaluate_poly(poly, y):
	s = list(poly) 
	stuff(s,y)
	
x = 0.0, 0.0, 5.0, 9.3, 7.0
y = -13
evaluate_poly(x, y)
You don't need to actually convert your tuple to a list, just iterate over it normally. For example instead of calling evaluate_poly(x, y) in the last line just directly call stuff(x, y) and you will see that you are getting the correct result.
 
You don't need to actually convert your tuple to a list, just iterate over it normally. For example instead of calling evaluate_poly(x, y) in the last line just directly call stuff(x, y) and you will see that you are getting the correct result.

Huh I will try it. I could have sworn I tried it before and got an error before. But then again my code changed a bit since my first attempt so maybe it was something else that did that. Thanks. :)

edit: it worked, thanks lol1.
 

moka

Member
We used intellij for our java ee application with tomcat. So many configurations and options, it's insane. Seriously, I cannot believe I primarily used eclipse and netbeans for java products. Jetbrains is my god. Intellij has great VCS support.

I second this SO HARD.

JETBRAINS JETBRAINS JETBRAINS
 

barnone

Member
looking for advice on branching out. I'm doing mobile apps development (ios, android, .net for backend) and have a CS degree (graduated 6 months ago). I feel like all I do is create UIs and sometimes code trivial business logic. I want to spread my wings! I got A's in all my CS classes and am wondering if I'm not reaching my full potential with mobile. I would really love to get into the music industry, even if I have to work on my low level programming. But I have no idea what audio programming means in today's businesses.

I've been learning behavior driven development also, and it rocks guys and gals!
 

Onemic

Member
In a Java interface, are a static method and default method essentially the same thing? If not, what's the difference between them?
 

squidyj

Member
So.... if you have an array sorted on some x such that the value of x could be mapped to a real number, couldn't you generate an approximate polynomial using least squares and then further a bound on the error of the polynomial providing a limited search space within the original sorted array within which to search?

that is to say if we say that the entry where x = 0.53 has index 3 then
f(0.53) = 3.0

then if f' is the polynomial approximating f (we assume that instead of mapping to integers, we are mapping

f'(0.53) ~= 3.0

and that we can establish an error bound such that

3.0 - g(0.53) <= f'(0.,53) <= 3.0 + g(0.53)

where g is our bound on the error.

Am I crazy? Is there somewhere where this is being done?
 
So.... if you have an array sorted on some x such that the value of x could be mapped to a real number, couldn't you generate an approximate polynomial using least squares and then further a bound on the error of the polynomial providing a limited search space within the original sorted array within which to search?

that is to say if we say that the entry where x = 0.53 has index 3 then
f(0.53) = 3.0

then if f' is the polynomial approximating f (we assume that instead of mapping to integers, we are mapping

f'(0.53) ~= 3.0

and that we can establish an error bound such that

3.0 - g(0.53) <= f'(0.,53) <= 3.0 + g(0.53)

where g is our bound on the error.

Am I crazy? Is there somewhere where this is being done?

What's the advantage? Are you trying to make reverse lookup faster or something? I.e. Find the index which a value is at in the array?

A straight sequential lookup is O(n) and a binary search is O(log n). Suppose you generate some polynomial. It has to be at least degree n-1, where n is the length of the array, to uniquely identity n values. Therefore computing the value of the polynomial is also O(n) (n multiplications, n-1 additions, n-1 exponentiations)

On the other hand, if the purpose is to be able to supply arbitrary values to the polynomial to see how close it lies to an existing value, maybe useful? Although depending what higher level problem you're trying to solve, there may be something better.
 

squidyj

Member
What's the advantage? Are you trying to make reverse lookup faster or something? I.e. Find the index which a value is at in the array?

A straight sequential lookup is O(n) and a binary search is O(log n). Suppose you generate some polynomial. It has to be at least degree n-1, where n is the length of the array, to uniquely identity n values. Therefore computing the value of the polynomial is also O(n) (n multiplications, n-1 additions, n-1 exponentiations)

On the other hand, if the purpose is to be able to supply arbitrary values to the polynomial to see how close it lies to an existing value, maybe useful? Although depending what higher level problem you're trying to solve, there may be something better.

if we wanted the polynomial to pass through every data point it would have to be degree n-1 but we just really need an approximation and an error, with a fixed degree, eg, fixed to being cubic, or quadratic.

You wouldn't necessarily hit the element just by evaluating the polynomial but you would establish a subrange it would exist in and you could binary search within that
 
Code:
#this function takes list we generate and then computes a polynomial function using values in the list 
def stuff(s, y): 
	x = 0
	b = 0
	for i in s:
		b += (float(i)) * (y**x) #in this case we are taking 7*y^4 + 9.3*y^3 + 5.0*y^2 + etc... where y = -13
		x += 1
	c = b 
	print c #correctly gives 180339.9
	return c  
		
#this function should take poly (a tuple) and converts it into a list. 
def evaluate_poly(poly, y):
	s = list(poly) 
	stuff(s,y)
	
x = 0.0, 0.0, 5.0, 9.3, 7.0
y = -13
evaluate_poly(x, y)

I hope this is helpful criticism, but you'll thank yourself later if you start using better names for your variables. It's really hard to read code with meaningless single letter variable names, even for simple problems like this.

Code:
def evaluate_poly(poly, x):
    result = 0
    exponent = 0
    
    for coefficient in poly:
        result += float(coefficient) * (x ** exponent)
        exponent += 1
        
    return result
 

injurai

Banned
I'm adequately familiar with subversion. Though I only use it in the limited sense that our terribly managed project demands.

I want to learn git, and by that I mean learn how to properly make use of trees, branches, pulls, commits, etc.

What are the best resources to learn? I know some people have created pretty handy tools and sites.
 
I'm adequately familiar with subversion. Though I only use it in the limited sense that our terribly managed project demands.

I want to learn git, and by that I mean learn how to properly make use of trees, branches, pulls, commits, etc.

What are the best resources to learn? I know some people have created pretty handy tools and sites.
I found this helpful. It was pretty easy to read and introduced concepts in a straightforward fashion. YMMV of course.
 
if we wanted the polynomial to pass through every data point it would have to be degree n-1 but we just really need an approximation and an error, with a fixed degree, eg, fixed to being cubic, or quadratic.

You wouldn't necessarily hit the element just by evaluating the polynomial but you would establish a subrange it would exist in and you could binary search within that

Why mess with approximations of real numbers when your domain is intrinsically countable?
 

RustyO

Member
C# / Binary Serialization question.

I've never really done this before, more used to working with serialization of XML files, so wanted to check if I was going about it the right way, or if there was a better approach?

What I would like to do is deserialize a file into a class, to allow easy modification, then be able to serialize back to file.

I have multiple byte files of about 600kb, that contain a logical structure based on start/end offsets. Each file can be logically subdivided further based on the start/offset into say ten of mySubClass, which I am populating based on for loops. (These can also be subdivided further and so on)

At the moment, I am using BinaryReader to read the file to myClass like below:

Code:
// C#
fileStream = File.Open(_File, FileMode.Open, FileAccess.Read);
BinaryReader binaryReader = new BinaryReader(fileStream);
int length = (int)binaryReader.BaseStream.Length;
binaryReader.BaseStream.Seek(0, SeekOrigin.Begin);
myClass = binaryReader.ReadBytes(length);
fileStream.Close();

Then performing the same concept as above, except across myClass via for loop to populate multiple instances of mySubClass.

This all works fine / as expected, but is a bit of a pain to do, so is there is a smarter way to perfrom the above?

Can I make myClass [Serializable()] and define each section of the file as mySubClass based on offset and length?
 
I hope this is helpful criticism, but you'll thank yourself later if you start using better names for your variables. It's really hard to read code with meaningless single letter variable names, even for simple problems like this.

Thanks, that is helpful. I probably should take better care to use more meaningful names for my variables, especially if I expect other people to read my code.

A general question I have for people: I need to develop a Hangman style game. I'm having some minor trouble and part of that is that I don't know a good strategy for breaking down coding problems. What do you guys usually do? Or what did you do when starting out? Should I write a list of the functionality I need my code to have on a piece of paper? Then maybe write out how I would get that functionality?
 
New to iOS programming here, using Swift. I'm trying to make a simple drop down menu when a button is clicked. I figured, why not use the UIPopoverController. But that's only for iPads. I did overwrite it to make it work for iPhones, but takes the whole screen up, not what i want. Plus, I have to pull the menu down just to see the choices. Probably doing something wrong on my end.

I want something like this:

So what would be the best way to create a drop down menu when a button is clicked? My guess is to create a TableView, grab the view from it, fix the dimensions, and do something like: self.view.addSubview(<View goes here>). Then remove the subview when done. I think I'm approaching this incorrectly though since I tried and failing miserably. Is there a better way to do this?

Edit: Solved. To simply do it, create a table view, extend the TableViewDelegate, TableViewDataSources in the current Controller you're in. Implement the basic table methods. Then hide the tableView when in viewDidLoad. When the button is clicked, then show the table. If you want to hide the table when the user clicks anything else then do:

Code:
 override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
         self.table.hidden = true
    }

Very simple and straight forward. I knew I was over complicating things.
 
A general question I have for people: I need to develop a Hangman style game. I'm having some minor trouble and part of that is that I don't know a good strategy for breaking down coding problems. What do you guys usually do? Or what did you do when starting out? Should I write a list of the functionality I need my code to have on a piece of paper? Then maybe write out how I would get that functionality?

Think about how the program works at a high level, build a skeleton and fill in the details.

For a hangman game, at a high level the program is just a loop.

  1. Initialize a new game state object or data structure with a random word.
  2. Display the current game state.
  3. Get input from player.
  4. Process input, updating the game state.
    • If the player is out of guesses then
      Terminate the loop. The player has lost.
    • If the player has guessed the word
      Terminate the loop. The player has won
    • Otherwise, Goto 2.

This is pretty much code that you can write into a program. The complex steps will be broken out into functions: e.g., initialize game state, display game state, get input, etc. are all functions.

In general, you want each function to have a clearly defined and limited role, and you want to reduce the interdependencies between them as much as possible. This will make it easier to read, debug, and maintain.
 
Think about how the program works at a high level, build a skeleton and fill in the details.

For a hangman game, at a high level the program is just a loop.

  1. Initialize a new game state object or data structure with a random word.
  2. Display the current game state.
  3. Get input from player.
  4. Process input, updating the game state.
    • If the player is out of guesses then
      Terminate the loop. The player has lost.
    • If the player has guessed the word
      Terminate the loop. The player has won
    • Otherwise, Goto 2.

This is pretty much code that you can write into a program. The complex steps will be broken out into functions: e.g., initialize game state, display game state, get input, etc. are all functions.

In general, you want each function to have a clearly defined and limited role, and you want to reduce the interdependencies between them as much as possible. This will make it easier to read, debug, and maintain.

Thanks. What you describe is what I have so far and that's the easiest part. The hard part for me right now is figuring out how to get the program to output stuff like "_____" and then update that string with the letters in order. Like lets say the word is "water" and the player guesses t. I want it to output something like "--t--" and then if they guess e output "--te-".

Mostly because I lack experience with editing and changing values in strings. I know how to do it to lists.
 
Thanks. What you describe is what I have so far and that's the easiest part. The hard part for me right now is figuring out how to get the program to output stuff like "_____" and then update that string with the letters in order. Like lets say the word is "water" and the player guesses t. I want it to output something like "--t--" and then if they guess e output "--te-".

Mostly because I lack experience with editing and changing values in strings. I know how to do it to lists.

Python is good for this because you can experiment in the interpreter and once you get it right, copy it into your code.

This is just string manipulation. I don't want to give too much away because this is homework, but part of the game state will be a list of letters guessed and what the correct answer is. You would iterate through the correct answer and check if each letter is in the "guessed" list. If it is, output the letter, otherwise, output a hyphen.

Edit: It might be helpful if you remember that in Python, a string can be treated as a list of letters. E.g. if you did

Code:
for x in 'hello':
    print x

it would print the letters in "hello".
 

maeh2k

Member
Thanks. What you describe is what I have so far and that's the easiest part. The hard part for me right now is figuring out how to get the program to output stuff like "_____" and then update that string with the letters in order. Like lets say the word is "water" and the player guesses t. I want it to output something like "--t--" and then if they guess e output "--te-".

Mostly because I lack experience with editing and changing values in strings. I know how to do it to lists.

You don't have to edit strings. You can create a class for the "board" that knows the actual word, which doesn't change, and knows which letters have already been guessed or which positions in the word have already been uncovered. Then you write a printer function that uses that information to piece together the new string everytime you print the word. Don't update the string.
 
if we wanted the polynomial to pass through every data point it would have to be degree n-1 but we just really need an approximation and an error, with a fixed degree, eg, fixed to being cubic, or quadratic.

You wouldn't necessarily hit the element just by evaluating the polynomial but you would establish a subrange it would exist in and you could binary search within that

Also realized this will not work if the array contains duplicate values.
 
Anyone have some good tutorials/ books. I just finished up Data Structures but it was a tough course. I want to iron out some of my downsides and really work hard this break. I am primarily working in Java.
 

upandaway

Member
Anyone have some good tutorials/ books. I just finished up Data Structures but it was a tough course. I want to iron out some of my downsides and really work hard this break. I am primarily working in Java.
Effective Java isn't really a data structures book but he talks a lot about patterns and collections (he wrote the collections classes in the API), might be able to help you out. It's a really good Java book anyway too
 

Onemic

Member
Have a Java question. I'm trying to see how it's possible that the compiler can supply a value to the index parameter when there is no instance of index anywhere within the program? Here is the function definition and call below:

Code:
    public void print(java.util.function.Function<Integer, Boolean> function) {
        for (int i = 0; i < SIZE; i++) {
            if (function.apply(i)) {
                System.out.print(arrayOfInts[i] + " ");
            }
        }
        System.out.println();
    }
Code:
        System.out.println("print(Function) with lambda expressions");
        ds.print(index -> {
            if (index % 2 == 0) return Boolean.TRUE;
            return Boolean.FALSE;
        });
        ds.print(index -> {
            if (index % 2 == 0) return Boolean.FALSE;
            return Boolean.TRUE;
        });

index is always supplied a value and I don't understand how.
 

maeh2k

Member
Have a Java question. I'm trying to see how it's possible that the compiler can supply a value to the index parameter when there is no instance of index anywhere within the program? Here is the function definition and call below:

Code:
    public void print(java.util.function.Function<Integer, Boolean> function) {
        for (int i = 0; i < SIZE; i++) {
            if (function.apply(i)) {
                System.out.print(arrayOfInts[i] + " ");
            }
        }
        System.out.println();
    }
Code:
        System.out.println("print(Function) with lambda expressions");
        ds.print(index -> {
            if (index % 2 == 0) return Boolean.TRUE;
            return Boolean.FALSE;
        });
        ds.print(index -> {
            if (index % 2 == 0) return Boolean.FALSE;
            return Boolean.TRUE;
        });

index is always supplied a value and I don't understand how.

The index is defined in the print function. Look at the argument of print -- a function that takes an integer and returns a boolean. That function is called for all indices from 0 to SIZE.

In the second code block the function is called with two different java.util.function.Function<Integer, Boolean>. The two functions that take an integer and return a boolean are supplied via lambda syntax.
 

Onemic

Member
The index is defined in the print function. Look at the argument of print -- a function that takes an integer and returns a boolean. That function is called for all indices from 0 to SIZE.

In the second code block the function is called with two different java.util.function.Function<Integer, Boolean>. The two functions that take an integer and return a boolean are supplied via lambda syntax.

I think this is where I'm confused. I always thought that the compiler would process the lambda expression first to get the result before using that result as the parameter for the print function?
 
I think this is where I'm confused. I always thought that the compiler would process the lambda expression first to get the result before using that result as the parameter for the print function?

Tada! Moment of enlightenment. The anonymous function created by evaluating the lambda expression is the parameter. The resulting function is then repeatedly called within the print method, with results that depend on the value of its own argument (or parameter, the words are interchangeable in this context).
 

Onemic

Member
Tada! Moment of enlightenment. The anonymous function created by evaluating the lambda expression is the parameter. The resulting function is then repeatedly called within the print method, with results that depend on the value of its own argument (or parameter, the words are interchangeable in this context).

ah, I think I get it now! As the parameter of the function, the lambda is not evaluated until the print function uses it which is:
Code:
if (function.apply(i)){...}
The apply function(which I'm still a little confused about tbh) applies the function(which takes an integer and returns a boolean) to the argument(i). This means that that the index is equivalent to the value i as it fufills the requirements for what function takes(an integer). after the lambda is evaluated and returns a boolean value, based on whether the value is true or false the print function will run the code within the if statement or skip it.

Am I understanding this correctly?
 

poweld

Member
ah, I think I get it now! As the parameter of the function, the lambda is not evaluated until the print function uses it which is:
Code:
if (function.apply(i)){...}
The apply function(which I'm still a little confused about tbh) applies the function(which takes an integer and returns a boolean) to the argument(i). This means that that the index is equivalent to the value i as it fufills the requirements for what function takes(an integer). after the lambda is evaluated and returns a boolean value, based on whether the value is true or false the print function will run the code within the if statement or skip it.

Am I understanding this correctly?

Yes, you have it right.
 

squidyj

Member
Also realized this will not work if the array contains duplicate values.

it doesn't seem like people are understanding what i'm saying.

first of all it is a function from the sorted value to a value that is 'somewhat close' to its index

second of all it is an approximating polynomial generated by least squares fitting. If we were attempting to exactly determine the index of a given value via polynomial the fact that duplicates can exist would be a problem. That is not the goal, the goal is to take a very large search space and transform it into a much smaller search space that you can then binary or sequential search. As such we can use (value,index) pairs as a dataset which we can use to provide an approximating polynomial of fixed degree by least squares fitting.
 
ah, I think I get it now! As the parameter of the function, the lambda is not evaluated until the print function uses it which is:
Code:
if (function.apply(i)){...}
The apply function(which I'm still a little confused about tbh) applies the function(which takes an integer and returns a boolean) to the argument(i).

Yes. Calling function.apply() just takes a function (its first argument) and applies it to the rest of the argument list. So function.apply(f, i) would have the same effect as the call f(i) would have, if that were allowed.

Apply is a basic primitive in functional programming. You'll see it turning up in all sorts of different programming languages that attempt to accommodate the functional paradigm.

https://en.wikipedia.org/wiki/Apply
 
Top Bottom