• 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

You should see what sort of string getImage() is returning. It should return the name of the image along with the file extension like "axe.png".

Also is the exception something like "File not found". Its always good to fully check the error log it throws.
 

Hylian7

Member
You should see what sort of string getImage() is returning. It should return the name of the image along with the file extension like "axe.png".

Also is the exception something like "File not found". Its always good to fully check the error log it throws.

I've checked what it returns, it does return the filename with extension.

Also here's the output of the Exception:

Code:
Exception in thread "main" javax.imageio.IIOException: Can't read input file!
	at javax.imageio.ImageIO.read(Unknown Source)
	at main.WindowDriver.setup(WindowDriver.java:50)
	at main.BackEnd.draft(BackEnd.java:143)
	at main.DotaDraftingDriver.main(DotaDraftingDriver.java:8)
 

Hylian7

Member
I'm an idiot and figured it out.

The real problem was it was getting hung up on the filename I had in the Hero object not matching the file name. Specifically, I forgot to rename Clockwerk's image to "clockwerk.png", instead of "rattletrap.png" as it was saved from the website.

I hate it when stupid things like that hang me up.

C41Zod6.jpg

Now I obviously have to fix the GUI the rest of the way, but I got past that stumbling block, finally.
 

jdavid459

Member
Hey guys -

So I have an idea I'd like to try out. Thing is...it seems insanely daunting for someone like me with little programming knowledge. I've been teaching myself Python for a few weeks now, and half assed a college course in Java awhile ago. I want to basically create a fantasy-football esque program that tracks users/statistics/supports user interaction with lots of variables. It wouldn't be for football, but for other interests...if that makes any sense.

Is that something I should even both attempting?

thanks.
 
Hey guys -

So I have an idea I'd like to try out. Thing is...it seems insanely daunting for someone like me with little programming knowledge. I've been teaching myself Python for a few weeks now, and half assed a college course in Java awhile ago. I want to basically create a fantasy-football esque program that tracks users/statistics/supports user interaction with lots of variables. It wouldn't be for football, but for other interests...if that makes any sense.

Is that something I should even both attempting?

thanks.

Sure - that's the best way to begin learning programming, in my opinion. To have something you want to make, and then dive in and start learning whatever you need to do it. It'll be a challenge, but if you keep at it and ask questions you can definitely do it.
 

jdavid459

Member
Sure - that's the best way to begin learning programming, in my opinion. To have something you want to make, and then dive in and start learning whatever you need to do it. It'll be a challenge, but if you keep at it and ask questions you can definitely do it.

That's good to hear. Just in the beginning stages at the moment, should I just try to get a basic grasp of programming? To be honest I'm pretty lost and don't know how much work will be web development, how much is programming, what the difference is, ect. Currently using codeacademy for Python...seems pretty good so far.
 

Hylian7

Member
Aaaaand I hate Swing (Java GUI classes). I was doing this in GridLayout only to find out that I needed to use GridBagLayout...
 

Tristam

Member
On second thought, I'll wait until I can take a closer look over your code before responding.

Thank you for checking it out -- I did find out that the secret lies in invoking the setRootIndex() method on the data mapper object, passing to it the current item's parent node. (Doing so resolves overlap between index row values.) I had tried using it before but wasn't implementing it correctly.

That's good to hear. Just in the beginning stages at the moment, should I just try to get a basic grasp of programming? To be honest I'm pretty lost and don't know how much work will be web development, how much is programming, what the difference is, ect. Currently using codeacademy for Python...seems pretty good so far.

I believe you should. If you're lost now, then you ought to continue with a beginner's book and/or guide until you can do something like, say, a genuine hangman game on a command-line interface. I agree with the other poster who replied to you that the best way to learn is to think of a cool idea you want to write in code and then implement it--but if you dive in head-first with zero or little base knowledge, it will be a frustrating experience I think.

