Roman representation of integers [duplicate] - java

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
How do you find a roman numeral equivalent of an integer
I am looking for a simple algorithm (preferably in Python). How to translate a given integer number to a Roman number?
string Roman(int Num){...}
For example, Roman(1981) must produce "MCMLXXXI".

I needed the opposite one time (going from Roman numerals to int). Wikipedia has surprisingly detailed information on how Roman numerals work. Once you realize that things are this well-defined and that a specification is available this easily, translating it to code is fairly trivial.

Here is a lengthy explanation how to do it with a lot of source code attached:
http://www.faqs.org/docs/javap/c9/ex-9-3-answer.html
But I think it could be done more efficient.

Check out the code at this ActiveState link. The code looks fairly well documented.

I can't think of a third party library that has this functionality. Sometimes you have to write some stuff yourself, although there are plenty of examples of how do to this online. Here is one from RoseIndia

For hundreds, tens and units the rule is pretty much the same, i.e. you have a 1, 5 and 10 character the representation will be the same for each, just that the letters change.
You could have a table of 10 entries which represents a template
0 -
1 = U
2 = UU
3 = UUU
4 = UF
5 = F
6 = FU
7 = FUU
8 = FUUU
9 = UT
Now also have for units, tens and hundreds your table:
Units = IVX
Tens = XLC
Hundreds = CDM
Apply your template for the number to the letter representation so a U is replaced by the first character, an F by the second and a T by the 3rd.
Thousands are just an M for each thousand.
Build your string starting with the thousands, then the hundreds, then the tens and then the units.
If you were building it backwards of course you could start with the units modding by 10, then construct your units string, divide by 10 and mod again and shift to the tens string, repeat with the hundreds string and when you get to the thousands string you will know it by the fact your string has just one character i.e. an M.

Related

