I am learning to code Java, and in a tutorial I learned to make the percentage of the percentage of wins I got. I am really confused what the integer "a" does exactly. Can someone please explain it in simple terms? (because I'm a complete newb)
double numOfGames = 10000;
double arrayNum = 1;
Random r = new Random();
int[] num = new int[(int) arrayNum]; // same as "= {0,0,0,0,0}
boolean gameResult = true;
boolean[] odds = new boolean[(int) numOfGames];
double numOfWins = 0;
for (int a = 0; a < numOfGames; a++) {
for (int i = 0; i < num.length; i++) {
num[i] = r.nextInt(100) + 1;
if (num[i] % 2 == 0) {
} else {
gameResult = false;
}
}
if (gameResult) {
odds[a] = true;
}
gameResult = true;
}
for (int i = 0; i < odds.length; i++) {
if (odds[i]) {
numOfWins++;
}
}
double perWin = (numOfWins / numOfGames) * 100;
System.out.println(perWin + " % of an array with " + arrayNum
+ " positions.");
}
}
It's a counter.
Basically it goes up by one every time that code block is run, in plain English this:
for (int a = 0; a < numOfGames; a++) {
// Do things.
}
Is like saying "Start counting at 0; Do things repeatedly until the counter reaches numOfGames".
a++ is just shorthand for a = a + 1 or "add 1 to a".
int = a is a local variable (an integer number) that increases by one in each iteration of your for loop. it simply goes from 0 to the total number of games, in this case: 10000. when it reaches the number of total games, it is discarded.
Related
Im using a while-loop to check if there is a matching number in an array. But when there is, it appears the loop becomes endless and doesnt stop running
Im very new to java, so I havent tried a lot of things because I dont know what will work and what will not.
I believe the problem lies within the fyllArray or sjekkArray.
NOTE: Im norwegian, so a lot of things I can name myself (variables?) are in norwegian, but I think anyone can understand it.
import java.text.DecimalFormat;
import static javax.swing.JOptionPane.*;
class UnikeTall{
java.text.DecimalFormat df = new DecimalFormat("0.0");
static int[] array;
boolean likt = false;
int min = 1000;
int max = 0;
private void setArray(int lengde){
array = new int[lengde];
}
private boolean sjekkArray(int tall){
for(int i = 0; i < array.length; i++){
if(tall == array[i]){
likt = true;
}
}
if(likt != true){
likt = false;
}
return likt;
}
private void fyllArray(){
int tall = 0;
boolean sjekk = false;
for(int i = 0; i < array.length; i++){
while(!sjekk){
tall = (int) (Math.random() * (900) + (100));
sjekkArray(tall);
if(likt == true){
continue;
}
if(likt == false) {
sjekk = true;
}
}
sjekk = false;
array[i] = tall;
}
}
private String sjekkMin(){
String lavest;
for(int i = 0; i < array.length; i++){
if(array[i] < min){
min = array[i];
}
}
lavest = "Minste tall er: " + min;
return lavest;
}
private String sjekkMax(){
String størst;
for(int i = 0; i < array.length; i++){
if(array[i] > max){
max = array[i];
}
}
størst = "Største tall er: " + max;
return størst;
}
private double gjennomsnitt(){
int sum = 0;
double snitt;
for(int i = 0; i < array.length; i++){
sum += array[i];
}
snitt = sum / array.length;
return snitt;
}
public void kjorArray(){
String utskrift = "";
int antall = 0;
int lengde = Integer.parseInt(showInputDialog("Hvor langt skal arrayet være?"));
//The text in the input box translates to: "How long do you want the array to be?"
setArray(lengde);
fyllArray();
for(int i = 0; i < array.length; i++){
if(antall < 5){
utskrift += array[i] + " ";
antall++;
}
else if(antall == 5){
utskrift += "\n" + array[i] + " ";
antall = 1;
}
}
utskrift += "\n";
utskrift += sjekkMin();
utskrift += "\n";
utskrift += sjekkMax();
utskrift += "\n";
String gsnitt = df.format(gjennomsnitt());
utskrift += "Snittet er: " + gsnitt;
showMessageDialog(null, utskrift);
}
}
public class oppgaveOblig3{
public static void main(String[] args){
new UnikeTall().kjorArray();
}
I would expect all the numbers in the array to be different. And that happens sometimes, but I believe that only happens when it works on the first try. When there is a matching number in the array, it stops.
But stopping, I mean the loop goes endless and my code stops at that point. Not getting any error codes because my program is still running
The sjekkArray method is supposed to check whether the value is already in your array, I think. Your problem is because you are using a object variable called likt in sjekkArray to pass the result of that test to the calling function fyllArray. But you fail to set likt to false at the beginning of sjekkArray. Because it's an object variable, once it is set to true, it will always stay true.
Make likt a local variable in sjekkArray and use the return value of sjekkArray in fyllArray.
In general, there are a lot of unnecessary complex ways of doing things in your code. It would be good if you could ask an experience programmer for guidance.
Hey guys I am trying to get the number of people who have the same birthday but this solution isn't working.This program is showing 0.0% .Please help me ...!.
public double calculate(int size, int count) {
int matches = 0;//initializing an integer variable
boolean out = false;
List<Integer> days=new ArrayList<Integer>();// creating arraylist name days of type int
for (int j = 0; j <count; j++) {
for (int i = 0; i < size; i++) {// initializing for loop till less than size
Random rand = new Random(); // creating an object of random function
int Brday = rand.nextInt(364) + 0;//initializing the limit of randomc number chozen
days.add(Brday); //adding values to arraylist
}
for (int l = 0; l < size; l++) {
int temp = l;//assigning value of l to a variable
for (int k = l + 1; k < size; k++) {
if (days.get(k) == temp) {// check statement to check values are same
matches++;//incrementing variable
out = true;
mOut.print("Count does have same birthday" + matches);
break;
} else {
mOut.print("does not have same birthday");
}
}
if (out) {
out = false;
break;
}
}
}
double prob = (double) matches / count;
mOut.print("The probability for two students to share a birthday is " + prob*100 + ".");
return prob;//returning double value of the function
}
Actually, you get either 0 percent or 100 percent with your code. Try invoking it with calculate(100, 100) if you want to see.
There are two things that are wrong in this code. First, if you run the simulation more than once (count > 1) then you never clear the list of birthdays before the second iteration.
Your method should begin with:
public double calculate(int size, int count) {
int matches = 0;
boolean out = false;
List<Integer> days;
for (int j = 0; j <count; j++) {
days = new ArrayList<Integer>();
Secondly, you're not comparing two birthdays but you're comparing a birthday to the index in the list.
This line:
int temp = l;//assigning value of l to a variable
Should read:
int temp = days.get(l); // Remember the birthday at index l
With those changes you'll get a much better result.
I'm a total beginner of java.
I have a homework to write a complete program that calculates the factorial of 50 using array.
I can't use any method like biginteger.
I can only use array because my professor wants us to understand the logic behind, I guess...
However, he didn't really teach us the detail of array, so I'm really confused here.
Basically, I'm trying to divide the big number and put it into array slot. So if the first array gets 235, I can divide it and extract the number and put it into one array slot. Then, put the remain next array slot. And repeat the process until I get the result (which is factorial of 50, and it's a huge number..)
I tried to understand what's the logic behind, but I really can't figure it out.. So far I have this on my mind.
import java.util.Scanner;
class Factorial
{
public static void main(String[] args)
{
int n;
Scanner kb = new Scanner(System.in);
System.out.println("Enter n");
n = kb.nextInt();
System.out.println(n +"! = " + fact(n));
}
public static int fact(int n)
{
int product = 1;
int[] a = new int[100];
a[0] = 1;
for (int j = 2; j < a.length; j++)
{
for(; n >= 1; n--)
{
product = product * n;
a[j-1] = n;
a[j] = a[j]/10;
a[j+1] = a[j]%10;
}
}
return product;
}
}
But it doesn't show me the factorial of 50.
it shows me 0 as the result, so apparently, it's not working.
I'm trying to use one method (fact()), but I'm not sure that's the right way to do.
My professor mentioned about using operator / and % to assign the number to the next slot of array repeatedly.
So I'm trying to use that for this homework.
Does anyone have an idea for this homework?
Please help me!
And sorry for the confusing instruction... I'm confused also, so please forgive me.
FYI: factorial of 50 is 30414093201713378043612608166064768844377641568960512000000000000
Try this.
static int[] fact(int n) {
int[] r = new int[100];
r[0] = 1;
for (int i = 1; i <= n; ++i) {
int carry = 0;
for (int j = 0; j < r.length; ++j) {
int x = r[j] * i + carry;
r[j] = x % 10;
carry = x / 10;
}
}
return r;
}
and
int[] result = fact(50);
int i = result.length - 1;
while (i > 0 && result[i] == 0)
--i;
while (i >= 0)
System.out.print(result[i--]);
System.out.println();
// -> 30414093201713378043612608166064768844377641568960512000000000000
Her's my result:
50 factorial - 30414093201713378043612608166064768844377641568960512000000000000
And here's the code. I hard coded an array of 100 digits. When printing, I skip the leading zeroes.
public class FactorialArray {
public static void main(String[] args) {
int n = 50;
System.out.print(n + " factorial - ");
int[] result = factorial(n);
boolean firstDigit = false;
for (int digit : result) {
if (digit > 0) {
firstDigit = true;
}
if (firstDigit) {
System.out.print(digit);
}
}
System.out.println();
}
private static int[] factorial(int n) {
int[] r = new int[100];
r[r.length - 1] = 1;
for (int i = 1; i <= n; i++) {
int carry = 0;
for (int j = r.length - 1; j >= 0; j--) {
int x = r[j] * i + carry;
r[j] = x % 10;
carry = x / 10;
}
}
return r;
}
}
How about:
public static BigInteger p(int numOfAllPerson) {
if (numOfAllPerson < 0) {
throw new IllegalArgumentException();
}
if (numOfAllPerson == 0) {
return BigInteger.ONE;
}
BigInteger retBigInt = BigInteger.ONE;
for (; numOfAllPerson > 0; numOfAllPerson--) {
retBigInt = retBigInt.multiply(BigInteger.valueOf(numOfAllPerson));
}
return retBigInt;
}
Please recall basic level of math how multiplication works?
2344
X 34
= (2344*4)*10^0 + (2344*3)*10^1 = ans
2344
X334
= (2344*4)*10^0 + (2344*3)*10^1 + (2344*3)*10^2= ans
So for m digits X n digits you need n list of string array.
Each time you multiply each digits with m. and store it.
After each step you will append 0,1,2,n-1 trailing zero(s) to that string.
Finally, sum all of n listed string. You know how to do that.
So up to this you know m*n
now it is very easy to compute 1*..........*49*50.
how about:
int[] arrayOfFifty = new int[50];
//populate the array with 1 to 50
for(int i = 1; i < 51; i++){
arrayOfFifty[i-1] = i;
}
//perform the factorial
long result = 1;
for(int i = 0; i < arrayOfFifty.length; i++){
result = arrayOfFifty[i] * result;
}
Did not test this. No idea how big the number is and if it would cause error due to the size of the number.
Updated. arrays use ".length" to measure the size.
I now updated result to long data type and it returns the following - which is obviously incorrect. This is a massive number and I'm not sure what your professor is trying to get at.
-3258495067890909184
I'm not sure if this is the best way to ask my question.
Basically, I have a 2D array that is being built from a text file.
It takes the first two int's for the dimensions. Then fills the array with the remaining data. That part is working fine.
In my array, I need to add each value with each adjacent value. To determine which value, when added with all of its adjacent values, is the highest. I need to do the reverse also, to find the lowest.
What kind of loop or function could I use to accomplish this? I'l create a small example below.
2 4 3 7 8
1 5 7 9 2
2 9 2 5 7
So the 2 would become a 7, the 4 would become a 14, and so on. After the math is done I need to detect which coordinate in the array is the largest number.
For simplicity, lets use the example you provided. The array is 5 by 3. Lets call the array data Try this
int totals[5][3];
for(int x = 0;x<5;x++){
for(int y = 0;y<5;y++){
int total = data[x][y]
if(x>0){
total+= data[x-1][y];
}
if(x<4){
total+= data[x+1][y];
}
if(y>0){
total+= data[x][y-1];
}
if(y<2){
total+= data[x][y+1];
}
totals[x][y] = total;
}
}
Then loop through the arrays and compare the values.
My approach would be the following:
public int largeNeighbor(int[][] numbers) {
int max = 0;
for (int i = 0; i < numbers.length ; i++) {
for (int j = 0; j < numbers[0].length; j++) {
int temp = numbers[i][j];
if (i > 0) {
temp += numbers[i-1][j];
}
if (i < numbers.length - 1) {
temp += numbers[i+1][j];
}
if (j > 0) {
temp += numbers[i][j-1];
}
if (j < numbers[0].length - 1) {
temp += numbers[i][j+1];
}
if (temp > max) {
max = temp;
}
}
}
return max;
}
When given a 2D integer array, the method will compare every value with added neighbors to the current max value.
You explained your situation well but in future questions you should include what you already have in small blocks of code. :)
I did this for fun. Hope someone enjoys.
import java.lang.ArrayIndexOutOfBoundsException;
import java.util.Random;
public class HelloWorld{
int smallest = 10000;
int largest = -1;
int xCoords_small = -1;
int yCoords_small = -1;
int xCoords_large = -1;
int yCoords_large = -1;
//Make it as big as you want!!!!!
int iSize = 5;
int jSize = 3;
int[][] totals = new int[iSize][jSize];
int[][] yourNumbers = new int[iSize][jSize];
Random r = new Random();
//Initializes the array. With random numbers. Yours would read in the
//the file here and initialize the array.
public HelloWorld(){
for(int i = 0; i < iSize; i++){
for(int j = 0; j < jSize; j++){
yourNumbers[i][j] = r.nextInt(10);
}
}
}
//Calculates the total and whether or not it's the largest number and
//tracks position in array and the total number.
//It has crumby error catching but this way you can make your array
//as big as you want without needing to change anything but the two
//two size variables.
public void calculate(){
for(int i = 0; i < iSize; i++){
for(int j = 0; j < jSize; j++){
int total = 0;
try{
total += yourNumbers[i][j];
}catch(ArrayIndexOutOfBoundsException ex ){
//do nothing
}
try{
total += yourNumbers[i-1][j];
}catch(ArrayIndexOutOfBoundsException ex){
//do nothing
}
try{
total += yourNumbers[i][j-1];
}catch(ArrayIndexOutOfBoundsException ex){
//do nothing
}
try{
total += yourNumbers[i+1][j];
}catch(ArrayIndexOutOfBoundsException ex){
//do nothing
}
try{
total += yourNumbers[i][j+1];
}catch(ArrayIndexOutOfBoundsException ex){
//do nothing
}
totals[i][j] = total;
if(total > largest){
largest = total;
xCoords_large = i;
yCoords_large = j;
}
if(total < smallest){
smallest = total;
xCoords_small = i;
yCoords_small = j;
}
System.out.println(total);
}
}
System.out.println(largest + " = Largest Total and it's beginning number in your 2D array. " + xCoords_large+ "," + yCoords_large+ " Its value = " + yourNumbers[xCoords_large][yCoords_large]);
System.out.println(smallest + " = Smallest Total and it's beginning number in your 2D array. " + xCoords_small + "," + yCoords_small + " Its value = " + yourNumbers[xCoords_small][yCoords_small]);
}
public static void main(String []args){
HelloWorld hw = new HelloWorld();
hw.calculate();
}
}
I am having some trouble with a simulated annealing algorithm to solve the n queens problem. Basically, I have it look for a better more, which works fine, but then I run a formula to check and see if it should take a "bad" move or not. From my understanding, the formula is e^(change in board state calculation)/CurrentTemperature. This number should be compared against a random double or float, if the random number is greater than the equation, the algorithm should take the "bad" move. The problem that I am getting is that the formula is always either REALLY close to 1 or over 1. Here some of my code (let me know if more should be provided):
temperature = n*100; //initializes starting temperature
currentTemp = n*100;
int cooldown = n*2; //initializes cool down temperature
float examine = 0; //this is the change in board calculation
int cost = 1;
boolean betterMove = false;
queen = new int[n];
int[][] board = graph; // generates a board of n size
float ran = 0; //random float to compare to
double compareAgainst = 0; //formula variable
cost = calculate(board, n); //calculates the cost
while (cost > 0 && currentTemp > 0)
{
// chooses a random queen to move that has a heuristic higher than zero
int Q = rand.nextInt(n);
while (queen[Q] == 0)
Q = rand.nextInt(n);
betterMove = false;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (board[i][j] == 1 && j == Q)
{
while (!betterMove)
{
int move = i;
while (move == i)
move = rand.nextInt(n); //pick a random move
tempBoard[i][j] = 0; //erase old position
tempBoard[move][j] = 1; //set new position
examine = calculate(tempBoard, n) - calculate(board, n); //calculates the difference between the change in boards
ran = rand.nextFloat(); //generates random number to compare against
compareAgainst = Math.pow(Math.E, (-examine / currentTemp)); //formula out of the book, basically is e^(change in board state divided by currentTemp)
if (calculate(tempBoard, n) < calculate(board, n)) //if this is a better move
{
for (int a = 0; a < n; a++)
for (int b = 0; b < n; b++)
board[a][b] = tempBoard[a][b]; //set it to the board
cost = calculate(board, n);
currentTemp -= cooldown; //cool down the temperature
betterMove = true;
}
else if(calculate(tempBoard,n) >= calculate(board,n)) //if this is a worse move
{
if(verbose == 1) //outputs whether or not this is a bad move and outputs function value and random float for simulated annealing purposes
{
System.out.println("This is a worse move");
System.out.println("The numbers for Simulated Annealing:");
System.out.println("Random number = " + ran);
System.out.println("Formula = " + compareAgainst);
System.out.println("Examine = " + examine);
}
if(ran > compareAgainst) //if the random float is greater than compare against, take the bad move
{
for (int a = 0; a < n; a++)
for (int b = 0; b < n; b++)
board[a][b] = tempBoard[a][b]; //take the move
cost = calculate(board, n);
currentTemp-= cooldown;
betterMove = true;
}
else //if not, do not take the move
{
for (int a = 0; a < n; a++)
for (int b = 0; b < n; b++)
tempBoard[a][b] = board[a][b];
}
currentTemp-= cooldown;
betterMove = true;
}
}
}
i = n;
j = n;
}
}
}
}
I have tried a number of things such as making the examine variable negative or taking the absolute value of the difference between board states. Also, the calculate function that is being called basically scans the board and returns back how many queens are in conflict, which is an int. Let me know if more clarification is needed. Thanks
Maybe the formula and examples in this image from OptaPlanner's docs help too: