[Boards: 3 / a / aco / adv / an / asp / b / biz / c / cgl / ck / cm / co / d / diy / e / fa / fit / g / gd / gif / h / hc / his / hm / hr / i / ic / int / jp / k / lgbt / lit / m / mlp / mu / n / news / o / out / p / po / pol / qa / r / r9k / s / s4s / sci / soc / sp / t / tg / toy / trash / trv / tv / u / v / vg / vp / vr / w / wg / wsg / wsr / x / y ] [Home]
4chanarchives logo
Recursion in java
Images are sometimes not shown due to bandwidth/network limitations. Refreshing the page usually helps.

You are currently reading a thread in /g/ - Technology

Thread replies: 52
Thread images: 4
File: recursion.png (17 KB, 858x470) Image search: [Google]
recursion.png
17 KB, 858x470
How can i alter the sumOfDigits method so that it takes negative numbers and returns the sum as well as positive?
>>
>>53583295
just...convert the negative number to a positive number...

if(n < 0) n = -n;
>>
>>53583322
Thank you, but the answer still needs to be represented as a negative
>>
>>53583524
Quit your course and do something else.

I'm not trying to be an asshole, but you're going to struggle as things progress, and you'll never get a good job as other people will all be better than you.
>>
not sure what you want. should sumOfDigits(-1234) return (-1) + 2 + 3 + 4 or -(1 + 2 + 3 + 4)?

also, why return 1 if n < 10?
>>
>>53583558


oh shut up. recursion is tricky. people can get software development jobs without actually knowing shit.
>>
>>53583558
Drama queen.
>>
File: Martin_Heidegger.jpg (48 KB, 318x460) Image search: [Google]
Martin_Heidegger.jpg
48 KB, 318x460
>>53583558

Don't listen to this anon.

Progress is achieved by hard work; I assure you the things you're trying to achieve will eventually click, they will become second nature, if you put the time in.

Some people appear to just "get" things straight off the bat. Thie is usually the result of "transferable" skills": a kid who learns music at an early age will have a head start in abstract thinking, for example. Don't let people with this kind of advantage distract you.

Stay focused anon and you will succeed.
>>
>>53583632

>recursion is tricky
Bullshit.

>people can get software development jobs without actually knowing shit
Do you like buggy, insecure software? Yes? Keep encouraging stupidity.
>>
Consider the following
long digits(long n, long sum) {
if (n < 10) return sum;
else return digits(n/10, sum+1);
}
long digits(long n) {
return digits(n, 0);
}
//same for the other one


Now your code will run much faster if Java ever does actually optimize tail calls http://bugs.java.com/bugdatabase/view_bug.do?bug_id=6804517
>>
>>53583632
>he fell for /g/ memes
In all seriousness this guy is right. If you want a good paying comfy job, the interviewers actually ask things to make sure you're not a total idiot. You could always work for a startup and be afraid of losing your job though
>>
>>53585498
Fuck, it's 5am, I'm on my phone, and I'm tired. Should be
return sum + 1
or
if (n == 0)
>>
>>53583295
>return 1;
should be return n;

How can these errors not stand out to you like the letter ‘X’ in a sea of 1s would stand out to a synaesthesiac?
>>
>>53585549
yeah i didnt understand why op is returning 1... like wtf??
>>
>>53585583
>>53585549
The fun part is that his rest case perfectly doesn't catch that.
>>
>>53583295
Meanwhile in Haskell

digits n = 1 + integerLog10 n
sumOfDigits n = sum [ digitToInt c | c <- show n ]
>>
  hi  
>>
>>53583295
why would you do that recursively in the first place?
>>
>>53585632
main = do print (digits 1234)
print (sumOfDigits 1234)

digits :: (Integral a, Num b) => a -> b
digits 0 = 0
digits n = 1 + digits (n `quot` 10)

