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;
}
Related
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);
}
}
}
I need to fill a 2D Array with numbers between 2 and 6, given by the user (is just part of a bigger proyect) but when I give the number I only get another request for a number.
public static int[][] crearTablero(int tamaño)
{
int[][] tablero = new int[tamaño][tamaño];
return tablero;
}
public static void imprimeTablero(int[][] tablero)
{
for(int i = 0; i<tablero.length; i++)
{
for(int j = 0; j<tablero[i].length; j++)
{
System.out.print(tablero[i][j] + " ");
}
System.out.println();
}
}
public static void swap(int[][] tablero, int x1, int y1, int x2, int y2)
{
int temp = tablero[x1][y1];
tablero[x1][y1] = tablero[x2][y2];
tablero[x2][y2] = temp;
}
public static void rellenarTablero(int[][] tablero) {
for (int x = 0; x < tablero.length; x++) {
for (int y = 0; y < tablero[x].length; y++) {
tablero[x][y] = aleatorio(numeroColores());
}
}
}
public static void shuffleBoard(int[][] tablero)
{
Random rnd = new Random();
int randX = 0;
for(int x = 0; x<tablero.length; x++)
{
randX = rnd.nextInt(tablero.length);
int[] temp = tablero[x];
tablero[x] = tablero[randX];
tablero[randX] = temp;
}
}
public static int numeroColores(){
int colores = 0;
System.out.print("Numero de colores (entre 2 y 6): ");
Scanner scn = new Scanner(System.in);
colores = scn.nextInt();
while(colores < 2 || colores > 6)
{
System.out.println("Invalid matrix size. Re-enter ");
}
return colores;
}
public static int aleatorio(int colores) {
int l = (int) (Math.floor(Math.random()*(colores-2)) + 2);
return l;
}
I would really appreciate some help because I don't know how to continue, Thanks.
You call numeroColores() in a for-loop in a for-loop, so you are of course asked multiple times for it.
Btw. you have an endless loop if you type in 1 or smaller or 7 or bigger with constantly getting the same line printed out and not asking for new input
Try this code to generate the random value between 2 and 6
public static int aleatorio(int colores) {
int l = 0;
while(l < 2 || l > 6) {
l = (int) (Math.floor(Math.random()*(colores-2)) + 2);
}
return l;
}
Situation with the code is I think that the for loop in the private method is not getting int[] userArray. I have spent hours trying to figure out why the for loop is not working, I even tried using while loop.
public class Arrays {
static Scanner scan = new Scanner(System.in);
private static int sizeOfArrayWanted;
private static double average = 0;
/**
* private static int smallestNumber=1;
*
* private static int count = 0; private static int total=0; private static
* int average=total/count; private static int largestNumber=0; private static
* int standardDeviation=0; private static int meanOfSD=0; private static int
* x1=0; private static int[] userArray= new int [0];
**/
private static int total1 = 0;
private static int standardDeviation = 0;
private static int finalAverage = 0;
public static void main(String[] args) {
// int randomNumber = (int)((Math.random() * 9) + 1);
System.out.println("Hello how big would you like the array?");
int sizeOfArrayWanted = scan.nextInt();
int smallestNumber = 1;
int largestNumber = 0;
int total = 0;
int standardDeviation = 0;
int count = 0;
double average = 0;
int[] userArray = new int[sizeOfArrayWanted];
for (int x = 0; x < sizeOfArrayWanted; x++) {
userArray[x] = (int) ((Math.random() * 9) + 0);
total = total + userArray[x];
count++;
if (userArray[x] < smallestNumber) {
smallestNumber = userArray[x];
}
if (userArray[x] > largestNumber) {
largestNumber = userArray[x];
}
System.out.print(userArray[x] + ", ");
average = total / count;
}
System.out.println("");
System.out.println("largest Number= " + largestNumber);
System.out.println("smallest Number= " + smallestNumber);
System.out.println("average =" + (total / count));
Arrays.computeStandardDeviation(userArray, sizeOfArrayWanted);
}
private static int computeStandardDeviation(int[] userArray, int sizeofArrayWanted) {
int x1 = 0;
while (x1 < sizeofArrayWanted) {
x1++;
userArray[x1] = (int) (userArray[x1] - average);
userArray[x1] = (int) Math.pow(userArray[x1], 2);
total1 = total1 + userArray[x1];
finalAverage = total1 / x1;
standardDeviation = (int) Math.sqrt(finalAverage);
}
return standardDeviation;
}
}
When I try to compile the program, I get the following errors:
Exception in thread "main" largest Number= 6
smallest Number= 1
average =4
java.lang.ArrayIndexOutOfBoundsException: 5
at Arrays.computeStandardDeviation(Arrays.java:80)
at Arrays.main(Arrays.java:67)
You increment x1 after the check. Making it 1 too large for array at last iteration. Move x1++ into average calculation.
while(x1<sizeofArrayWanted)
{
// x1++;
finalAverage = total1 / ++x1;
The issue is from the computeStandardDeviation method. The index starts at 0, so increasing it immediately will cause it not to look at the first spot in the array and therefore also check the last index + 1 location. It should be like this
private static int computeStandardDeviation(int [] userArray, int sizeofArrayWanted)
{
int x1=0;
while(x1<sizeofArrayWanted)
{
userArray[x1]=(int) (userArray[x1]-average);
userArray[x1]=(int) Math.pow(userArray[x1], 2);
total1=total1+userArray[x1];
finalAverage=total1/x1;
standardDeviation= (int) Math.sqrt(finalAverage);
x1++; // move this here
}
return standardDeviation;
}
Array index out of bounds exception is because you are incrementing x1 before doing operations, rather you should do all operations and increment x1 at the end. Otherwise, at the last iteration of the loop, you will be accessing an element outside the scope of the array.
private static int computeStandardDeviation(int[] userArray, int sizeofArrayWanted) {
int x1 = 0;
while (x1 < sizeofArrayWanted) {
userArray[x1] = (int) (userArray[x1] - average);
userArray[x1] = (int) Math.pow(userArray[x1], 2);
total1 = total1 + userArray[x1];
finalAverage = total1 / x1;
standardDeviation = (int) Math.sqrt(finalAverage);
x1++; //Increment should be done after all operations
}
return standardDeviation;
}
Also you dont need to pass the size parameter explicitly here, since you can just get the size from the array passed to the method.
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();
}
}
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));
}
}