Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I really need help with this task here. Im stuck at it and I really would appreciate your help
Here is the task:
Give a recursive function r on A that reverses a string. For instance,
r(logikk) = kkigol and r(moro) = orom. (given that A the amount of
letters in the Norwegian alphabet which has 29 letters.). Define the
function in such a way that it is correctly regardless of what A are.
Also logikk means logic in norwegian, and moro means fun in norwegian in case you're wondering.
I've tried to google on how I can solve tasks like this, but I had no luck. I hope I can get the help I need here.
Thanks a lot.
Here's a hint:
Define a function that takes a string argument.
If that argument is an empty string, return it. (Hint: this is not the best base case.)
Otherwise, return the last character of the string concatenated onto … what?
What is recursion?
If you think about the two questions here, you will have the answer.
(This answer is an attempt to stick to the spirit of https://meta.stackexchange.com/questions/10811/how-do-i-ask-and-answer-homework-questions/10812#10812.)
Here is the algorithm. I hope it would help you.
public String r(String str){
if(str.length() <= 1){
return str;
} else {
String reverse += str.charAt(str.length()-1)
+ r(str.substring(0,str.length()-1));
return reverse;
}
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
In my app, a user can fill out certain information about him on his profile. For example I have an about section, where the user can write a paragraph about his life. Right now, if the user types anything and saves the input, it is shown as one paragraph. I want it so that if the user hits enter, it should add a <p> tag when it is displaying the content.
Update
Just look at this question for example. When I type a question and hit enter
this text appeared on a new line
this is what I want!
You dont have to handle enter key.
Lets assume you are getting textarea value as a string str.
when you display it, just wrap every line with <p>
//`str` is textarea value
var str = document.getElementById("myTextarea").value;
var lines = str.split(/\r?\n/);
// create html
var html="";
for(var i=0;i<lines.length;i++){
html+='<p>'+lines[i]+'</p>';
}
// use html here showing inside some div
var divEl = document.getElementById("myDiv");
divEL.innerHTML = html;
I don't know what you are exactly asking for, but you can intercept the Enter key on inputs by doing such (with jquery).
$(".yourinputid").keyup(function (e) {
if (e.keyCode == 13) {
// Manipulate the DOM
}
});
I'm a bit confused about the <p> tag part. What do you want exactly to do?
Use nl2br() on POST value server-side (if on PHP; equivalents in other languages should be avaliable) or String.replace() on the textarea value client-side.
my code is long but i think my question is simple: How can i build a google GUI to show a grid of multiple groups of radio buttons.
in essence, i want to build something that is like:
Jane Smith:
Question 1: radio1, radio2, radio3, radio4
Question 2: radio1, radio2, radio3, radio4
John Doe:
Question 1: radio1, radio2, radio3, radio4
Question 2: radio1, radio2, radio3, radio4
etc.etc...
I have the whole code written to dynamically create the page and all the nested for loops for the logic to read each group of radio buttons back out into an array after the user submits to then be able to parse and have my way with it.
But how do i get the variables of the radio buttons themselvse?
the solutions here seem overly complicated as it is about 10 lines of code that would need to be injected into each layer of my 3 layer deep for loops to make that work, i think. unless i'm thinking about it wrong.
RadioButtons must have the same name (be part of the same group) to work as expected (exclusive-OR) so the solution to assign a client handler to each of them that sets a value to a hidden widget (or a textBox) is, AFAIK, the only working solution if you're not using a form.
The code is not so complicated and in your case it will be the same for each question so you could easily implement it in your code.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
What are some clever uses for infinite generators? I've seen lots of seemingly trivial examples like "list all even numbers", but I assume there must be others that have more applicability to real-world scenarios. Concrete examples (in any language that support generators) appreciated!
I'll give a trivial sample as an answer.
Look at the Haskell code on http://rosettacode.org/wiki/Hamming_numbers#Haskell; that uses lazy lists (which are somewhat like generators) in a creative way to list all Hamming numbers.
A random generator might be considered clever use.
Trivial example: yield Fibonacci numbers one at a time (sans overflow checking, in C#):
public static IEnumerable<double> Fibonacci()
{
double n_minus2 = 1;
double n_minus1 = 1;
yield return n_minus2;
yield return n_minus1;
while(true)
{
double n = n_minus2 + n_minus1;
yield return n;
n_minus2 = n_minus1;
n_minus1 = n;
}
}
In the case of languages that support single decision and action without brackets, such as the following example:
if (var == true)
doSomething();
What is the preferred way of writing this? Should brackets always be used, or should their usage be left as a preference of the individual developer? Additionally, does this practice depend on the size of the code block, such as in the following example:
if (var == 1)
doSomething(1);
else if (var > 1 && var < 10)
doSomething(2);
else
{
validate(var);
doSomething(var);
}
There isn't really a right answer. This is what coding standards within the company are for. If you can keep it consistent across the whole company then it will be easy to read. I personally like
if ( a == b) {
doSomething();
}
else {
doSomething();
}
but this is a holy war.
I recommend
if(a==b)
{
doSomething();
}
because I find it far easier to do it up-front than to try to remember to add the braces when I add a second statement to to success condition...
if(a==b)
doSomething();
doSomethingElse();
is very different to
if(a==b)
{
doSomething();
doSomethingElse();
}
see Joel's article for further details
I tend to use braces at all times. You can get some subtle bugs where you started off with something like:
if(something)
DoOneThing();
else
DoItDifferently();
and then decide to add another operation to the else clause and forget to wrap it in braces:
if(something)
DoOneThing();
else
DoItDifferently();
AlwaysGetsCalled();
AlwaysGetsCalled() will always get called, and if you're sitting there at 3am wondering why your code is behaving all strange, something like that could elude you for quite some time. For this reason alone, I always use braces.
My preference is to be consistent, e.g., if you use brackets on one block, use brackets all throughout even with just one statement:
if (cond1)
{
SomeOperation();
Another();
}
elseif (cond2)
{
DoSomething();
}
else
{
DoNothing();
DoAnother();
}
But if you have just a bunch of one liners:
if (cond1)
DoFirst();
elseif (cond2)
DoSecond();
else
DoElse();
Looks cleaner (if you don't mind the dummy method names ;) that way, but that's just me.
This also applies to loop constructs and the like:
foreach (var s as Something)
if (s == someCondition)
yield return SomeMethod(s);
You should also consider that this is a convention that might be more suited to .NET (notice that Java peepz like to have their first curly brace in the same line as the if).
Chalk this one to lack of experience, but during my seven-year stint as a code monkey I've never actually seen anyone make the mistake of not adding braces when adding code to a block that doesn't have braces. That's precisely zero times.
And before the wisecrackers get to it, no, the reason wasn't "everyone always uses braces".
So, an honest question -- I really would like to get actual replies instead of just downvotes: does that ever actually happen?
(Edit: I've heard enough outsourcing horror stories to clarify a bit: does it ever actually happen to competent programmers?)
It doesn't really matter, as long as you're consistent with it.
There does seem to be a tendency to demand sameness within a single statement, i.e. if there's brackets in one branch, there's brackets everywhere. The Linux kernel coding standards, for one, mandate that.
I would strongly advocate always using braces, even when they're optional. Why? Take this chunk of C++ code:
if (var == 1)
doSomething();
doSomethingElse();
Now, someone comes along who isn't really paying enough attention and decides that something extra needs to happen if (var == 1), so they do this:
if (var == 1)
doSomething();
doSomethingExtra();
doSomethingElse();
It's all still beautifully indented but it won't do what was intended.
By always using braces, you're more likely to avoid this sort of bug.
I personnally side with McConnell's explanation from Code Complete.
Use them whenever you can. They enhance your code's readability and remove the few and scarce confusions that might occur.
There is one thing that's more important though....Consistency. Which ever style you use,make sure you always do it the same way.
Start writing stuff like:
If A == true
FunctA();
If B == "Test"
{
FunctB();
}
You are bound to end up looking for an odd bug where the compiler won't understand what you were trying to do and that will be hard to find.
Basically find the one you are comfortable writing everytime and stick to it. I do believe in using the block delimeters('{', '}') as much as possible is the way to go.
I don't want to start a question inside another, but there is something related to this that I want to mention to get your mental juices going. One the decision of using the brackets has been made. Where do you put the opening bracket? On the same line as the statement or underneath. Indented brackets or not?
If A == false {
//calls and whatnot
}
//or
If B == "BlaBla"
{
//calls and whatnot
}
//or
If C == B
{
//calls and whatnot
}
Please don't answer to this since this would be a new question. If I see an interest in this I will open a new question your input.
I've always used brackets at all times except for the case where I'm checking a variable for NULL before freeing it, like is necessary in C
In that case, I make sure it's clear that it's a single statement by keeping everything on one line, like this:
if (aString) free(aString);
There is no right or wrong way to write the above statement. There are plenty of accepted coding styles. However, for me, I prefer keeping the coding style consist throughout the entire project. ie. If the project is using K&R style, you should use K&R.
Ruby nicely obviates one issue in the discussion. The standard for a one-liner is:
do_something if (a == b)
and for a multi-line:
if (a == b)
do_something
do_something_else
end
This allows concise one-line statements, but it forces you to reorganize the statement if you go from single- to multi-line.
This is not (yet) available in Java, nor in many other languages, AFAIK.
As others have mentioned, doing an if statement in two lines without braces can lead to confusion:
if (a == b)
DoSomething();
DoSomethingElse(); <-- outside if statement
so I place it on a single line if I can do so without hurting readability:
if (a == b) DoSomething();
and at all other times I use braces.
Ternary operators are a little different. Most of the time I do them on one line:
var c = (a == b) ? DoSomething() : DoSomethingElse();
but sometimes the statements have nested function calls, or lambda expressions which
make a one-line statement difficult to parse visually, so I prefer something like this:
var c = (a == b)
? AReallyReallyLongFunctionName()
: AnotherReallyReallyLongFunctionOrStatement();
Still more concise than an if/else block but easy to see what's going on.
Sun's Code Conventions for the Java programming Language has this to say:
The if-else class of statements should
have the following form:
if (condition) {
statements;
}
if (condition) {
statements;
} else {
statements;
}
if (condition) {
statements;
} else if (condition) {
statements;
} else {
statements;
}
Our boss makes us put { } after a decision statement no matter what, even if it's a single statement. It's really annoying to add two extra lines. The only exception is ternary operators.
I guess it's a good thing I have my code monitor in portrait orientation at 1200x1600.
I prefer
if (cond)
{
//statement
}
even with only a single statement. If you were going to write something once, had no doubts that it worked, and never planned on another coder ever looking at that code, go ahead and use whatever format you want. But, what does the extra bracketing really cost you? Less time in the course of a year than it takes to type up this post.
Yes, I like to indent my brackets to the level of the block, too.
Python is nice in that the indentation defines the block. The question is moot in a language like that.
I tend to agree with Joel Spolsky on that one with that article (Making Wrong Code Look Wrong) with the following code example :
if (i != 0)
bar(i);
foo(i);
Foo is now unconditionnal. Wich is real bad!
I always use brackets for decision statements. It helps code maintainability and it makes the code less bug prone.
I use curly braces around every statement if and only if at least one of them requires it.
In Perl if you are doing a simple test, sometime you will write it in this form:
do_something if condition;
do_something unless condition;
Which can be really useful to check the arguments at the start of a subroutine.
sub test{
my($self,#args) = #_;
return undef unless defined $self;
# rest of code goes here
}
The golden rule is that, when working in an existing project, follow those coding standards.
When I'm at home, I have two forms.
The first is the single line:
if (condition) doThis();
and the second is for multiple lines:
if (condition) {
doThis();
}
I used to follow the "use curly braces always" line like an apparatchik. However, I've modified my style to allow for omitting them on single line conditional expressions:
if(!ok)return;
For any multistatement scenario though I'm still of the opinion that braces should be mandatory:
if(!ok){
do();
that();
thing();
}