Web development--at least the kind that isn't just static HTML/CSS pages--is programming. The HTML/CSS (and JavaScript if you so choose) is always used to display the front end, but you're gonna have to store all those user statistics in a (presumably relational) database. Popular open-source relational databases include MySQL and PostgreSQL. You'll need to at least learn the basics of how these relational databases work; fortunately, learning the basics of the language used to query data (that is, SQL) is very easy. But to implement those queries on a webpage, you need a scripting language (like Python, or PHP, or Perl, etc...if you're not using PHP, which was explicitly made for Web programming, you'll probably want learn how to use a Web framework, like Django for Python) as a sort of intermediary between your front-end (your HTML/CSS stuff) and your back-end (your database). The scripting language is the vehicle by which you allow users to fetch data, create new data, modify existing data, etc. These ideas together are the heart of what makes a dynamic website dynamic and not just a static collection of HTML/CSS pages.

The last thing you would want to learn is at least the very basics of installing and configuring Web server software. Apache is a very popular choice.

I would continue sticking to learning how to code on the command line if I were you. Then I would
1. learn the basics of a relational database like MySQL
2. install the MySQL server software on your computer, and then try to use Python's MySQL module to design a (command line) Python program in which you can perform the traditional database functions -- reading, creating, updating, and deleting data -- in your program.
3. learn how to use a Web framework (like Django for Python) or learn PHP, and try designing that same program in step 2 as something accessible from the web browser rather than command line environment. Of course this will require you to...
4. install Web server software (like Apache) on your computer (the localhost), and do the bare minimum configuration of it in order for your website to work.

A dynamic website is a piece of machinery with more than one or two parts. You don't necessarily need to have advanced knowledge of all those parts just to make one, but you will need to know the basics at least. Don't be too intimidated, though -- I'm still a novice (just started learning Python as my first language myself about 13 months ago) -- but after six or seven months of self-study I was comfortable creating my own dynamic website.
 

Granadier

Is currently on Stage 1: Denial regarding the service game future
What you're doing now with the Dog class is pretty useless since it really just changes the frame's display value. You're not really doing anything with the dog, in other words.

You should create a dog along with useful properties.

Thanks for clarifying this. It works much better now.

Aaaaand I hate Swing (Java GUI classes). I was doing this in GridLayout only to find out that I needed to use GridBagLayout...

I am growing to hate it as well. What is your end goal for that Dota program?
 

Hylian7

Member
Thanks for clarifying this. It works much better now.



I am growing to hate it as well. What is your end goal for that Dota program?

Basically it's a drafting game sort of like this: http://dota2draft.the-cluster.org/

But it's a desktop client meant for hotseat play. Online play might come later, but I plan to make it into and android app after the Desktop version is finished.

The reason I found out GridLayout sucks for this is that I wanted to make the buttons to be exactly the size of the pictures, and GridLayout won't let you do that apparently.
 

Exuro

Member
Having trouble using execvp.

char* args[1] = {"ls");

execvp(args[0], args);


I'm just trying to get it to work. If I do this it says ls not found, yet it runs fine for my roomate. The only way I can get it to work is to increase the element count on args. Any ideas?

EDIT: I figured out the issue but I have no idea why it fixed it. I call fork and put exec in the child process. I have a linked list that i'll transfer data to the args and for some reason if I move the code that deletes the linked list to before the fork it works, but if I do it afterwards I get the errors.
 

Granadier

Is currently on Stage 1: Denial regarding the service game future
Basically it's a drafting game sort of like this: http://dota2draft.the-cluster.org/

But it's a desktop client meant for hotseat play. Online play might come later, but I plan to make it into and android app after the Desktop version is finished.

The reason I found out GridLayout sucks for this is that I wanted to make the buttons to be exactly the size of the pictures, and GridLayout won't let you do that apparently.

Cool deal. Good luck with the program.

Try setting your button size manually to the size of the pictures, then have the GridLayout specify a gap between the buttons if needed.
 

OceanBlue