sumOfDigits :: Integral a => a -> a
sumOfDigits 0 = 0
sumOfDigits n = r + sumOfDigits q
where (q,r) = quotRem n 10


Using quotient instead of modulo to allow it to work for negative numbers in addition to positive numbers, while using the most general possible type.
>>
 
def sumOfDigits( n ):
n=abs(n)
if n<10:
return n
else:
return n%10 + sumOfDigits(n//10)

what do you guys think about this on python??
>>
>>53583909
OP, just ignore and filter these kind of attention seeking tripfag manchildren, they yearn for attention their parents never gave them.
>>
>>53585666
Colleges and universities LOVE to teach recursion with numeric examples where recursion is significantly slower and more complex. When I say "love", I mean it's never taught in a different way.
The dumb students don't get it anyway and the half smart students wonder why they need to implement a recursive version of perfectly viable code.
>>
(define (sumofdigits n)
(define (sumrec n addr)
(cond ((< n 10) (+ n addr))
(else (sumrec (floor (/ n 10)) (+ addr (modulo n 10))))))
(cond ((< n 0) (- (sumrec (floor (- n)) 0)))
(else (sumrec (floor n) 0)))

>tfw tail calls
>>
>>53585666
Why not? The algorithm for solving nicely splits things into independent subproblems which are imo most naturally expressed with recursion.
>>
File: fuck the police 2.jpg (8 KB, 262x193) Image search: [Google]
fuck the police 2.jpg
8 KB, 262x193
>>53585770
right
glad i've got that behind me

    public static long sumOfDigits(long n) {
String nStr = Long.toString(n);
long sum = 0;
for( int i = 0; i < nStr.length(); i++ ) {
sum += Character.getNumericValue(nStr.charAt(i));
}
return sum;
}
>>
>>53585817
wtf is this shit
>>
>>53585770
teaching recursion with numbers gives a good framing of the formal idea of reducing a problem to its base case, which is the typical formulation of a recursive approach. you can teach something with strings or whatever, but you risk people not understanding the real power of recursion.

and you say "the dumb students don't get it anyway" but i think you're just assuming that pedagogically we (academics) are okay with that. obviously we're not, but the history of teaching CS is barely 50 or 60 years old. You can't really appreciate how new that is (and how new the field of teaching CS is) unless you place it alongside other fields.

Add to that the fact that most CS instructors have a much stronger mathematics background than anything else, and
1) it's no surprise that instruction is so terrible, and
2) it shouldn't really surprise anyone that the most abstracted, basic examples and approaches to teaching CS concepts are predicated on numerical cases.
>>
>>53585817
>not using an iterator
>>
>>53585813
not in this case though

see >>53585817
>>
how would you do this non recursively and still be faster then???
>>
>>53585860
Doing this in Java is a little unfair. There's enough overhead in the recursive function calls that it'd be pretty easy to get under that. Also in a language that actually wants you to use recursion things will be optimized to the point where a well-written recursive and a well-written iterative approach will both actually do the same things down on metal.
Come to think of it, how big are longs in Java and how big is the stack allowed to grow?
>>
>>53585839
Lists and trees are much better for introducing recursive thought. That's what we use at my university.

In particular, it leads naturally into the concept of tree folding since it's just an abstraction on top of manual recursion.

In general, data structures are the best approach to introducing structure, and algebraic data structures are the best data structures for introducing algebraic thought.
>>
>>53586001
>In general, data structures are the best approach to introducing structure, and algebraic data structures are the best data structures for introducing algebraic thought.
Which sounds entirely obvious - almost trivial - if you just read this sentence, really.
>>
>>53586013
>>53586001
sure, but teaching structures with structures requires some understanding of structures (this sounds stupid but whatever).

point being, if an instructor wants to teach recursion but wants the students to have a good appreciation of things like trees and stuff first, then that means delaying the instruction on recursion until after data structures are explained well enough.

