Create several integers with a formula? - java

Is there a way to do what the title suggests? What I'm trying to do is create a table of experience values required to level up like so:
int level1 = 50;
int level2 = level1 + (level1 * 0.1);
int level3 = level2 + (level2 * 0.1);
But I want to get to around 100 levels... Is there a way to quickly define x number of usable int values?

Assuming you're continuing that formula...
int[] array = new int[100];
array[0] = 50;
for (int i = 1; i < 100; i++) {
array[i] = (int) (array[i - 1] * 1.1);
}

Use this approach:
public class Level
{
public Level()
{
int[] levels = new int[100]; // 100 Levels
initializeLevels(levels);
printLevels(levels);
}
private void initializeLevels(int[] levels)
{
levels[0] = 50;
for (int i = 1; i < 100; i++)
{
levels[i] = (int) (levels[i - 1] * 1.1f);
}
}
private void printLevels(int[] levels)
{
for (int i = 0; i < 100; i++)
{
System.out.println("Level " + (i + 1) + " = " + levels[i]);
}
}
public static void main(String[] args)
{
new Level();
}
}

Related

Cannot invoke "City.getX()" because "city[i]" is null

Hey Im working on a homework and i got stuck, i need to return the name of the two citys with the least amount of distance between them, the citys must be in order that the second one is after the first one (first i, second i+1);
Thanks.
public class Maincity {
public static void main(String[] args) {
City [] cityArr = new City[10];
String[] nameArr = new String[] {"Hadera","Beer Sheva","Haifa", "Ashdod", "Eilat", "Jerusalem", "Ashkelon", "Tel Aviv", "Hertzila", "Netanya"};
for (int i=0;i<cityArr.length;i++) {
int rRandom = (int)(Math.random() * 100000) + 10000;
int xRandom = (int)(Math.random() * 10000) + 1000;
int yRandom = (int)(Math.random() * 10000) + 1000;
City ir = new City(nameArr[i], rRandom, xRandom, yRandom);
System.out.println(ir);
}
System.out.println(Distance(cityArr));
}
public static int Distance(City[] city) {
int min = 100000000;
for (int i = 0; i < city.length; i++) {
int newX = city[i].getX() - city[i + 1].getX();
int newY = city[i].getY() - city[i + 1].getY();
newX = (int) Math.pow(newX, 2);
newY = (int) Math.pow(newY, 2);
int nDistance = (int) (Math.sqrt(newX) + Math.sqrt(newY));
if (nDistance < min) {
min = nDistance;
}
}
return min;
}
}
There were 2 problems:
You didn't put the city into array.
The index calculation (i+1) throwed ArrayIndexOutOfBoundsException
public static void main(String[] args) {
String[] nameArr=new String[] {"Hadera","Beer Sheva","Haifa", "Ashdod", "Eilat", "Jerusalem", "Ashkelon", "Tel Aviv", "Hertzila", "Netanya"};
City [] cityArr= new City[nameArr.length];
for(int i=0;i<cityArr.length;i++) {
int rRandom = (int)(Math.random()*100000)+10000;
int xRandom = (int)(Math.random()*10000)+1000;
int yRandom = (int)(Math.random()*10000)+1000;
City ir = new City(nameArr[i],rRandom, xRandom, yRandom);
cityArr[i] = ir;
System.out.println(ir);
}
System.out.println(Distance(cityArr));
}
public static int Distance(City[] city) {
int min =100000000;
for(int i=0;i<city.length;i++) {
int nextCityIndex = (i+1) % city.length;
int newX =city[i].getX() - city[nextCityIndex].getX();
int newY =city[i].getY() - city[nextCityIndex].getY();
newX = (int) Math.pow(newX, 2);
newY = (int) Math.pow(newY, 2);
int nDistance = (int) (Math.sqrt(newX)+Math.sqrt(newY));
if(nDistance<min) {
min=nDistance;
}
}
return min;
}

Create bar graph using Java

