Convert Percent to Odds Ratio and Reverse - formula

Easy softball for someone to knock out of the park: what is the correct coding formula for computing an odds ratio to a percent, and a percent to an odds ratio? Example:
Odds to Percent
1 in 8192 = 0.0001220
Percent to Odds
0.0001220 = 1 in 8192
Programming language is irrelevant.

odds_to_percent(a, b):
return str(float(a)/b)
percent_to_odds(x):
return '1 in ' + str(1.0/x)
Not sure what exactly you need. There are many decisions about rounding and co.

Here's what I came up with:
public struct Odds
{
private int _a;
private int _b;
public int A
{
get
{
return _a;
}
}
public int B
{
get
{
return _b;
}
}
public Odds(int a, int b)
{
this._a = a;
this._b = b;
}
public Odds(double percent)
{
Odds odds = FromPercent(percent);
this._a = odds.A;
this._b = odds.B;
}
public Odds Invert()
{
return new Odds(_b, _a);
}
public double ToPercent()
{
return ToPercent(_a, _b);
}
public static double ToPercent(int a, int b)
{
return ((double)a / (b + a));
}
public static Odds FromPercent(double percent)
{
int multiplier = GetDecimalMultiplier(percent);
return new Odds(1, (multiplier - (int)(percent * multiplier)) / (int)(percent * multiplier));
}
private static int GetDecimalMultiplier(double n)
{
if (n > 0.01)
{
return 100;
}
if (n > 0.001)
{
return 100000;
}
if (n > 0.0001)
{
return 100000000;
}
throw new Exception("Number too small!");
}
public override string ToString()
{
return A + "-" + B;
}
}
Odds to Percent:
public static double ToPercent(int a, int b)
{
return ((double)a / (b + a));
}
Percent to Odds(May not be perfect)
public static Odds FromPercent(double percent)
{
int multiplier = GetDecimalMultiplier(percent);
return new Odds(1, (multiplier - (int)(percent * multiplier)) / (int)(percent * multiplier));
}
private static int GetDecimalMultiplier(double n)
{
if (n > 0.01)
{
return 100;
}
if (n > 0.001)
{
return 100000;
}
if (n > 0.0001)
{
return 100000000;
}
throw new Exception("Number too small!");
}

Related

Check if a number is prime using recursion