basically this gets back to the pedagogy issue. maybe we need to completely restructure the way we teach CS so that some aspects of structures are taught, but not others, so students won't be completely lost and confused when you try to teach them recursion as a better way of chomping through a tree or something.
>>
>>53585839
My supreme example for recursion would be searching for a directory with a certain name/path.
That would be pretty dumb not to solve with recursion.

Or groups containing groups and you want to know all groups containing group X.
>>
>>53586072
I think the first and underlying principle for approaching high-level programming has to be the understanding of what it means to represent data.

Once you understand the essence of data itself, you can immediately grasp what it means to process data.
>>
>>53586146
Would be pretty dumb to do using recursion because it would make it more difficult to parallelize the task.
>>
>>53586146
This is a good example, and it's a good example precisely because ‘directories’ are an example of tree structures that most CS students will already have a solid intuition of.
>>
>>53586164
>Would be pretty dumb to do using recursion because it would make it more difficult to parallelize the task.
This is trivially and blatantly false.

Recursion makes it just as easy to parallelize - if not even easier. Besides, this is not a task I think of as immediately wanting to be parallelized. The disk is the bottleneck, not the CPU.

No point in parallelizing something that will only introduce additional seeking overhead as your contexts switch.
>>
>>53583295
not entirely sure of this...

first set a 'flag' to see if number is positive or negative.
if (n<0)
{f=-1;}
else
{f=1;}


then in return stmt of sumOfDigits
use Math.abs(n) instead of n and multiply it by f.
>>
>>53586162
yeah but getting people to this level definitely requires some time set aside in the curriculum. you may argue that courses should indeed start with this, but it's a little too nebulous and abstract to get people interested in continuing and taking more courses.

you have to understand that departments and major programs are entities with goals - instructors want the courses to be exciting and engaging and for more and more students to want to take the course. if a university only allocates proportionately to the number of students enrolled, then wooing more students means getting more funding for teaching and whatnot. to say nothing of the financial incentives, there's a prestige factor of having a popular program.

at my university fully 90% of the undergrads will have taken a CS course before graduating. that has a huge effect on the kind of funding and attention our department gets (i'm a phd student so this stuff doesn't affect me *as much*, but recruiting undergraduate research assistants is very different here than when it seemed to be at my undergrad university).
>>
>>53586183
Except when you have multiple disks and parallelization makes perfect sense.
>>
>>53586265
In real-world scenarios I think the important thing to realize is that education doesn't follow one ‘strand’. This might be where some high-level strand starts off, but at the same time you might have a networking class or low-level digital logic class or a practical java course or whatever.

Education of a field in general, I think, works best by starting off with concrete starting points and developing the student towards a point where all of these concrete and seemingly completely different starting points merge into one whole picture.

It's sort of like mathematics. A first-time mathematics student will just see a bunch of discrete topics and rules. They will not see all of the connections between them until later, when they have a more complete and full picture of the science as a whole.

It's at that moment where true scientific beauty tends to emerge - when you realize all the similarities, and start apply things you learned in one school to another.
>>
>>53586164
You have never tried to write parallel code in a modern language, did you?

public static Set<File> findDirectoriesWithName(String name, File startDirectory) {
int coreCount = Runtime.getRuntime().availableProcessors();
BlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(128);
ThreadPoolExecutor tpe = new ThreadPoolExecutor(coreCount, coreCount, 1, TimeUnit.DAYS, queue);

Set<File> result = Collections.newSetFromMap(new ConcurrentHashMap<File, Boolean>());
findDirectoriesWithNameInternal(name, startDirectory, tpe, result);

return result;

}