I am working on an assignment to create a bar graph using Java using random numbers, but I do not know how to code it properly, it keeps on giving errors when I move on to the next step.
public class BinSort {
final int N_BINS = 0; //number of bins
final int N_SAMPLES = 0; //total random integers
final float BIN_WIDTH = 0; //width of the bin
int [] nums; //generate and store random numbers
int [] binCount; //array
int max = 0; //largest random number = (max-1)
public void main(String[] args) {
int nBins, nSamples; //initializers
BIN_WIDTH = (float) (max/N_BINS); //calculate BIN_WIDTH
nums = new int[] {}; //initialize nums array
for (int i = 0; i < max; i++) {
int array = nums[i];
}
}
public void generateBins() {
int bin;
int [] binCount = new int [N_BINS]; //set binCount array with N_BINS elements
for (int i = 0; i < N_SAMPLES; i++) {
int array = binCount[i];
bin = (int) Math.floor(nums[i]/BIN_WIDTH);
}
}
public void printBins() {
float freq;
for(int i = 0; i < binCount.length; i++) {
freq = (binCount[i]/N_SAMPLES);
System.out.print(N_SAMPLES + " random integers in " + binCount + " sorted into " + N_BINS + " bins:");
float binMin = i * BIN_WIDTH;
float binMax = binMin + BIN_WIDTH;
System.out.println(binCount[i] + freq + binMin + binMax);
}
}
}
This code is incomplete, but I do not know what to do next. So, I am stuck.
Can someone please help me?
Edit: The program does not compile after running in eclipse. It says the execution is terminated in the console.
Only static variables can be used in the static method . Below code is compiling fine:
public class BinSort {
static final int N_BINS = 0; //number of bins
static final int N_SAMPLES = 0; //total random integers
static float BIN_WIDTH = 0; //width of the bin
static int [] nums; //generate and store random numbers
int [] binCount; //array
static int max = 0; //largest random number = (max-1)
public static void main(String[] args) {
int nBins, nSamples; //initializers
BIN_WIDTH = (float) (max/N_BINS); //calculate BIN_WIDTH
nums = new int[] {}; //initialize nums array
for (int i = 0; i < max; i++) {
int array = nums[i];
}
}
public void generateBins() {
int bin;
int [] binCount = new int [N_BINS]; //set binCount array with N_BINS elements
for (int i = 0; i < N_SAMPLES; i++) {
int array = binCount[i];
bin = (int) Math.floor(nums[i]/BIN_WIDTH);
}
}
public void printBins() {
float freq;
for(int i = 0; i < binCount.length; i++) {
freq = (binCount[i]/N_SAMPLES);
System.out.print(N_SAMPLES + " random integers in " + binCount + " sorted into " + N_BINS + " bins:");
float binMin = i * BIN_WIDTH;
float binMax = binMin + BIN_WIDTH;
System.out.println(binCount[i] + freq + binMin + binMax);
}
}
}

Octave to Java - InitializeThetas Function

Hi guys I´m new in java.
I'm trying to convert an octave function in to Java(using JBlas) but I´m not sure how to do this line:
OCTAVE: Thetas{i} = rand(sizes(i+1), sizes(i) + 1)*2*EPSILON-EPSILON;
My code in Java:
public class InitializeThetas {
public static DoubleMatrix InitializeThetas(DoubleMatrix sizes, double epsilon)
{
int L= sizes.length;
epsilon = 0.03;
DoubleMatrix Thetas = new DoubleMatrix(new double[]{});
Random r = new Random();
for (int i = 1; i <= L - 1; i++)
{
//Thetas{i} = rand(sizes(i+1), sizes(i) + 1)*2*EPSILON-EPSILON;
Thetas.data[i]= r.nextInt() * 2 * epsilon - epsilon;
}
return Thetas;
}
}
Is this close to what you want?
public class InitializeThetas {
public static Collection<DoubleMatrix> InitializeThetas(DoubleMatrix sizes, double epsilon)
{
int L= sizes.length;
epsilon = 0.03;
Collection<DoubleMatrix> Thetas = new ArrayList<DoubleMatrix>();
for (int i = 0; i < L - 1; i++)
{
Thetas.add(DoubleMatrix.rand(Double.valueOf(sizes.get(i + 1)).intValue(), Double.valueOf(sizes.get(i)).intValue() + 1).mul(2).mul(epsilon).sub(epsilon));
}
return Thetas;
}
public static void main(String[] args) {
DoubleMatrix soze = new DoubleMatrix(10);
for(int i = 0;i<10;i++){
soze.put(i,i+1);
}
System.out.println(InitializeThetas(soze,1.1));
}
}

How to compare integer elements within ArrayList?