Finding Repeating part of fraction (a/b) and print only repeating integers as String in java? [closed]

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 1 year ago.
Improve this question
I'm solving a problem of fraction,
if the fraction part is repeating, print the only repeating integers as String.
if the fraction part is not repeating, print upto 4 digits after decimal.
if the fraction output is simple print it directly as string.
E.g.
a) 1/3 = 0.3333... , here 3 is recurring, so need to print only 0.3.
b) 5/2 = 2.5 -- Simple Math.
c) 22/7 = 3.14287, here 14287 is repeating, so need to print 3.14287
Can you please help, the solution should have O(k) time complexity and space complexity
public String fractionToDecimal(int numerator, int denominator) {
StringBuilder tem = new StringBuilder();
long q = numerator / denominator;
return tem.append(q);
}
This question is quite complicated. You need to know quite a few advanced concepts to fully understand why it is so.
Binary vs. Decimal
The notion '1 divided by 3 repeats the 3 endlessly' only works if you presuppose a decimal rendering system. Think about it: Why does '10' come after '9'? As in, why did 'we' decide not to have a specific symbol for the notion 'ten', and instead this is the exact point on the number line 'we' decided to go for two digits, the first digit and the zero digit written next to each other? That's an arbitrary choice, and if you delve into history, humans made this choice because we have 10 fingers. Not all humans made this choice, to be clear: Sumerians had unique digits all the way up to 60, and this explains why there are 60 seconds in a minute, for example. There are remote tribes using 6, 3, and even weirder number systems.
If you want to spend some fun math time, go down the rabbithole on wikipedia reading about exotic number systems. It's mesmering stuff, a fine way to spend an hour (or two, or ten!)
Imagine a number system for aliens that had only 3 fingers total. They'd count:
Human Alien
0 0
1 1
2 2
3 10
4 11
5 12
6 20
8 21
9 22
10 30
Their number system isn't "weird" or "bad". Just different.
However, that number concept goes both ways: When you write, say, "1 divided by 4 = 0.25", that 25 is also in 'decimal' (the name for a number system that has 10 digits, like what most humans on the planet earth like to use).
In human, 1 divided by 10 is 0.1. Easy, right?
Well, in '3-finger alien', one divided by three is... 0.1.
Not 0.1 repeating. Nono. Just 0.1. It fits perfectly. In their number system, one divided by ten is actually quite complicated, where it is ridiculously simple in ours.
Computers are aliens too. They have 2 fingers. Just 0 and 1, that's all. A computer counts: 0 1 10 11 100 101 110 111 and so on.
An a / b operation that repeats in decimal may not repeat in binary. Or it may. Or a number that doesn't repeat in decimal may repeat in binary (1/5 repeats endlessly in binary, in decimal, it's just 0.2, easy).
Given that computers don't like counting in decimal, any basic operation is an instant 'loser' - you can no longer answer the question if you even write double or float anywhere in your code here.
But it requires knowledge of binary and some fairly fundamental math to even know that.
Solution strategy 1: BigDecimal
NOTE: I don't think this is the best way to go about it, I'd go with strategy 2, but for completeness...
Java has a class baked into the core library called java.math.BigDecimal that is intended to be used when you don't want any losses. double and float are [A] binary based, so trying to use them to figure out repeating strides is completely impossible, and [B] silently round numbers all the time to the nearest representable number. You get rounding errors. Even 0.1 + 0.2 isn't quite 0.3 in double math.
For these reasons, BigDecimal exists, which is decimal, and 'perfect'.
The problem is, well, it's perfect. In basis, dividing 1 by 3 in BigDecimal math is impossible - an exception occurs. You need to understand the quite complicated API of BigDecimal to know about how to navigate this issue. You can tell BigDecimal about exactly how much precision you're okay with.
So, what you can do:
Convert your divider and dividend into BigDecimal numbers.
Configure these for 100 digits after the comma precision.
Divide one by the other.
Convert the result to a string.
Analyse the string to find the repeating stride.
That algorithm is technically still incorrect - you can have inputs that have a repetition stride that is longer than 100 characters, or a division operation that appears to have a repeating stride when it actually doesn't.
Still, for probably every combination of numbers up to 100 or so you care to throw at it, the above would work. You can also choose to go further (more than 100 digits), or to write an algorithm that tries to find a repeat stride with 100 digits, and if it fails, that it just uses a while loop to start over, ever incrementing the # of digits used until you do find that repeating stride in the input.
You'll be using many methods of BigDecimal and doing some fairly tricky operation on the resulting string to attempt to find the repetition stride properly.
It's one way to solve this problem. If you would like to try, then read this and have fun!
Solution Strategy 2: Use math
You can use a mathematical algorithm to derive the next decimal digit given a divisor and dividend. This isn't so much computer science, it's purely a mathematical exercise, and hence, don't search for 'java' or 'programming' or whatnot online when looking for this.
The basic gist is this:
1/4 becomes the number 0.25, how would one derive that? Well, had you multiplied the input by 10 first, i.e. calculate 10/4, then all you really need to do is calculate in integral math. 4 fits into 10 twice, with some left over. That's where the 2 comes from.
Then to derive the 5: Take the left-over (4 fits into 10 twice, and that leaves 2), and multiply it again by 10. Now calculate 20/4. That is 5, with nothing left over. Great, that's where the 5 comes from, and we get to conclude that there is no need to continue. It's zeroes from here on out.
You can write this algorithm in java code. Never should it ever mention double or float (you immediately fail the exercise if you do this). a / b, if both a and b are integral, does exactly what you want: Calculates how often b fits into a, tossing any remainder. You can then obtain the remainder with some more simple math:
int dividend = 1;
int divisor = 4;
List<Integer> digits = new ArrayList<>();
// you're going to have to think about when to end this loop
System.out.print("The digits are: 0.");
while (dividend != 0 && digits.size() < 100) {
dividend *= 10;
int digit = dividend / divisor;
dividend -= (digit * divisor);
digits.add(digit);
System.out.print(digit);
}
I'll leave the code you'd need to write to find repetitions to you. You can be certain it repeats 'cleanly' when your divisor number ends up being a divisor value you've seen before. For example, when doing 1/3, going through this algorithm:
First loop through:
dividend (1) is multiplied by 10, becomes 10.
dividend is now integer-divided by the divisor (3), producing the digit 3.
We determine what's left: the digit times the divisor is 9, so 9 of those 10 have been used up, leaving the 1. We set dividend to 1.
As you can see, nothing actually changed: The dividend is still 1 just like it was at the start, therefore all loops through go like this, producing an endless stream of 3 values, which is indeed the correct answer.
You can maintain a list of dividends you've already seen. e.g. by storing them in a Set<Integer>. Once you hit a number you've already seen, you can just stop printing: You've started the repetition.
This algorithm has the considerable benefit of always being correct.
So what do I do?
I think your teacher wants you to figure out the second one, and not to delve into the BigDecimal API.
This is an awesome exercise, but more about math than programming.