Member
How extensive is the average college grad's understanding of software design, and how important is it?

I'm taking a special topics elective course called Object-Oriented Programming and I feel as if this is the first time I've ever been taught anything about designing software. It's as if all my other classes just dumped concepts like classes and algorithms on me and I just threw stuff at my code. We've had to do large projects in previous classes as well and groups would always get lost in a mess of references and coupled classes to where only two or three people could keep track of what different parts of the software did. Honestly, this class feels way too important to be optional (and only taught every other semester in my university) and I can't believe some of my friends aren't taking it. We've been taught about things like encapsulation and information hiding, but I at least only learned what they meant and not how to use them.

Am I just putting too much value in this class? Or is this something most students in other universities learn and mine is just failing? I don't have any real-world experience so I don't have a good frame of reference (I've been looking for an internship, but no luck so far). Due to this class, I also feel obligated to take Design Patterns before I graduate even though I can graduate without it. I feel like these classes are what I've been wanting to learn all throughout college.
 

jdavid459

Member
I believe you should. If you're lost now, then you ought to continue with a beginner's book and/or guide until you can do something like, say, a genuine hangman game on a command-line interface. I agree with the other poster who replied to you that the best way to learn is to think of a cool idea you want to write in code and then implement it--but if you dive in head-first with zero or little base knowledge, it will be a frustrating experience I think.

Web development--at least the kind that isn't just static HTML/CSS pages--is programming. The HTML/CSS (and JavaScript if you so choose) is always used to display the front end, but you're gonna have to store all those user statistics in a (presumably relational) database. Popular open-source relational databases include MySQL and PostgreSQL. You'll need to at least learn the basics of how these relational databases work; fortunately, learning the basics of the language used to query data (that is, SQL) is very easy. But to implement those queries on a webpage, you need a scripting language (like Python, or PHP, or Perl, etc...if you're not using PHP, which was explicitly made for Web programming, you'll probably want learn how to use a Web framework, like Django for Python) as a sort of intermediary between your front-end (your HTML/CSS stuff) and your back-end (your database). The scripting language is the vehicle by which you allow users to fetch data, create new data, modify existing data, etc. These ideas together are the heart of what makes a dynamic website dynamic and not just a static collection of HTML/CSS pages.

The last thing you would want to learn is at least the very basics of installing and configuring Web server software. Apache is a very popular choice.

I would continue sticking to learning how to code on the command line if I were you. Then I would
1. learn the basics of a relational database like MySQL
2. install the MySQL server software on your computer, and then try to use Python's MySQL module to design a (command line) Python program in which you can perform the traditional database functions -- reading, creating, updating, and deleting data -- in your program.
3. learn how to use a Web framework (like Django for Python) or learn PHP, and try designing that same program in step 2 as something accessible from the web browser rather than command line environment. Of course this will require you to...
4. install Web server software (like Apache) on your computer (the localhost), and do the bare minimum configuration of it in order for your website to work.

A dynamic website is a piece of machinery with more than one or two parts. You don't necessarily need to have advanced knowledge of all those parts just to make one, but you will need to know the basics at least. Don't be too intimidated, though -- I'm still a novice (just started learning Python as my first language myself about 13 months ago) -- but after six or seven months of self-study I was comfortable creating my own dynamic website.

I can't thank you enough man, what a very well thought out post. Saved it and will refer back to it on my journey. Glad to hear this is in fact doable. Hopefully I learn a lot on the way and stick with it. Thanks again.
 

tokkun

Member
Thanks for the replies. I guess I'm a bit confused then on how to go about solving this. Is calloc itself just setting aside memory for the list, but I never actually "made" the list? Also, in terms of dereferencing list, how would I go about getting the text information from each node if my current approach is causing segmentation faults?

I suppose I'm just stumped at this point, this is my first time using this kind of memory allocation in C so I appreciate the help.

Edit: Also, this wasn't listed in my original code post, but the helper function createNode will use a malloc for both the node itself as well as the text field for the node.


You are attempting to use a dynamically allocated array of node pointers:

Code:
Node** list;

Your first memory allocation allocates space for the array. Since you are using calloc, it also initializes all the data to zero.

Code:
list = (Node**) calloc(num_elements * sizeof(Node*));

And the contents of list look like:

Code:
{0, 0, 0, 0, 0, 0, 0, ..., 0}

Those are all NULL pointers. You can't do anything with them, because they point to nothing.

If you want to store nodes in the list, you need to replace the null pointers with Node pointers that point to valid memory.

It's up to you whether you want to do this in advance:

Code:
for (int i = 0; i < num_elements; ++i) {
  list[i] = malloc(sizeof(Node));
  // Add some guard value into the Node so you know it is empty.
}

or do it on demand:

Code:
int next_free_node_index = 0;

// Do some stuff until you decide you need a new node.
list[next_free_node_index++] = CreateNode(/* some args */);

...

Node* CreateNode(/* some args */) {
  Node* ptr = malloc(sizeof(Node));
  // Populate node data through ptr from args
  return ptr;
}
 
How extensive is the average college grad's understanding of software design, and how important is it?

From my experience very few graduates will understand design patterns or will even know they exist. If you do study it, you will be ahead of the curve and would be a much more valuable hire to somebody like me.

Essentially it is the difference between somebody who knows how to code and somebody who knows how to code a commercial bit of software. There is actually quite a big difference in approach and that will be what you start to learn as you enter the workforce.
 

iapetus

Scary Euro Man
Basically it's a drafting game sort of like this: http://dota2draft.the-cluster.org/

But it's a desktop client meant for hotseat play. Online play might come later, but I plan to make it into and android app after the Desktop version is finished.

The reason I found out GridLayout sucks for this is that I wanted to make the buttons to be exactly the size of the pictures, and GridLayout won't let you do that apparently.

So use FlowLayout.

GridBagLayout is almost always a bad idea. If you're using GridBagLayout you're probably doing it wrong.
 

BreakyBoy

o_O @_@ O_o
From my experience very few graduates will understand design patterns or will even know they exist. If you do study it, you will be ahead of the curve and would be a much more valuable hire to somebody like me.

Essentially it is the difference between somebody who knows how to code and somebody who knows how to code a commercial bit of software. There is actually quite a big difference in approach and that will be what you start to learn as you enter the workforce.

I'm kind of amazed this isn't taught as a requirement. For a multitude of reasons (several being my own damned fault) I never got past the Junior level of programming courses at any university I attended. I've just gone straight into the work force, and for what it's worth I've done alright for myself and have received nothing but compliments from my team leads and peers.

That being said, aside from some inexperience with some algorithms to solve some common problems, design patterns was one of those thing I only had a vague awareness of, never mind any real familiarity with it. It's been something I've had to learn on the job, and I always just assumed it was one of those things I missed out on by not finishing my coursework before entering the workforce.

I'm just really amazed that it isn't a normal requirement for CS. In my experience, it really does seem to be applicable all the damned time.
 

Water

Member
I'm just really amazed that it isn't a normal requirement for CS. In my experience, it really does seem to be applicable all the damned time.
Out of curiosity, which individual design patterns do you find the most useful?

In programming education I'm kind of sceptical towards object oriented programming, and by extension, design patterns. Not that it's bad to be good at these things, I just suspect they are taught too early and given too much weight.
 
how do you keep your 'knife sharp'? Job pretty much is ducktaping hacks onto old complicated shitty code with minimal refactoring room. More than once I caught myself (or a coworker did) kinda emulating the shitty code style when implementing new features >.<
 
Hello!

Any C buff around here can help me go through code for a C program and help me translate it to python?

I just need information on what the program is doing so that I can rewrite it python!

I can't post code spinets here since the code comes with a scientific package and I'm afraid it may be copyrighted to the company!

So if you have time to go through 100 lines of simple code that takes a binary file and outputs a ascii text file, I would be very happy!

Please send me a PM if you are able and willing! I'll explain further then!
 

BreakyBoy

o_O @_@ O_o
Out of curiosity, which individual design patterns do you find the most useful?

Observer and Producer/Consumer are the two that immediately sprung to mind, as they are (at least two of) the ones that I've been using in my work projects in the last two years.

But I will point out that, like algorithms, a data pattern's usefulness is intrinsically dependent on the problem you're trying to solve. As such, I'd expect you'd get wildly different answers from everyone else here. I can also easily imagine there would be many who might say "none".

Not to mention that I've only been at this (professionally) for about two years. I'm still learning.

In programming education I'm kind of sceptical towards object oriented programming, and by extension, design patterns. Not that it's bad to be good at these things, I just suspect they are taught too early and given too much weight.

I take it then that in your experience design patterns are emphasized, perhaps overly so? I guess that just reflects a wider variance in curriculum for a CS degree than I would have expected.

Considering I still want to finish my degree at some point, and I have to decide where to do so, this is something to think about when I make my decision.
 

tokkun

Member
Out of curiosity, which individual design patterns do you find the most useful?

In programming education I'm kind of sceptical towards object oriented programming, and by extension, design patterns. Not that it's bad to be good at these things, I just suspect they are taught too early and given too much weight.

Here are the things I would have liked to have been taught, in that they are both very useful and are not obvious extensions of the basic concepts of object oriented programming:

Dependency Injection - Specifically in the context of mock objects and unit testing. I think it is important for students to get experience with design for testability, and this is probably the most significant DFT concept in OO languages.

Resource Allocation is Initialization / Dispose Pattern - Probably the most important pattern in terms of avoiding software defects. Even in exception-free code, RAII can be really for functions with multiple exit points.

Callbacks/Continuations - Extremely useful in many forms: decoupled communication (Observer pattern), delegation (Event Handler pattern), and asynchronous interfaces.
 

BreakyBoy

o_O @_@ O_o
Speaking of design patterns and algorithms, anyone have any suggestions for books on either topic? I know the classics for design patterns are Code Complete and Design Patterns (by the Gang of Four), but are there any others you guys have liked for either patterns or algorithms?

Work/life balance doesn't leave much room at the moment for going back to school, so anything I can use in the interim would be helpful.
 
Introduction to Algorithms 3rd edition (CLRS) from MIT is a great book my data structures and algorithms classes used and it was pretty solid. All the pseudocode basically translated to Python with minimal effort which was nice and fairly in depth.
 

kingslunk

Member
how do you keep your 'knife sharp'? Job pretty much is ducktaping hacks onto old complicated shitty code with minimal refactoring room. More than once I caught myself (or a coworker did) kinda emulating the shitty code style when implementing new features >.<

I try and write good code outside of work. I essentially do the same thing as you at work.
 

Linkhero1

Member
Java question

I have a string called text. I want to create a function that removes the middle letter of text. If text divides evenly, I want it to remove the two middle letters. If it divides oddly, I want to remove the single middle letter. This is fairly simple with an if statement, but how would I do this without an if statement?

I can't wrap my mind around it for some reason.

Code:
String text;

public void removeMid() {

     this.text = ?

}

if text is "hello", removeMid would make text "helo"
if text is "person", removeMid would make text "peon"

so on and so forth.
 
Java question

I have a string called text. I want to create a function that removes the middle letter of text. If text divides evenly, I want it to remove the two middle letters. If it divides oddly, I want to remove the single middle letter. This is fairly simple with an if statement, but how would I do this without an if statement?

I can't wrap my mind around it for some reason.

Code:
String text;

public void removeMid() {

     this.text = ?

}

if text is "hello", removeMid would make text "helo"
if text is "person", removeMid would make text "peon"

so on and so forth.
Not sure why you wanna do it without using if-statements, but maybe something like this? (I haven't tried if this works, fyi)

Edit: Nvm, I was thinking about using modulo but can't figure out how. Again, why not use if-statements? It would probably create much more understandable code. You could use the ternary operator, but I assume you don't want that either.
 

upandaway

Member
I don't really remember, but I think dividing two ints makes an int (rounding down)? If so, can you use a substring like this?

Code:
substring( text.length() / 2 , text.length() - (text.length() / 2) )

Or whatever the math is, so that if the string is has a middle char, it would be the same number, but if the string has two middle characters, it would give those two indexes.

edit: hmm, i think the math works technically, but the way substring uses indexes makes it annoying. maybe some other string method, dunno
 

usea

Member
Break the problem down even further. You want to find a pair of integer midpoints given a length. If the length is even, the midpoints should be 1 apart, and if the length is odd the midpoints should be the same.

Then use your two midpoints and take the left side of the string (beginning to left-midpoint), and the right side (right midpoint until end), and combine them to get your result.

This approach (always having two midpoints) allows you to avoid the if statement. You don't have to do either 1 or 2 substring operations; you always do two.

(your if statement really just moved into the Math library, but that's an arbitrary restriction anyway)

Code:
public static String removeMiddle(String s) {
    double mid = s.length() / 2.0;
    int leftEnd = (int)Math.floor(mid - 0.1);
    int rightEnd = (int)Math.ceil(mid + 0.1);
    String left = s.substring(0, leftEnd);
    String right = s.substring(rightEnd, s.length());
    return left + right;
}
I'm sure there are other (better) ways of finding the two midpoints. This is just what came to mind first. My midpoints are either 1 or 2 apart, instead of 0 or 1. You can do it either way (replace the ceil with floor), but I chose 1 and 2 to make the substrings more clear.

Looking at examples of lengths 5 and 6:
5 / 2.0 = 2.5
2.5 - 0.1 = 2.4
Math.floor(2.4) = 2.0
2.5 + 0.1 = 2.6
Math.ceil(2.6) = 3.0

6 / 2.0 = 3.0
3.0 - 0.1 = 2.9
Math.floor(2.9) = 2.0
3.0 + 0.1 = 3.1
Math.ceil(3.1) = 4.0
 

upandaway

Member
Eh, there's no need to use Math. I tried running what I said above and it works (basically the same thing you did):

Code:
String s = text.substring(0, text.length() - text.length() / 2 - 1) + text.substring(text.length() / 2 + 1, text.length());
 

usea

Member
That version is better since we'll never have negatives. Yours implicitly casts to int, which is the same as Math.floor except for negatives.
 

upandaway

Member
You mean in the case of an empty string? I'm pretty sure (int)Math.floor(-0.1) rounds down to -1...

Yep, ran it (also ran your code with an empty string to be safe, it gives an error). Can't call absolute on it, either.. any ways to handle an empty string besides an if statement?
 

usea

Member
No, I mean negatives. The only difference between Math.floor and casting to int is for negatives (and performance). So our versions are equivalent since length will never be negative. So there's no real reason to use Math.
 

Granadier

Is currently on Stage 1: Denial regarding the service game future
Code:
public static String removeMiddle(String s) {
    double mid = s.length() / 2.0;
    int leftEnd = (int)Math.floor(mid - 0.1);
    int rightEnd = (int)Math.ceil(mid + 0.1);
    String left = s.substring(0, leftEnd);
    String right = s.substring(rightEnd, s.length());
    return left + right;
}

Very ingenious way of solving that problem.
I don't think I would have thought of using a midpoint + floor/ceiling to get the substrings.

Oh I misunderstood what you said first. Oops~

Trying to find a way to handle an empty string but I'm stumped.

You mean without using an if/else statement?
 

iapetus

Scary Euro Man
You mean without using an if/else statement?

If we're still allowing Math calls:

String s = text.substring(0, Math.max(0, text.length() - text.length() / 2 - 1)) + text.substring(Math.min(text.length(), text.length() / 2 + 1), text.length());

Math.max almost certainly uses if, though. So this is almost certainly cheating.
 

Hylian7

Member
Why does he have to do it without if/else statements? That seems like a silly constraint.

That would be like asking you to do some algorithm like Fibonacci without variables.
 

Granadier

Is currently on Stage 1: Denial regarding the service game future
If we're still allowing Math calls:

String s = text.substring(0, Math.max(0, text.length() - text.length() / 2 - 1)) + text.substring(Math.min(text.length(), text.length() / 2 + 1), text.length());

Math.max almost certainly uses if, though. So this is almost certainly cheating.

Would you mind explaining what that line is doing?

Why does he have to do it without if/else statements? That seems like a silly constraint.

That would be like asking you to do some algorithm like Fibonacci without variables.

He may just be doing it for the fun. Just to see if it's possible.

Wait, it's really simple! Solution coming in a minute...

I'm waiting with bated breath.
 

iapetus

Scary Euro Man
Would you mind explaining what that line is doing?

Exactly the same as the previous version, but it's using Math.min and Math.max to clamp the top and bottom ends of the substring to the size of the string.

Another cheaty way to do it is simply wrap the whole thing in a try/catch block and output "" if we get an exception. :)

Unfortunately the simple solution I had just leads to a similar but different problem.
 

usea

Member
You can use a lookup table (or equivalent) for the length of the string. For example make a repeating iterable containing just [0,1] over and over. Then grab the element at the length of the word. Use that to pick whether your second midpoint should be the same as the left midpoint, or one greater.
 

iapetus

Scary Euro Man
Done it, I think.

String s = text.substring(0, text.length() - text.length() / 2 - (text.length() * 2 / (text.length() + 1))) + text.substring(text.length() / 2 + (text.length() * 2 / (text.length() + 1)));

And if you understand how that works, you've got a sicker mind than me. :D
 

Linkhero1

Member
It's not as simple as I thought it would be. Thank you for all your replies. In this case, we don't bother checking for an empty string. I don't have an IDE installed at my work computer I'm currently using but I will check the solutions here once I'm home. upandaway's solution looks the cleanest. I was trying to avoid using the Math library.

Not sure why you wanna do it without using if-statements, but maybe something like this? (I haven't tried if this works, fyi)

Edit: Nvm, I was thinking about using modulo but can't figure out how. Again, why not use if-statements? It would probably create much more understandable code. You could use the ternary operator, but I assume you don't want that either.

It was a brain teaser thrown my way. I'm trying to get a better grasp on things.

Done it, I think.

String s = text.substring(0, text.length() - text.length() / 2 - (text.length() * 2 / (text.length() + 1))) + text.substring(text.length() / 2 + (text.length() * 2 / (text.length() + 1)));

And if you understand how that works, you've got a sicker mind than me. :D

My head hurts just looking at it!

Edit: I'm really trying to understand this solution but I become scatterbrained midway through the first substring lol.
 

iapetus

Scary Euro Man
It was a brain teaser thrown my way. I'm trying to get a better grasp on things.

It's possible that there's a looping way of doing it that they had in mind.

Code:
    StringBuilder firstHalf = new StringBuilder();
    StringBuilder secondHalf = new StringBuilder();
    for (int i = 0; i < (text.length() - 1) / 2; i++) {
      firstHalf.append(text.charAt(i));
      secondHalf.append(text.charAt(text.length() - i - 1));
    }
    String s2 = firstHalf.append(secondHalf.reverse()).toString();

This can probably be done more simply, in fact.

Code:
    StringBuilder processed = new StringBuilder();
    for (int i = (text.length() - 1) / 2 - 1; i >= 0; i--) {
      processed.append(text.charAt(text.length() - i - 1));
      processed.insert(0, text.charAt(i));
    }

The single line solution using just substring, length and integer arithmetic is definitely more awesome, though. :D
 
Top Bottom