This is a recursive check if this is a prime number -- is it correct?
public static boolean isPrimeRecursive (int n,int i){//i eqoual to n
if (n <= 1) {
return false;
}if (i==1){
return false;
}if(n%i==0){
return false;
}
return isPrimeRecursive(n,i--);
}
I wouldn't burden your user with that mysterious second argument but rather present a different method of just one argument, that first deals with numbers less than 2 and even numbers, and then calls into your recursive method with the proper arguments:
private static boolean isPrimeRecursive(int n, int i) {
if (i * i > n) {
return true;
}
if (n % i == 0) {
return false;
}
return isPrimeRecursive(n, i + 2);
}
public static boolean isPrime(int n) {
if (n <= 2 || n % 2 == 0) {
return (n == 2);
}
return isPrimeRecursive(n, 3);
}
public static void main(String[] args) {
System.out.println(isPrime(Integer.parseInt(args[0])));
}
With your code, you should start of i with a value of n-1 since n % n is always true of prime numbers.
Then in your condition (if (i == 1) { ... }, should return true because if the method reaches to 1, then it fulfills all other conditions.
Finally in your return statement return isPrimeRecursive(n, i++);, it is better to use ++i since i++ will increment after the execution of the function with the value of i.
public static boolean isPrimeRecursive (int n,int i){
if (n <= 1) {
return false;
}
if (i == 1) {
return true;
}
if(n % i == 0){
return false;
}
return isPrimeRecursive(n, --i);
}
In your main function, you will then use:
int n = 17;
System.out.println(isPrimeRecursive(n, n-1);
Another way of doing it is to always start i with a value of 2 and increment it's value. From there.
public static boolean isPrimeRecursive (int n, int i) {
if (n <= 2) {
return (n == 2) ? true : false;
}
if (i >= n) {
return true;
}
if (n % i == 0) {
return false;
}
return isPrimeRecursive(n, ++i);
}
Then you simple do:
int n = 17;
System.out.println(isPrimeRecursive(n, 2);

Breadth-First Search with obstacles

I'm currently making a game as a school project and I'm trying to figure out the pathfinding of enemies. I've made a basic BFS which works pretty well but does not take in account obstacles, so enemies are stuck by an obstacle is there's one when trying to reach the player. I've tried different things but all I got was null pointer (which I kind of understand, but I don't know how to make this works).
public class BFS {
private Player player;
private Field field;
private Queue<Tile> queue;
private HashMap<Tile, Tile> parents;
private ArrayList<Tile> adjTiles;
public BFS(Player player, Field field) {
this.player = player;
this.field = field;
this.queue = new LinkedList<>();
this.parents = new HashMap<Tile, Tile>();
this.adjTiles = new ArrayList<>();
}
public void lancerBFS() {
int x = player.getIndiceX();
int y = player.getIndiceY();
Tile player = field.getNextTile(y, x);
this.parents.clear();
this.queue.clear();
this.adjTiles.clear();
this.queue.add(field.getNextTile(y, x));
this.parents.put(field.getNextTile(y, x), field.getNextTile(y, x));
while (!queue.isEmpty()) {
Tile temp = queue.remove();
y = temp.getI();
x = temp.getJ();
if (x > 0) {
this.adjTiles.add(field.getNextTile(y, x-1));
}
if (y > 0) {
this.adjTiles.add(field.getNextTile(y-1, x));
}
if (x < 24) {
this.adjTiles.add(field.getNextTile(y, x+1));
}
if (y < 24) {
this.adjTiles.add(field.getNextTile(y+1, x));
}
for (int i = 0 ; i < adjTiles.size() ; i++) {
if (!this.parents.containsKey(adjTiles.get(i))) {
this.parents.put(this.adjTiles.get(i), temp);
this.queue.add(this.adjTiles.get(i));
}
}
this.adjTiles.clear();
}
}
public Tile searchWay(AnimatedEntity entity) {
int x = entity.getIndiceX();
int y = entity.getIndiceY();
Tile t = this.field.getNextTile(y, x);
return this.parents.get(t);
}
public HashMap<Tile, Tile> getParents() {
return parents;
}
}
How I use it (my tiles are 32x32 on a 25x25 map, and enemies move 4 pixels by 4 pixels)
public void moveEnemy(AnimatedEntity e) {
Tile nextTile = this.bfs.searchWay(e);
Tile enemyAt = this.map.getNextTile(e.getIndiceY(), e.getIndiceX());
if (nextTile.getI() == enemyAt.getI() && nextTile.getJ() < enemyAt.getJ()) {
e.moveLeft(entities, inanimatedEntities);
}
if (nextTile.getI() < enemyAt.getI() && nextTile.getJ() == enemyAt.getJ()) {
e.moveUp(entities, inanimatedEntities);
}
if (nextTile.getI() == enemyAt.getI() && nextTile.getJ() > enemyAt.getJ()) {
e.moveRight(entities, inanimatedEntities);
}
if (nextTile.getI() > enemyAt.getI() && nextTile.getJ() == enemyAt.getJ()) {
e.moveDown(entities, inanimatedEntities);
}
}
How enemies get stuck in game:
How enemies get stuck after trying to include isObstacle notion

Calculation exponential growth with recursion

So I'm trying to figure out how to calculate a stock's exponential growth with recursion. The stock's original value, the percentage and the number of years is given by the user.
This is what I thought would work but I was proven wrong. Any ideas?
public static void main(String[] args) {
String cheese = JOptionPane.showInputDialog("Stock price.");
double v = Double.parseDouble(cheese);
String mayo = JOptionPane.showInputDialog("Percentage.");
double p = Double.parseDouble(mayo);
String ham = JOptionPane.showInputDialog("Years.");
double n = Double.parseDouble(ham);
System.out.println(stockGrowth(v, p, n));
}
static double stockGrowth(double v, double p, double n) {
if (n > 0) {
return stockGrowth(v * Math.pow(p, n)) + Math.pow(p, n - 1);
} else {
return v;
}
}
Cheers.
If p=0.05 (that is 5%) then one year later v has grown to v*1.05 = v*(1+p).
This leads to the following definition:
static double stockGrowth(double v, double p, double n) {
if (n > 0) {
return stockGrowth(v * (1+p), p, n - 1);
} else {
return v;
}
}

Heapsort Error during runtime

Here is a heapsort program I've created in Java, but I'm having an issue where it won't run.
I'm not getting any errors during compilation, which made the error hard to identify, but if I comment out the size decrement in my extract maximum function the program will run, so I assume that's where the error is. Unfortunately, that line is crucial to the program functioning properly.
If there's anything simple causing this problem, or if major adjustments need to be made to the program, I'd like to know either way.
All input is welcome.
Update
added main function.
Code can now be copy-and-pasted to run.
public class Heap
{
private int [] data;
private int [] fin;
private int size;
private int tmp = 0;
/**
* Constructor for objects of class Heap
*/
public Heap(int[] A)
{
data = A;
size = data.length;
fin = new int [size];
this.buildHeap(0);
for(int n = size - 1; n >= 0; n--)
{
fin[n] = this.extractMax();
}
}
public int getSize()
{
return size;
}
private void setSize(int i)
{
size = i;
}
public void print()
{
for(int i = 0; i < this.getSize(); i++)
System.out.printf("%d\n", fin[i]);
}
/**
* build heap using top down method
*
* #param i the index of the node being built upon
*/
private void buildHeap(int i)
{
if(i <= (size - 2)/2)
{
buildHeap(2*i + 1);
buildHeap(2*i + 2);
heapify(i);
}
}
/**
* Extract maximum number
*
* #return maximum number of heap
*/
private int extractMax()
{
int n = size;
int store = 0;
store = data[0];
data[0] = data[n - 1];
size--;
this.heapify(0);
return store;
}
/**
* Heapify array
*
* #param i the index to heapify upon
*/
private void heapify(int i)
{
if(2*i + 1 < size && data[2*i + 1] > data[i])
{
if(2*i + 2 < size && data[2*i + 2] > data[2*i + 1])
{
this.exchange(i, 2*i + 2);
heapify(2*i + 2);
}
else
{
this.exchange(i, 2*i + 1);
heapify(2*i + 1);
}
}
if(2*i + 2 < size && data[2*i + 2] > data[i])
{
this.exchange(i, 2*i + 2);
heapify(2*i + 2);
}
}
private boolean exchange(int i, int k)
{
tmp = data[i];
data[i] = data[k];
data[k] = tmp;
return true;
}
public static void main(String [] args)
{
int [] arr = {5,13,2,25,7,17,20,8,4};
Heap heapsort = new Heap(arr);
heapsort.print();
}
}

Recursively searching a tree to get the binary coding for a character

Hi im trying to figure out how to recursively search a tree to find a character and the binary code to get to that character. basically the goal is to go find the code for the character and then write it to a file. the file writer part i can do no problem but the real problem is putting the binary code into a string. while im searching for the character. please help!
this is the code for the recursive method:
public String biNum(Frequency root, String temp, String letter)
{
//String temp = "";
boolean wentLeft = false;
if(root.getString() == null && !wentLeft)
{
if(root.left.getString() == null)
{
temp = temp + "0";
return biNum(root.left, temp, letter);
}
if(root.left.getString().equals(letter))
{
return temp = temp + "0";
}
else
{
wentLeft = true;
temp = temp.substring(0, temp.length() - 1);
return temp;
}
}
if(root.getString() == null && wentLeft)
{
if(root.right.getString() == null)
{
temp = temp + "1";
return (biNum(root.right, temp, letter));
}
if(root.right.getString().equals(letter))
{
return temp = temp + "1";
}
else
{
wentLeft = false;
temp = temp.substring(0, temp.length() - 1);
return temp;
}
}
return temp;
}
and this is the Frequency class:
package huffman;
public class Frequency implements Comparable {
private String s;
private int n;
public Frequency left;
public Frequency right;
private String biNum;
private String leaf;
Frequency(String s, int n, String biNum)
{
this.s = s;
this.n = n;
this.biNum = biNum;
}
public String getString()
{
return s;
}
public int getFreq()
{
return n;
}
public void setFreq(int n)
{
this.n = n;
}
public String getLeaf()
{
return leaf;
}
public void setLeaf()
{
this.leaf = "leaf";
}
#Override
public int compareTo(Object arg0) {
Frequency other = (Frequency)arg0;
return n < other.n ? -1 : (n == other.n ? 0 : 1);
}
}
In your updated version, I think you should re-examine return biNum(root.left, temp, letter);. Specifically, what happens if the root node of the entire tree has a left child which is not a leaf (and thus root.left.getString() == null) but the value you seek descends from the right child of the root node of the entire tree.
Consider this tree, for example:
26
/ \
/ \
/ \
11 15
/ \ / \
/ B A \
6 5 6 9
/ \ / \
D \ C sp
3 3 4 5
/ \
E F
2 1
and trace the steps your function will follow looking for the letter C.
Perhaps you should consider traversing the entire tree (and building up the pattern of 1s and 0s as you go) without looking for any specific letter but taking a particular action when you find a leaf node?

Resources