Rounding in AS400/RPG vs Rounding in Java

I'm trying to convert some AS400/RPG code into Java.
I was able to find an example online that mirrored what I am seeing in the code:
d elevensix s 11 6 inz(26285.88991)
d seventwo s 7 2
c eval(h) seventwo = elevensix
c eval *inlr = *on
I have written code in Java and I am finding that the results of the rounding I see in the RPG code, it is not matching the type of rounding I see in Java. Here is a sample of the rounding I am doing in Java:
private Long roundAmount(Double amount) {
return Math.round(amount);
}
In practice my code generates results that match up to the results from the RPG code however I am finding examples which are inconsistent in the logic; some which round up as expected and others that don't.
I have worked heavily with Java; this is my first foray into RPG. I'm honestly not even sure where to begin. For example, in the RPG code above; how exactly is it working? I see the results of the operation being put into a variable marked with 2 decimal places; is the rounding implicit? Searching online I find the following definition for how Java handles rounding:
The Math.round() method in Java is used to round a number to its​
closest integer. This is done by adding 1/2 to the number,
taking the floor of the result, and casting the result to an integer
data type.
Honestly this is clear and concise. I have not found a comparable explanation for how it works in RPG; to be clear this is programming on an AS400 which uses RPG, but a much older version than what I believe the current standard is. However an explanation even for the modern implementation would be a start.
The RPG code you posted does a different thing than your Java code.
The Java code transform a Double to a Long, while the RPG code is rounding a number with 6 decimals to a number with 2 decimals.
In particular, elevensix is a number with 11 digits which 6 of them are for the decimal part and 5 of them for the integer part; seventwo is a number with 7 digits which 2 of them are for the decimal part and 5 of them for the integer part.
eval(h) is copying the value of elevensix into seventwo and rounding it to 2 decimal digits with "half-adjust" logic (that's what the "h" stand for, without it the decimals would be truncated).
From the RPG documentation (that you can find also in PDF format) and in particular here:
Half-adjusting is done by adding 5 (-5 if the field is negative) one
position to the right of the last specified decimal position in the
result field.
Which to me seems similar to what Math.round does, but generalized to any decimal position.
Also it would correspond to the Java Math RoundingMode.HALF_UP.
Since you didn't provide some actual examples that generate the inconcistencies it's difficult to give you a definitive solution.
Anyway, that RPG code in Java could be replicated with BigDecimals with the method setScale like this:
double result = new BigDecimal(amount.toString())
.setScale(2, RoundingMode.HALF_UP)
.doubleValue();
You might also consider to use Apache Commons Math method round which, looking at the implementation, does pretty much the same thing.
Your problem could also be caused by the limited precision of Double and in that case you should just use BigDecimals, see Double vs. BigDecimal?.

E appended onto double in Java [duplicate]

This question already has answers here:
Long float-number output shows letters
(5 answers)
Closed 2 years ago.
I'm working on creating a workbench for testing the performance of sorting algorithms. For some of my performance stats, it appears that the results aren't being returned correctly. Larger values are being stored as decimals with an E towards the end for example 1.2497388E7 instead of an 8 digit whole number. I'm just wondering if anyone knows what might be causing this.
Results from Running sorting algorithm for various sizes of arrays
Thanks
This is common mathematical notation to show that the number is what is displayed x10^ what's after E :)
For example:
1.24E5 = 124000 (1.24*10^5).
In other words: It's just a really big number
I don't think that this is a problem with the data itself (that should be stored correctly); it's probably more to do with how you are outputting it.
When your number is over a certain threshold of size, it is common to notate it in a compressed fashion using E. This is used to denote standard form, which is where a number is written in the form number x 10^n.
If you are using the standard System.out functions for the console, it is probably being formatted that way automatically due to size.
If you want to prevent this, use System.out.printf with the %f flag for formatting.
For example:
double number = 10.5;
System.out.printf("Value at double is: %f\n", number);
For more info, see the format documentation

Math twenty four game Java [duplicate]

This question already has answers here:
Building a math game in Java
(3 answers)
Closed 8 years ago.
The 24 Game is an arithmetical game in which the objective is to find a way to manipulate four integers so that the end result is 24. Addition, subtraction, multiplication, or division in any order of the numbers may be used to make the four digits operations from one to nine equal 24.
The rules are simple: you have to use each number only once and only the 4 numbers that were read from the user to find one equation to obtain 24.
For example, for the numbers 4,7,8,8, a possible solution is: (7-(8/8))*4=24.
Most sets of 4 digits can be used in multiple equations that result in 24: for example the input: 2, 2, 4 and 7 can be used in multiple ways to obtain 24:
2+2*(4+7) = 24
2+2*(7+4) = 24
(2+2)*7-4 = 24
(2*2)*7-4 = 24
2*(2*7)-4 = 24
There are also combinations of 4 numbers that cannot result into any equation equal with 24. For example 1,1,1,1. In this case, your program should return that there is no possible equation equal with 24.
Note: Although we will enter 4 integers between 1 and 9, we will use doubles to compute all the operations. For example, the numbers 3,3,8,8 can be combined into the formula: 8/(3-8/3) = 24.
Workflow: Your program should read the 4 numbers from the user and output a formula that results in 24. The algorithm should enumerate all the possible orders of 4 numbers, all the possible combinations and all the possible formulas. There is no required GUI for this project I need help with a method that will shuffle the operators for all 64 possible combos so 4 operators and 3 being used in each equation and also account for parenthesis during the equations . I have no idea where to begin.
If you can generate permutations of a string. You need to do that for all the numbers to get all the permutations possible for those numbers.
Now you just need to plugin permutations of operators (3 at a time).
For that you can generate all the permutations of the operators and store them in an array, as that would remain constant for each case. And out of each permutation generated, just pick the first 3 characters as we are looking at groups of 3 out of the 4 possible.
Once you have that, it's simply a matter of reading a permutation of the numbers and then reading a permutation of operators and evaluating the expression.
For reference, I have made a simple demo of a function that finds permutations of a string in Java. The recursive function looks something like (from a relevant SO Post):
public void permut(String str1,String str2){
if(str2.length() != 0){
char ch = str2.charAt(0);
for(int i = 0; i <= str1.length();i++)
permut(str1.substring(0,i) + ch + str1.substring(i,str1.length()),
str2.substring(1,str2.length()));
}else{
System.out.println(str1);
}
}
If you can successfully generate all permutations of a string, the above exercise should be doable. I hope it gets you started in the right direction.

Finding a missing integer, given 4 billion unsorted integers [duplicate]

This question already has answers here:
Generate an integer that is not among four billion given ones
(38 answers)
Closed 8 years ago.
I came across this interview questions and I was trying to understand how to approach this problem. I read this question on SO. I understood the approach of the author of the post, however I do not understand the approach suggested in the accepted answer. So I moved to this blog. According to this blog we can calculate the number of zeroes and ones at each of the bit positions and from that we can find out the missing number. But then for that the file should have 2^32-1 numbers which is greater than 4 billion. So that method should not work right? I am sure there is something wrong in my understanding, but I just can't figure out the missing link.
If you had a "complete" sequence of numbers from 0 to 2^N-1 then the number of bits set in each bit position would be equal (and equal to (2^N)/2).
If only one number is missing, then it's 1 bits correspond to the bit positions that are short one bit count.
Note that this only works for powers of 2, but possibly one can work out more complex formulae for "odd" counts.
add the intergers up using long
subtract the result from (N+1)*(N+2)/2 where N is the number of integers in your file. The result is your missing number
Example:
file contains 1,3
sum = 4
N=2, so (N+1)(N+2)/2 = (2+1)(2+2)/2 = 6
6-sum=6-4=2
2 is your missing number

Categories

Resources