I am trying to solve a problem by fetching the maximum number from each row in a triangle. So far am able to generate a triangle but how do I fetch the max number from each row?
Here is my code
private static Integer solve(Triangle triangle)
{
//triangle is extending an ArrayList
System.out.println(triangle);
return 0;
}
This is what am producing so far:
6
3 5
9 7 1
4 6 8 4
but now I want to get the result which says:
"In this triangle the maximum total is: 6 + 5 + 9 + 8 = 26"
Here is the complete code:
public class HellTriangle {
private static final int TRIANGLE_HEIGHT = 10;
public static void start() {
Triangle triangle = generateTriangle();
//System.out.println(triangle);
long start = System.currentTimeMillis();
Integer result = solve(triangle);
long end = System.currentTimeMillis();
System.out.println("Result:" + result);
System.out.println("Resolution time: " + (end - start) + "ms");
}
private static Triangle generateTriangle() {
Triangle triangle = new Triangle();
Random random = new Random();
for (int i = 0; i < TRIANGLE_HEIGHT; i++) {
Row row = new Row();
for (int j = 0; j <= i; j++) {
row.add(random.nextInt(100));
}
triangle.add(row);
}
return triangle;
}
private static class Row extends ArrayList<Integer> {
public String toString() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < size(); i++) {
sb.append(String.format("%02d", get(i)));
//rows.add(get(i));
if (i < (size() - 1)) {
sb.append(" ");
}
}
return sb.toString();
}
}
private static class Triangle extends ArrayList<Row> {
public String toString() {
// sb is used to make modification to the String
StringBuilder sb = new StringBuilder();
for (int i = 0; i < size(); i++) {
for (int j = 0; j < (TRIANGLE_HEIGHT - 1 - i); j++) {
sb.append(" ");
}
sb.append(get(i));
if (i < (size() - 1)) {
sb.append("\n");
}
}
return sb.toString();
}
}
private static Integer solve(Triangle triangle) {
System.out.println(triangle);
return 0;
}
public static void main(String[] args) {
start();
}
}
Any help would be appreciated!
Here, just change with your solve()
private static void solve(Triangle triangle) {
System.out.println(triangle);
ArrayList<Integer> result = new ArrayList<Integer>();
int total = 0;
for(Row row : triangle){
Collections.sort(row);
total += row.get(row.size()-1);
result.add(row.get(row.size()-1));
}
for(Integer intr : result)
System.out.println("Largest elements of the rows: " + intr);
System.out.println("Total: " + total);
}
As there is no ordering in your rows and this would lead to O(n) to get the maximum value per row i would look up the maximum value during insertion. Something like that (not tested and you probably have to override the other add methods also, depending on your use case):
public class Row extends ArrayList<Integer> {
public String toString() {
...
}
private Integer max = null;
#Override
public boolean add(Integer elem) {
if (elem != null && (max == null || max < elem)) {
max = elem;
}
return super.add(elem);
}
public Integer getMax() {
return max;
}
}
Try
private static int getTriangleMax(final Triangle rows)
{
int max = 0;
for (final Row row : rows)
{
final int rowMax = getRowMax(row);
max += rowMax;
}
return max;
}
private static int getRowMax(final Row row)
{
int rowMax = Integer.MIN_VALUE;
for (final Integer integer : row)
{
if (rowMax < integer)
{
rowMax = integer;
}
}
return rowMax;
}
Simple-Solution:
1.Add the static list as here:
private static List maxRowVal=new ArrayList();
2.Replace your generateTriangle() function with this:
private static Triangle generateTriangle()
{
Triangle triangle = new Triangle();
Random random = new Random();
for (int i = 0; i < TRIANGLE_HEIGHT; i++) {
Row row = new Row();
int maxTemp=0;
for (int j = 0; j <= i; j++) {
int rand=random.nextInt(100);
row.add(rand);
if(rand>maxTemp)
maxTemp=rand; //will get max value for the row
}
maxRowVal.add(maxTemp);
triangle.add(row);
}
return triangle;
}
Simple indeed!!
This is not exactly what you asked for, but I would like to show you a different way to go about this problem. People have done this for me before, and I really appreciated seeing different ways to solve a problems. Good luck with your coding!
Below is the code in its entirety, so you can just copy, paste and run it.
public class SSCCE {
public static void main(String[] args) {
// Here you specify the size of your triangle. Change the number dim to
// whatever you want. The triangle will be represented by a 2d-array.
final int dim = 5;
int[][] triangle = new int[dim][dim];
// Walks through the triangle and fills it with random numbers from 1-9.
for (int r = 0; r < dim; r++) {
for (int c = 0; c < r + 1; c++) {
triangle[r][c] = (int) (9 * Math.random()) + 1;
}
}
// This piece just prints the triangle so you can see what's in it.
for (int r = 0; r < dim; r++) {
for (int c = 0; c < r + 1; c++) {
System.out.print(triangle[r][c] + " ");
}
System.out.println();
}
// This part finds the maximum of each row. It prints each rows maximum
// as well as the sum of all the maximums at the end.
int sum = 0;
System.out.print("\nIn this triangle the maximum total is: ");
for (int r = 0; r < dim; r++) {
int currentMax = 0;
for (int c = 0; c < r + 1; c++) {
if (triangle[r][c] > currentMax) {
currentMax = triangle[r][c];
}
}
sum += currentMax;
if (r != 0) {
System.out.print(" + ");
}
System.out.print(currentMax);
}
System.out.println(" = " + sum + ".");
}
}
Output:
9
9 2
1 7 3
1 7 3 3
5 7 5 1 9
In this triangle the maximum total is: 9 + 9 + 7 + 7 + 9 = 41.