private static void findDirectoriesWithNameInternal(String name, File directory, ThreadPoolExecutor tpe, Set<File> foundDirectories) {
if (directory.getName().equals(name)) {
foundDirectories.add(directory);
}
for (File subDirectory : directory.listFiles()) {
if (subDirectory.isDirectory()) {
tpe.submit(() -> findDirectoriesWithNameInternal(name, subDirectory, tpe, foundDirectories));
}
}
}
>>
>>53586338
>Java
>Modern language
Holy shit that is some ugly concurrency. Please stop making my eyes bleed :(
>>
>>53586327
definitely. and bringing it all back to the beginning i think the easiest tangible example that professors can offer is a numerical example of recursion. it may benefit students to see a much more complex use of recursion just to be in awe of the kinds of stuff you can do with it, but numerical cases are simple, tangible examples of the basic premise of what recurring *means*.
>>
>>53586493
when i say "that professors can offer" i should have said something more like "the easiest thing that comes to mind". I think we're still figuring out the best practices for teaching CS, and i very much doubt that we have anything figured out at this point. as in, my hunch is that in 100 years almost everything we're doing now will look backwards and stupid.
>>
>>53583295
Use a language which isn't complete shit
>>
File: 1419247379844.png (27 KB, 407x446) Image search: [Google]
1419247379844.png
27 KB, 407x446
class sumOfDigitsThread extends Thread {
private long sum;
private String digits;

public sumOfDigitsThread(String s) {
this.digits = s;
}

public long getSum() {
return sum;
}

public String toString() {
return "Sum for digits " + digits + " = " + sum;
}

public void run() {
for( int i = 0; i < digits.length(); i++ ) {
sum += Character.getNumericValue(digits.charAt(i));
}
}
}

public class Main {
private static Set<Thread> makeThreads(String number, int threadNumber) {
Set<Thread> threads = new HashSet<Thread>();
for ( int i=0; i < threadNumber; i++) {
float beginIndex = number.length() * i / threadNumber;
float endIndex = number.length() * (i+1) / threadNumber;
String subNumber = number.substring( (int)beginIndex, (int)endIndex);
threads.add(new sumOfDigitsThread(subNumber));
}
return threads;
}

public static void main(String[] args) {
String number = "12345678";
int noOfThreads = 4;

Set<Thread> threads = makeThreads(number, noOfThreads);
for ( Thread thread : threads ) {
thread.run();
}

// >waiting for threads

long sum = 0;
for ( Thread thread : threads ) {
long partialSum = ((sumOfDigitsThread)thread).getSum();
System.out.println(thread);
sum += partialSum;
}
System.out.println("Total sum for digits " + number + " == " + sum);
}
}
>>
>>53583295
Math.abs
>>
>>53583295
>>53585498
>>53585677
>>53585714
>>53585787
This is monkey code. "Lisp schools" (the mainstream method of teaching with recursion and all that bullshit) don't teach anything about mathematics or algorithms.
>>
>>53589295
>This is monkey code.
Where's your solution, then?

Also how come you listed >>53585677 but not >>53585632 when the former is literally the latter except ignoring the existence of the library functions to do the same thing?
Thread replies: 52
Thread images: 4

banner
banner
[Boards: 3 / a / aco / adv / an / asp / b / biz / c / cgl / ck / cm / co / d / diy / e / fa / fit / g / gd / gif / h / hc / his / hm / hr / i / ic / int / jp / k / lgbt / lit / m / mlp / mu / n / news / o / out / p / po / pol / qa / r / r9k / s / s4s / sci / soc / sp / t / tg / toy / trash / trv / tv / u / v / vg / vp / vr / w / wg / wsg / wsr / x / y] [Home]

All trademarks and copyrights on this page are owned by their respective parties. Images uploaded are the responsibility of the Poster. Comments are owned by the Poster.
If a post contains personal/copyrighted/illegal content you can contact me at [email protected] with that post and thread number and it will be removed as soon as possible.
DMCA Content Takedown via dmca.com
All images are hosted on imgur.com, send takedown notices to them.
This is a 4chan archive - all of the content originated from them. If you need IP information for a Poster - you need to contact them. This website shows only archived content.