|
Thread Rules 1. This is not a "do my homework for me" thread. If you have specific questions, ask, but don't post an assignment or homework problem and expect an exact solution. 2. No recruiting for your cockamamie projects (you won't replace facebook with 3 dudes you found on the internet and $20) 3. If you can't articulate why a language is bad, don't start slinging shit about it. Just remember that nothing is worse than making CSS IE6 compatible. 4. Use [code] tags to format code blocks. |
|
+ Show Spoiler +For some reason, I struggle with this simple line of c. I am writing a UNIX shell in C at the moment and want to adress a certain file, even when I change the directory with cd/. What I am currently using to log every input is: FILE *filePointer = fopen("name", "ab+");
When I change directories, the next time I use the lines above, the new current directory gets picked. I dont wan't to hardcode the directory and filename by simply doing path* = "C://...." . . . FILE *filePointer = fopen(path, "ab+");
I use this to get the current directory on start and combine it with a set filename, but fopen() no longer works then. Combining the strings works fine. char* logfile_name = "logfile.txt"; char currentDirectory[1024]; getcwd(currentDirectory, sizeof(currentDirectory)); char* logfile = malloc(strlen(currentDirectory) +strlen("/") + strlen(logfile_name)); FILE *fp = fopen(logfile, "ab+");
Fuck it. Absolut directory it is. I won't do all this hassle for my first and only C-assignment this semester after which we immediately switch to java
|
On October 27 2015 04:25 Artesimo wrote:I use this to get the current directory on start and combine it with a set filename, but fopen() no longer works then. Combining the strings works fine. char currentDirectory[1024]; getcwd(currentDirectory, sizeof(currentDirectory)); char* logfile = malloc(strlen(currentDirectory) +strlen("/") + strlen(logfile_name)); FILE *fp = fopen(logfile, "ab+");
I'd guess that is because you never write anything to the logfile array. Instead you just pass garbage to fopen.
|
On October 27 2015 04:33 spinesheath wrote: I'd guess that is because you never write anything to the logfile array. Instead you just pass garbage to fopen. I do, I just forgot to add it, sorry about that. It is my first time with C, so my code is a mess and I oversaw it. As I said, if I check the merged string with printf() it gives me the complete path+filename, but I cant sue it on fopen();
EDIT: another fuckup on my part. It doesnt work properly. The / I added is missing, so it goes path1/path2/path3Filename instead of path1/path2/path3/Filename
|
On October 25 2015 03:10 Itsmedudeman wrote: My tip would be don't be afraid to try and take on something a bit bigger than something you think you can handle. If you only do practice problems that you already know all that teaches you is memorization skills. When you work on a harder project you can learn so much more by being forced to branch out of your comfort zone and learn things you can't learn from a textbook by encountering your own unique problems and problem solving your way through them with whatever resource available.
Also, feel free to change the subject mid-way. Its your project after all.  I once wanted to write a simple game and ended up writing an extension to the object model of the language I was using - just because that one thing in the game library didn't seem to do its job in the most elegant way. I did not learn a thing about game programming but I learned a lot about the stuff my natural curiosity led me to. 100% win.
|
Hey folks, I've got a question for you. I've been trying to do some challenges on /r/dailyprogrammer and got stuck on finding the distinct prime factors of an integer. Here's my attempt so far:
def findFactors(n): factors=[] f=2 while n!=1: if (n%f)==0: factors.append(f) n/=f else: f+=1
return factors
However, this fails at the distinct part. I tried it with adding in things like "if not in factors" but then it would run indefinitely because it couldn't find a last factor.
For example, 492 was factored by 2 = 246, by 3=82, by 41=2, but then it's left with a 2, which is already used as a factor. I can't seem to figure out how 492 is even supposed to be factored, and I can't find any resources online that state the distinct prime factor for it, such as Wolfram.
The challenge, and some example code is here, but they seem to do the exact same thing.
|
On October 27 2015 06:46 WarSame wrote:Hey folks, I've got a question for you. I've been trying to do some challenges on /r/dailyprogrammer and got stuck on finding the distinct prime factors of an integer. Here's my attempt so far: def findFactors(n): factors=[] f=2 while n!=1: if (n%f)==0: factors.append(f) n/=f else: f+=1
return factors
However, this fails at the distinct part. I tried it with adding in things like "if not in factors" but then it would run indefinitely because it couldn't find a last factor. For example, 492 was factored by 2 = 246, by 3=82, by 41=2, but then it's left with a 2, which is already used as a factor. I can't seem to figure out how 492 is even supposed to be factored, and I can't find any resources online that state the distinct prime factor for it, such as Wolfram. The challenge, and some example code is here, but they seem to do the exact same thing. Think of a simple input, like factoring the number 4.
What should happen when a prime occurs multiple times in the factorization? Consider 2^3 = 8. It only has one distinct prime factor, 2, that is repeated 3 times. What about 2 * 2 * 3 * 3 = 36, which has distinct prime factors 2 and 3?
There is a simple addition to your program that would handle this case.
|
Oh, I see. I misunderstood the question, I believe. By distinct primes they mean for you to only add each number to the factor list even if it happens more than once? Ex: 12 = 2*2*3, but the distinct prime factors would be 2,3, right?
EDIT: I've changed it to def findFactors(n): factors=[] f=2 while n!=1: while (n%f)==0: if f not in factors: factors.append(f) n/=f else: f+=1
return factors and have yet to see any problems. Thank you!
|
On October 27 2015 07:27 WarSame wrote:Oh, I see. I misunderstood the question, I believe. By distinct primes they mean for you to only add each number to the factor list even if it happens more than once? Ex: 12 = 2*2*3, but the distinct prime factors would be 2,3, right? EDIT: I've changed it to def findFactors(n): factors=[] f=2 while n!=1: while (n%f)==0: if f not in factors: factors.append(f) n/=f else: f+=1
return factors and have yet to see any problems. Thank you! That's python, so make it more pythonic and use a set instead of a list for unique items. If you don't like sets, you can get the same power by using a dictionary and returning the keys (secretly also a set).
Forgot to say that using a set is more legible, and allows you to remove that if statement.
Edit 2: just saw you have an indentation error around your else statement. Presumably that's just a quirk of pasting your code here? It should give a parse error.
|
The set suggestion is a good idea, and I'll go use that. Thanks!
The indentation error actually works fine - python allows for while/else loops. Yes, really. It also has some usability - if the while breaks out of the loop, it skips the else. If the while never runs, the else still does. If while finishes normally, the else runs afterwards. It was an error from me modifying the if though.
|
I've run into a minor problem while learning to use MongoDB. Whenever I try to query a collection for some specific fields, the order they get printed always remain the same. E.g. db.users.find({}, {name: 1, password: 1}); returns identical to db.users.find({}, {password: 1, name: 1}); I'm wondering if it is possible to change the order they get returned, similar to how it can be done in SQL, where SELECT name, password FROM users and SELECT password, name FROM users returns the same fields, but in different order. I tried looking through the documentation for MongoDB, but I haven't been able to find anything.
|
I don't think you can. Mongo results are json-like objects and their field order depends on the underlying implementation (it's a form of tree structure that you shouldn't worry about). The projection thus only specifies what fields to include and not the order (which you should consider meaningless, because you cannot be sure about it and it can change arbitrarily). If you want to print them always in the same order, address that when printing. The following pseudo code illustrates it a bit better:
print (result.name, result.password)
|
Pretty much what Acrofales said. You shouldn't rely on your query to provide you with fields in certain order. You can always change it when printing data to the user. If you have to return it as raw data, without printing it (as a JSON response to be consumed by some API for example) then you should pass it through some data transformer which will ensure that your output is exactly what you want.
|
Java noob here, the ?: operation works only when you want to affect a value ? like
String foo = num.isOdd "yes" : "no"
I wanted to do something like :
InetAddress ia = InetAddress.getByName(textFieldIP.getText()); //get the IP address ia.isReachable(3000) ? lblResult.setText("Success") : lblResult.setText("Failure"); //write either Success or Failure if the IP is reachable And it doesn't work. When I do a dumb if/else, it works without any issue.
|
I'm fairly sure that doesn't work because ? : just returns a value like so:
max = (a > b) ? a : b;
Might be wrong though.
|
I guess you would do this if you want to use ?:
lblResult.setText( ia.isReachable(3000) ? "Success" : "Failure" );
|
On October 28 2015 02:47 Ropid wrote:I guess you would do this if you want to use ?: lblResult.setText( ia.isReachable(3000) ? "Success" : "Failure" );
Oh yeah thank you very much ! Seems obvious now that I see it.
|
I still wouldn't put a ternary as function param.
String result = ia.isReachable(3000) ? "Success" : "Failure";
lblResult.setText(result);
|
Are we allowed to post code here just for code review/efficiency? I have some code I wrote for a /r/dailyprogrammer challenge that is taking me about a half hour to run, but someone said that they got their version to run in under a second, so I'd like to see where the improvement could be made. EDIT: After about an hour of looking at it, I finally found the difference right after posting. It's amazing what one line can do.
The slow version:
import itertools, operator, math
def combo(s,v):#alias function return itertools.combinations_with_replacement(s,v)
def findLims(numDig): return 10**(numDig-1),10**(numDig)
def numDigits(n): return int(math.log10(n))+1
def main(): numDig, numFang=map(int,raw_input().split()) #vampire can be in this range vampBot,vampTop=findLims(numDig) fangBot,fangTop=findLims(numDig/numFang) print vampBot,vampTop vampires={}#dict containing all vampires in vamprange for fang in combo(range(fangBot,fangTop),numFang): #combo for 10 to 99 returns 10,11,12,etc. #multiply the combination values together vampire=reduce(operator.mul,fang) vampLen=numDigits(vampire) if vampLen!=numDig: continue fangDig=sorted(''.join(map(str,fang))) vampDig=sorted(str(vampire)) if vampire in range(vampBot,vampTop): if fangDig == vampDig: vampires[vampire]=fang print fang for v,f in sorted(vampires.items()): print "{}={}".format(v,'*'.join(map(str,f)))
main()
The fast version simply removes that "if vampire in range(vampBot,vampTop)" and the program runs in half a second, or about 1/3600 the time.
|
+ Show Spoiler + package test;
import javax.swing.JOptionPane;
public class ChangeCalculator {
public static void main(String[] args) {
String price = JOptionPane.showInputDialog("Enter price:"); String paid = JOptionPane.showInputDialog("How much did you pay with?"); double num1 = Double.parseDouble(price); double num2 = Double.parseDouble(paid); double change = num2 - num1; if(num1 > num2){ JOptionPane.showMessageDialog (null, "Invalid entry!", "Warning", JOptionPane.WARNING_MESSAGE); System.exit(1); } int remainingChange = (int) change * 100; int numberOfHundredsEuros = remainingChange / 10000; remainingChange = remainingChange % 10000;
int numberOfFiftyEuros = remainingChange / 5000; remainingChange = remainingChange % 5000;
int numberOfTwentyEuros = remainingChange / 2000; remainingChange = remainingChange % 2000;
int numberOfTenEuros = remainingChange / 1000; remainingChange = remainingChange % 1000;
int numberOfFiveEuros = remainingChange / 500; remainingChange = remainingChange % 500; int numberOfTwoEuros = remainingChange / 200; remainingChange = remainingChange % 200; int numberOfOneEuros = remainingChange / 100; remainingChange = remainingChange % 100; int numberOfFiftyCents = remainingChange / 50; remainingChange = remainingChange % 50; int numberOfTwentyCents = remainingChange / 20; remainingChange = remainingChange % 20; int numberOfTenCents = remainingChange / 10; remainingChange = remainingChange % 10; int numberOfFiveCents = remainingChange / 5; remainingChange = remainingChange % 5; int rest = remainingChange; String myString = "Your amount " + change + " consists of: \n" + "100 Euros: " + numberOfHundredsEuros + "\n" + "50 Euros: " + numberOfFiftyEuros + "\n" + "20 Euros: " + numberOfTwentyEuros + "\n" + "10 Euros: " + numberOfTenEuros + "\n" + "5 Euros: " + numberOfFiveEuros + "\n" + "2 Euros: " + numberOfTwoEuros + "\n" + "1 Euros: " + numberOfOneEuros + "\n" + "\n" + "50 Cents: " + numberOfFiftyCents + "\n" + "20 Cents: " + numberOfTwentyCents + "\n" + "10 Cents: " + numberOfTenCents + "\n" + "5 Cents: " + numberOfFiveCents + "\n" + "Remaining Cents: " + rest; JOptionPane.showMessageDialog(null, myString); } }
Yo dudes! I'm trying to program a change calcuator in Java for an assignment I have in school. It works kinda okay but it wont print out cents. Any ideas?
Code in spoiler.
|
|
|
|