Weighted random numbers: boundary case

In reference to the top answer given in this post, I've noticed that it fails for a boundary case when rnd=sum_of_weight. The fix is to generate random numbers in [0,sum_of_weight), however i was wondering why the code fails for this boundary case? Is it a flaw in the algorithm?
EDIT: Also, does the weight array need to be sorted high to low? It seems so, based on the subtraction loop.
Below is the Java code that implements the pseudo-code in the above post.
int sum_of_weight = 0;
int []choice_weight = {50, 15, 15, 10, 10}; // percentages
int num_choices = choice_weight.length;
public void init() {
for (int i = 0; i < num_choices; i++) {
sum_of_weight += choice_weight[i];
}
}
int next() {
int rnd = (int)Util.between(0, sum_of_weight);// random(sum_of_weight);
rnd=sum_of_weight; // force the exception by hitting boundary case
//System.out.print("rnd=" + rnd);
for (int i = 0; i < num_choices; i++) {
if (rnd < choice_weight[i])
return i;
rnd -= choice_weight[i];
}
throw new RuntimeException("should never get here for rnd=" + rnd);
}
public static void main(String[] args) {
SimpleWeight sw = new SimpleWeight();
sw.init();
for (int i=0; i < 10;i++) {
System.out.println(sw.next());
}
}
Step 2 of the algorithm you link to states:
2) pick a random number between 0 and less than the sum weights.
To me, this reads clearly and unambiguously that the correct way is to pick a number from [0,sum_of_weight). Picking a number from a different range (e.g. any range that includes sum_of_weight) isn't a flaw in the algorithm, it's a flaw in the implementation of that algorithm.
edit No, the weights do not need to be sorted for the algorithm to work.
For those that find it useful, here is another implementation of the above. Open to feedback too if you want to make it better. I'm still a beginner.
import java.util.Random;
public class WeightedRandom {
private int choiceWeight[];
private int numChoices = 0;
private int i = 0;
private Random r = new Random();
public WeightedRandom() {
this.choiceWeight = new int[] { 60, 35, 5 };
this.numChoices = choiceWeight.length;
}
public WeightedRandom(int[] choiceWeight) {
this.choiceWeight = choiceWeight;
this.numChoices = this.choiceWeight.length;
}
public int weightedRandomGenerator() {
int sumOfWeight = 0;
for (int i = 0; i < numChoices; i++) {
sumOfWeight += choiceWeight[i];
}
int randomNumber = r.nextInt(sumOfWeight);
for (int i = 0; i < numChoices; i++) {
if (randomNumber < choiceWeight[i])
return i;
randomNumber -= choiceWeight[i];
}
throw new RuntimeException("should never get here for RandomNumber = " + randomNumber);
}
public void printWeightedAverage(int numberOfIterations) {
int numberCount[] = new int[numChoices];
for (int n = 0; n < numberOfIterations; n++) {
i = weightedRandomGenerator();
numberCount[i]++;
}
for (int n = 0; n < numChoices; n++)
System.out.println("Occurance of " + n + " = " + (((double) numberCount[n]) / numberOfIterations) * 100 + "%");
System.out.println("--------");
}
public static void main(String[] args) {
WeightedRandom wr = new WeightedRandom();
WeightedRandom wr2 = new WeightedRandom(new int[] { 49, 25, 15, 5, 3, 2, 1 });
wr.printWeightedAverage(100_000_000);
wr2.printWeightedAverage(100_000_000);
}
}

Categories

Resources