• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Tim Cooke
  • Jeanne Boyarsky
  • Liutauras Vilda
Sheriffs:
  • Frank Carver
  • Henry Wong
  • Ron McLeod
Saloon Keepers:
  • Tim Moores
  • Frits Walraven
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Piet Souris
  • Himai Minh

Recursion Help -3. Understanding better

 
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The problem is Given an array of ints, is it possible to choose a group of some of the ints, such that the group sums to the given target? Target below is 10.

I know to solve the problem in a different way. Trying to understand the below code. This should give me deeper understanding on recursion.

Could any of you explain, when Line #13(groupSum(start + 1, nums, target - nums[start])) would be executed and when Line #14(groupSum(start + 1, nums, target)) would be executed or both execute parallel y. By looking into the print-line display I see the Line #14 gets executed only one Line#13 is false. Is this the way it works.

I can understand Line #13 and 14 are same statement. For explaining clarity, I have used the Line #s to differentiate recursively called function. Sorry about that!



Print-Line output:

 
Bartender
Posts: 1845
10
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Your question is nothing specifically to do with recursion, and is mainly related to java syntax of the OR operator.

In Java, the boolean operators are "lazy" by default.
So when evaluating A || B (A or B), It will first evaluate A (the left hand side). If A is true, it does not bother to evaluate B, as in boolean logic true ORed with anything is always going to be true.

The person coding this example has just taken advantage of this feature, and the fact that this recursive method returns a boolean value.
Essentially it is the same as



It just takes less lines of code.
The down side is that it makes it more difficult to read and understand.

 
Did you ever grow anything in the garden of your mind? - Fred Rogers. Tiny ad:
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic