What was the exact problem? Kindly share the scenario and the solution as might help others visitng this post...
NP-complete 42 Junior Poster
NP-complete 42 Junior Poster
NP-complete 42 Junior Poster
What was the exact problem? Kindly share the scenario and the solution as might help others visitng this post...
Please be more specific... is it a user defined function or a standard function like, say, strncpy()? Most of the standard functions of C are available in C++ but a few C++ specific functions won't be available to C and you cannot use them in C.
Please give more details.
@meowmonkey: can you post your solution (if that's not a problem!) so that we can have a look if what you did was indeed the best that could have been done...
Well, you asked for the best way and having 3 levels of iteration (for->while->for) doesn't sound quite optimal...
My pleasure, rubberman! Add a rep, maybe? :-)
And hey, good luck finding that old floppy! I'm sure people can learn a thing or two about exception handling and how to inmplement them with your code...
Example:
int fib (int n)
{
if (n <= 1)
return n;
else
return fib(n - 1) + fib(n - 2);
}
But the iterative approach is much better in terms of complexity! That is, for large n's the iterative version will be much faster than the recursive one.
Well, you can improve the naive recursive approach^^ with memoization but if you have never heard of Dynamic Programming, may be you can skip this for now.
But keep it at the back of your head and you may find this handy when you learn DP (if you're into a CS program, you will someday!)
@general2012: why did you start 2 threads for this?
I have replied in similar lines as AncientDragon in the other thread. Check that out for the printf problem as well...
Along with not using gets, you should also not cast the output of malloc() and you should make a habit of including stdlib.h for malloc so that you will atleast get some friendly warnings.
Why its not working:
1. p->count is never initialized to anything.
But the main problem is this:
2. You are trying to copy a C-string to a character. p->name[any index] refers to a single character and not a C-string. So strcpy fails.
3. Again, you want to print a C-String (with that %s) but you are really trying to feed a character to that %s. Result: your code crashes.
The fix:
#include<stdio.h>
#include<string.h>
typedef struct{
int count;
char name[20];
}student;
int main()
{
student *p;
p = (student*) malloc(sizeof(student));
char input_name[20];
gets(input_name);
strcpy(p->name, input_name);
printf("%s", p->name);
getch();
}
Now, a few tips to improve:
1. Use fgets instead of gets.
2. Once you use fgets you may as well want to use strncpy to make the copy overflow safe.
3. You may want to include stdlib.h for malloc. In that case, the cast would be redundant (And this should be the case!)
Also, you would like to print array[0] to array[4] to get the first 5 values :)
Could you guys help me solving this? :)
Offcourse! But first, you need to show us some proof of efforts (that's DaniWeb rules, btw)
Try to read up on arrays in the Java (Oracle) tutorials, and come up with something yourself.
We'll help you build on that...
then why is there even a namespace?
That's there so that YOU can use your own namespaces. In large programs, you may face name conflicts (especially if you're just a part of a 100 developer team!). To avoid that you may have custom namespaces for convenience.
so why is there a std ?
Well the C++ standard committe decided to put all the standard objects (variables and stuffs) in one organisation level (that's the std namespace) rather than scattering them over different namespaces like std1, std2, ..., etc.
Their reason was to just show us the feature existed, the real use comes when you use it for your own contexts.
What have you done so far?
If you haven't, then start on something. We are not here to do your homework. We are here to help you in case you get stuck.
You are NOT using StringTokenizer to merge the 2 arrays into the 3rd. You are using it to read the 2 arrays from a txt file. In that context, your strategy will depend on the way the data is distributed in that txt file.
As far as the merging is concerned, I believe you're looking into a better solution ^^
I have completed the objective
Show us the proof (its DaniWeb's policy) and we'll be more than happy to comment on effectiveness and the rest...
Okay, first of all that apparently meaningless output is NOT representing "1" in any language, not even Klingon :)
As James mentioned, the part after [B@
is an unique ID for the array so every time you recompile your code its gonna print out something different.
Now,
"1".getBytes()
returns a byte array which as per your call contains '1' - the number. (Byte in java is just another integer datatype with the shortest range, -128 to 127. And a byte array doesn't mean it will give you the binary representations of the numbers it contains)
So 2 places where you went wrong:
1. You were trying to print the array itself and not its contents.
2. System.out.println (Arrays.toString(array));
as James mentioned will give you 49 which is the ASCII representation of numeric 1. (Did you try it correctly? It shoudn't have given you that [B@... stuff again! Did you add import java.util.* at the top?)
Finally, to get a clearer picture and to understand that byte array is nothing but just another int array where you can only put integers < 127 and > -128, try the following code:
public class ByteArrayExample
{
public static void main (String args[])
{
byte[] array = {1, 2, 3};
for (int i = 0; i < array.length; i++) {
System.out.println (array[i]);
}
}
}
So you want to echo the command line?
Well, well... consider this simple code snippet for that (from oracle's official tutorial):
public class Echo {
public static void main (String[] args) {
for (String s: args) {
System.out.println(s);
}
// you could have also used
// for (int i = 0; i < args.length; i++)
// then inside, println(args[i])
// the above is just a handy syntactic sugar
// to print arrays and collections.
}
}
Now output depends on how you give the input:
c:\yourCodeDirectory>java ab cd
ab
cd
c:\yourCodeDirectory>java "ab cd"
ab cd
c:\yourCodeDirectory>java "ab cd ef gh etc"
ab cd ef gh etc
So, moral of the story, giving inverted commas ("") around your command line input will treat the entire sequence (till you hit enter) as a single entity.
that's strange... I simulated your scenario to see if i was missing something... but it worked perfectly in my case as it should!
Try running any other java code in your system... btw, are you sure your jdk is valid (was downloaded from the official Oracle site)?
You mean you want to put 2 spaces, right?
If that's the case, then look at my code once again and tell me where you can change it to print 2 spaces?
Doesn't the above code do that already? Please elaborate...
Okay, that's good... now to read from that file line-by-line, you can do something like:
String line = "";
while (txtFile.hasNextLine()) {
line = txtFile.nextLine()
}
But, now think of how you'd read the data to facilitate your problem. Maybe after reading a particular line, you would like to read the different "tokens" in that line. Guess what, that Scanner class you're using has something for reading different tokens in the same line too. Scanner API
Also, just to be clear, the 3rd line of the text file is what? Is it the item in the (0,0) position of the table?
Probably this is what you're looking for:
public class numbers {
public static void main(String[] args) {
final int N = (args.length);
for (int i = 0; i < N; i++)
System.out.print(args[i]);
System.out.println();
System.out.print('\"');
for (int j = 0; j < N; j++) {
System.out.print(args[j]);
// this will give a space after
// every word, except the last
if (j < N-1) {
System.out.print(" ");
}
}
System.out.print('\"');
System.out.println();
}
}
Hope this helps... :)
Think about it and come up with something yourself. We need to have proof of your efforts in order to help you.
Show us what you've done so far and we'll help you from there...
Are you sure your commnad prompt says like this:
c:\>myWork>javac Example.java
c:\>myWork>java Example
?
Dude, I told you once to stick to a single thread. Initially you had two threads for this...now you've made 3!
As far as the calculations are concerned, why don't you calculate for some test cases and see if your code is giving you the same result or not?
You have defined the array inside main() of Numbers class. So the scope of that array is limited to main() of Numbers only. You would probably like to have that array as a private instance of the Numbers class and have public setters/getters to access it from other classes (perhaps Numbers should have been an Interface, but nevermind)... something like this:
public class Numbers {
private int[][] matrix;
public void setMatrix (int[][] matrix) {
this.matrix = matrix;
}
public int[][] getMatrix (){
return this.matrix;
}
// other utility methods...
// ...
}
Now, inside Probability you do something like this:
class Probability {
public static void main (String[] args) {
// creating a reference of the Numbers class
Numbers aNumber = new Numbers();
// initialize a new matrix
int[][] matrix = {{3, 6, 10, 16, 24}};
// bind the newly created matrix with the Number class' matrix
aNumber.setMatrix(matrix);
// after the above, the matrix in Number class reference aNumber will
// have the value {{3, 6, 10, 16, 24}}.
// Now you can use it for your own purposes by simply calling
// the getMatrix() method... like this:
int[][] matrixToBeUsed = aNumber.getMatrix();
// Now, do whatever with this matrixToBeUsed...
// ...
}
}
You'll have to import the Numbers class if the Probability class is in a different package (which it should).
In case you need to have a single hard-coded matrix, you may not have a setter...
In that case,
you can alter the …
@subramanya.vl: The code he posted is not complete. And he has quite a number of classes not just Basket or Article...
@TheMrPatrick: If you still haven't worked it out, please share the full code that you've written so far. Maybe we can help you better if we first understand what you're trying to do.
a good example every now and again can be far more enlightening than umpteen posts explaining what changes should be made.
I agree.
I was only asking you to wait till he comes up with his version first. I somehow felt that he was not comfortable making the changes... he didn't even change your variable names to the ones he was originally using... :)
pakArtikel method is already receiving an article as a parameter. So why make a new Article? You can simply use this:
public void pakArtikel(Artikel artikel)
{
Basket myBasket = new Basket();
myBasket.add(artikel);
}
If you really want to use a new article then those <suitable parameters> would be the various values with which you would like to create a new article via its constructor. That is it should have the values for all the instance variables (fields) of class Article.
@subramanya.vl: You made a slight mistake... you forgot the brackets for the constructor while initializing.
@MistaGeorge: that's correct. A parent cannot inherit from subclass.
Having said that, just for the sake of availability of a 2d array you may not need an inheritance structure.
Share your class design or atleast tell us what you're trying to design so that we can guide you better.
@jalpesh_007: Dude, why are you repeating the same question as JamesCherill asked, in a different way? If it had been unintentional, then in future first read the previous posts before you give your own suggestions and try not to be redundant. Thanks.
I think your if should be:
if ( time <= TimeRequested )
that is, you're printing all the journeys which can be completed before the requested time.
Also, since there can be more than one suitable journey you may change your print message as
cout << "You can take : " ; (though its purely a cosmetic change :))
Now, for the case when the requested time is too low and none of the journeys are suitable, you have to consider every journey; so that else part is not what you want.
Instead, have a boolean variable, say, hasSomeJourney and initialize it to false. Then inside that if statement, make it true (because if it reaches inside the if, it has journey(s) that matched the condition).
Now outside the main while (line 46) check whether this variable is true or false and accordingly print out the message (i.e. if its false, no journey satisfied, so print the error message)
@deceptikon: please allow him to make the changes himself this time...don't put up a snippet for him.
How does the Sorting.insertionSort() method look like? Is it from any standard API?
my pleasure...:)
You never calculated total time. The variable TimeRequiered
simply calculates the time for each change and when you print the value outside the loop it prints the last value.
To calculate total time first initialize the variable TimeRequiered
to 0 at the beginning. Then change line# 44 to
TimeRequiered = TimeRequiered + (DistanceLenght/DistanceSpeed * 60);
This will get you the total time for each journey.
BTW, your variables need to be floats or doubles to handle decimals.
If your class has covered functions by now then please use them. Structure your code so that you don't mess up your main. Its like delegating works to helpers. Have separate functions for average, standard eviation and others (if you can think up some) and call those methods from inside main.
Okay... I see that you've posted something on the same problem in another thread... In future try to stick to a single thread (article) for a single (or related) problem.
We all can help...that's why we are here... but we don't help people who doesn't show any effort... and we don't do your homework. That's not DaniWeb.
Try to think of some logic to solve the problem and we will certainly help you build up on it.
share your modified code...
It is possible. What do you think should be the strategy? It looks like a homework question, so we'll only provide hints. But first think of something yourself and we'll help you build on it.
Also, please specify what your input files look like so that we have an idea of how the merge is happening.
You are moving the temp to temp next before and then trying to print temp's variables! That's why you're getting all garbage!
You should move line# 29 and 30 between line# 34 and 35.
But that's not the only problem!
You're reading off the first line using getline! The inFile >> temp->R etc. assignments are only assigning from 2nd line onwards, if at all there is a 2nd line!
Even if you remove the getline (which you should) your loop needs a check for EOF and when it happens it should break out. Otherwise, your code will fail for empty files and for a file with 2 lines it will print garbage for the 3rd iteration.
You should have something like if ( inFile.eof()) break;
between line# 28 and 29.
And for all the above reasons its perhaps better to use a std::vector<Widget> as Nick suggested.
for running an app you do not need a compiler. You can simply take out the .exe and share it.
It'll run, but given the fact that you're using "Turbo C++" it might not run as you would've expected it to, on a few machines.
A few advice:
@brent: did you use the correct usage of in_avail() as highlighted by deceptikon in his first post?
Also, check out that sticky (and read it full, because somewhere down in the comments section someone mentioned that using pause2 instead of pause may do the trick in unix) and try to implement Narue's final solution and see how that turns out in unix...don't forget to implement that trick as well...
Well, try out the correct usage of in_avail() first...and if that works you may skip Narue's full implementation.
@Taywin: I think you meant your loop to be :for (int i = 1; i < array[index]; i++
and NOTfor (int i = 1; i <= array[index]; i++)
Why inclusive? Pseudo code syntax?
Oh! I see... then what's the workaround for unix?
The sample output you gave above includes all that you want, may be not in a neat format, and sem 2's subjects are printed first, but apart from that I don't see where the problem is!
But if you're not getting the above output and it is what you want to get, well, I copy pasted your code and did the changes i suggested earlier to compile it and in my compiler, Visual Studio 2010, it does give the output in the above format.
Define a string somewhere and call it whatever... i called it str...then inside that loop use this:
// for the last word, no comma afterwards...
if (i == (aa5.length - 1)) {
str = str + aa5[i];
} else {
str = str + aa5[i] + ", ";
}
Did you try ignoring the \r as well?
Try to use deceptikon's advise of using ignore with a large value (like 100 or numeric_limits<streamsize>::max()) and ignore the \r as well and see if it runs on unix...
What is your expected output and what are getting now? Please specify the error(s).
A few observations at a glance:
If you're using any standard compiler, your code may not compile.
#include <iostream>
(no .h)#include <string>
int main (void)
the code above is not meeting with your requirements...you're not validating your input, you're not checking the sum condition either!
Why don't you follow the modular approach I discussed in the previous post? It'll be much simpler for you to understand the flow and you can debug yourself then.
Also, try to put curly braces for every for loop. Removing them can gain you one less line but cost you a lot on readability. (you haven't for the loops on line 9, 10, 15 and 22)
But, did you omit them on purpose or did you simply missed them?
Anyway, follow the modular approach and we'll be more than happy to help.
Which compiler? And which platform?
It works as its supposed to in Visual Studio 2010 (i used the command line tool) on a Windows machine.
I think, if you're on *nix, along with that cin.ignore(cin.rdbuf()->in_avail(),'\n');
you also need a cin.ignore(cin.rdbuf()->in_avail(),'\r');
I'm not sure, but intuition tells me that it has to do with the platform specific implementation of \r and \n by C/C++.
Did you implement getInput() outside main()? Its not a built-in function and you need to provide its implementation. Also, try to wrap the above code in a separate function (rather than copying everything inside main) and try using that function from inside main. This way, you'll have more modularity and you'll better understand your code
(You didn't write the above code snippet yourself, did you?)
In short, the break-up would be something like this (roughly) :
// #define SIZE as 5
#define SIZE 5
// define the various modules:
void takeInput (int arr[][SIZE], sizeOfArr)
{
// the above snippet...
}
int isEqualSum (int arr[][SIZE], sizeOfArr)
{
// check for the 2nd condition here and return 0 or 1 accordingly...
}
void printArrLine (int arr[][SIZE], sizeOfArr)
{
// print as per your requirements...
}
// now, integrate all the modules from within main:
int main (void)
{
// declare array
// call takeInput by passing the array and its size
takeInput (arr, SIZE);
// check if 2nd condition is true
if (isEqualSum (arr, SIZE))
{
// call another helper function to print the array
printArrLine (arr, SIZE);
std::cout<<"meets second condition";
}
return 0;
}
Try that and let us know... Happy coding!