Results 1 to 2 of 2
Thread: Writing 'polynomial' class
- 02-01-2013, 10:54 PM #1Member
- Join Date
- Oct 2012
- Rep Power
Writing 'polynomial' class
Hey all, I'm writing a polynomial class that will have methods to output, evaluate, add, subtract, and multiply polynomials. I'm going to use the driver class to read a text file formatted like this:
3 First 6 3 4 1 2 0 Second 10 12 18 6 -4 2 1 1 Third 4 1 -20 0
6X^3 + 0X^2 + 4X^1 + 2X^0 <--first line
The 'polynomial' class is the part that I am stumped on, if I read the lines with scanner in the driver and pass the subsequent lines as Strings to the polynomial class, how can I tokenize (or use whatever method) the 'ints' in the Sting line and store them to a single array where the index is the degree of the polynomial and the int stored is the coefficient? It only has to work up to a degree of 20. (X^20)
Any help is greatly appreciated. If I can get this part of the polynomial class working, I can figure out everything else out.
- 02-02-2013, 12:45 AM #2Moderator
- Join Date
- Feb 2009
- New Zealand
- Rep Power
Re: Writing 'polynomial' class
I'd represent a polynomial as some sort of Map whose keys and values are both Integer (the power and coefficient respectively). The only "tokenising" needed is that provided by the String split() method.
Supposing that the index always lies >=0 and <=20 then an int array (of length 21) could play the role of the map. Just make sure that "unused" terms have a coefficient of zero. Again the only parsing or tokenising you have to do is that provided by split(). I suggest you write some code to test, experiment and get familiar with both split() and the parse() method of Integer. This latter is what enables you to calculate the int value associated with the strings obtained from the input.
Personally, as I said, if I wanted a map I'd go for a Map: because that's the most straight forward thing to do. Certainly there might be efficiency to be had by using int arrays to implement my own map or sparse array, but I'd put off such complications until the polynomial behaviour was done, tested and found to be correct.
Notice that the restriction on the range of the index (which has a whiff about it, of being an ad hoc "requirement" facilitating the use of arrays...) means that the product of two polynomials won't always be defined.
- By son012189 in forum New To JavaReplies: 2Last Post: 02-15-2012, 05:34 PM
- By AndrewSD in forum New To JavaReplies: 3Last Post: 01-11-2011, 04:24 AM
- By smray7 in forum New To JavaReplies: 3Last Post: 11-30-2010, 06:16 PM
- By MasqueradeToday in forum New To JavaReplies: 1Last Post: 10-07-2010, 11:53 PM
- By wardd85 in forum New To JavaReplies: 5Last Post: 07-16-2008, 10:59 PM