For this lab a cool number is any number that when divided by 3,4,5 & 6 will leave a remainder of 1. I have done the static boolean IsCoolNumber and I made a private int b to use as a counter but I have absolutely no idea where I would put for example a b++. Any help would greatly be appreciated.
Thanks in advance!
import static java.lang.System.*;
public class CoolNumbers
{
private int b=0;
public static boolean isCoolNumber( int num )
{
int x;
x = 6;
for(x = 6; x<num; x++)
{
if ((x%3==1) && (x%4==1) && (x%5 ==1) && (x%6 == 1))
return true;
}
return false;
}
public static int countCoolNumbers( int stop )
{
//add counter
}
public static void main( String[] args )
{
System.out.println( CoolNumbers.countCoolNumbers(250) + " cool numbers between 6 - " + 250);
//add more test cases
}
}
In isCoolNumber you don't need a loop, a single statement will do.
public static boolean isCoolNumber(int x) {
return (x % 3 == 1) && (x % 4 == 1) && (x % 5 == 1) && (x % 6 == 1);
}
To count the "cool numbers" add a simple loop in the currently empty countCoolNumbers( int stop ) method.
for (int i = start; i < stop; i++) {
if (isCoolNumber(i)) {
count++;
}
}
Write your method countCoolNumbersas below and try it...
public static int countCoolNumbers( int stop ){
boolean check=isCoolNumber(stop);
int num=0;
if(check==true){
num=stop;
}
num=0;
return num;
`}
public static void main( String[] args ) {
System.out.println( CoolNumbers.countCoolNumbers(250) + " cool numbers between 6 - " + 250);
//add more test cases
}
Then output will be:
0 cool numbers between 6 - 250
Related
I have a problem relating to the percolation model with the latest version of Java
My project includes three file a illegalargumentexception.java file (use to handle illegal arguments), a percolation.java file (the datatype), and the PercolationStats.java file (use to calculate and generate the statistic)
In my expectation, the code should generate the probability of the percolated model (after a specific time of trials)
And here is my code:
the percolation datatype:
import edu.princeton.cs.algs4.WeightedQuickUnionUF;
public class percolation {
public static boolean[] grid;
public static WeightedQuickUnionUF gridMap ;
public static int openCell;
public static int top = 0;
private static int current_index;
public int bottom;
private int n;
public percolation(int n) {
}
// creates n-by-n grid, with all sites initially blocked
public int Percolation (int n) {
gridMap = new WeightedQuickUnionUF(n*n + 2);
grid = new boolean[n*n + 2];
this.n =n;
openCell = 0;
top = 0;
bottom = n*n +1;
if (n <=0) {
throw new IllegalArgumentException("Grid's number can not negative or equal to zero");
}
return n ;
}
// opens the site (row, col) if it is not open already
public void open( int row, int col) {
current_index = (row-1)*n + (col-1);
grid[percolation.current_index] = true;
percolation.openCell++;
if (row == 1)
gridMap.union(percolation.current_index, top);
if(row == this.n)
gridMap.union(current_index, col);
if (row > this.n || col > this.n)
throw new IllegalArgumentException("Out of bound");
if (row <1 || col <1)
throw new IllegalArgumentException("The index must be greater than zero");
if(row >1 && isOpen(row-1, col)) // above cell
{
assert(current_index > n);
gridMap.union(current_index,current_index-n);
}
if (row < this.n && isOpen(row + 1 , col)) // below cell
{
assert(current_index + n < n * n);
gridMap.union(current_index , current_index + n);
}
if(col > 1 && isOpen(row, col - 1)) //left cell
{
gridMap.union(current_index,current_index- 1);
}
if(col < this.n && isOpen(row, col + 1)) //right cell
{
gridMap.union(current_index,current_index + 1);
}
return ;
}
// is the site (row, col) open?
public boolean isOpen(int row, int col) {
return grid[current_index];
}
// is the site (row, col) full?
public boolean isFull(int row, int col)
{
if(!isOpen(row,col)) return false;
return gridMap.find(current_index) == gridMap.find(top);
}
public int numberOfOpenSites() // returns the number of open sites
{
return percolation.openCell;
}
// does the system percolate?
public boolean percolates() {
return gridMap.find(top) == gridMap.find(bottom);
}
// test client (optional)
public static void main(String[] args) {
}
}
the PercolationStats.java file
import edu.princeton.cs.algs4.StdRandom;
import edu.princeton.cs.algs4.StdStats;
public class PercolationStats {
public static double[] result;
public static int trials;
// perform independent trials on an n-by-n grid
public PercolationStats(int n, int trials) {
double[] result = new double[trials];
int test_row ;
int test_col ;
for (int i=0; i <trials; i++) {
percolation per = new percolation(n);
while (!per.percolates()) {
test_row = (int)((StdRandom.uniformInt(n)*n) +1 );
test_col = (int)((StdRandom.uniformInt(n)*n) +1 );
if( !per.isOpen(test_row,test_col) )
per.open(test_row,test_col);
}
result[i] = (double)(per.numberOfOpenSites()) / (n * n);
}
if(n <= 0 || trials <= 0) throw new IllegalArgumentException("Must greater than zero");
}
// sample mean of percolation threshold
public double mean() {
return StdStats.mean(result);
}
// sample standard deviation of percolation threshold
public double stddev() {
return StdStats.stddev(result) ;
}
// low endpoint of 95% confidence interval
public double Low_confidence() {
return (mean() - (1.96 * stddev())/ Math.sqrt(trials));
}
// high endpoint of 95% confidence interval
public double High_confidenceHi() {
return mean() + (1.96 * stddev())/ Math.sqrt(trials);
}
// test client (see below)
public static void main(String[] args) {
PercolationStats s = new PercolationStats(50,10000);
System.out.println("Mean:" + s.mean());
System.out.println("Standard Deviation:"+ s.stddev());
System.out.println("High Confidence" + s.High_confidenceHi());
System.out.println("Low Confidence" + s.Low_confidence());
}
}
My expectation is when I compile the PercolationStats file it will generate the result of the percolating probability threshold like this: (the result if you give the input 200 by 200 grid and try the simulation 100 times
~/Desktop/percolation> java-algs4 PercolationStats 200 100
mean = 0.5929934999999997
stddev = 0.00876990421552567
95% confidence interval = [0.5912745987737567, 0.5947124012262428]
but my result is a bunch of errors that:
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "edu.princeton.cs.algs4.WeightedQuickUnionUF.find(int)" because "percolation.gridMap" is null
at percolation.percolates(percolation.java:93)
at PercolationStats.<init>(PercolationStats.java:17)
at PercolationStats.main(PercolationStats.java:58)\
I believe this is to be caused by the percolate datatype, and to be more specific is the line:
public boolean percolates() {
return gridMap.find(top) == gridMap.find(bottom);
}
It states that the gridMap variable of Union-Find is null - I don't know why this happens, I speculate this can relate to the scope of the "gridMap" variable, which is not applicable to all methods in the datatype. That is my hypothesis It could be wrong.
Can anyone give me a clue for why this happens and what should I fix for the successful compilation (I means to generate the probability)
Thanks in advance!
You have not set gridMap, though it is mentioned in a method called public int Percolation (int n). Perhaps you intended that Percolation is called from body of the constructor which you declared as public percolation(int n).
The fix should be simple: move the public int Percolation (int n) code into the constructor or make constructor public percolation(int n) call Percolation(n).
The class should follow conventions and renamed to Percolation.
I have a problem, I have the correct(PART 1) and incorrect code (PART 2). I cant figure out why the incorrect code is incorrect.
the
static int sum = 0
part is the incorrect part of the code in PART 2. If that line of code is moved to the same location at PART 1. The code works.
if the range is from 10 to 20. PART 2 outputs an incorrect sum of 111. The sum should be 75. There are 3 possible combinations to get 111.
18 + 18 + correct sum
17 +19 + correct sum
16 + 20 + correct sum
Im guessing PART 2 passes through 18 + 18? but how?!
PART 1 Correct Code
ublic class SumOddRange {
public static boolean isOdd(int number){
if (number <= 0) {
return false;
}
return number % 2 != 0;
}
public static int sumOdd(int start, int end){
if ( (end < start) || (start < 0) || (end < 0) ){
return -1;
}
int sum = 0;
for (int i = start; i<=end; i++){
if (isOdd(i)){
sum +=i;
}
}
return sum;
}
PART 2 INCORRECT CODE
public class SumOddRange {
public static boolean isOdd(int number) {
if((number > 0) && (number % 2 != 0)) {
return true;
}
else {
return false;
}
}
static int startOne = 0;
static int sum = 0;
public static int sumOdd(int start, int end) {
if ((end >= start) && (end > 0) && (start > 0)) {
for (startOne = start; startOne <= end; startOne++) {
if (isOdd(startOne)) {
sum += startOne;
}
}
return sum;
} else
return -1;
}
The problem is that you are using static variables.
What does static mean?
After creating a class, you can create instances (also called objects) of this class. This is what happens, when you use a command like
SumOddRange a = new SumOddRange();
SumOddRange b = new SumOddRange();
As you probably know, there are methods and variables in a class. These methods and classes can be seperated into
Class methods and variables
Object methods and variables (object variables are most often called attributes)
This means that some methods and variables do belong to the class, so all the instances of this class share this variable or method. This is what static is used for. So if the class in the image above has a static attribute named staticAttributeName, a.staticAttributeName and b.staticAttributeName have to be the same.
If a variable isn't static, this variable is not shared by the instances. All instances have their own instance of this variable. So although their name is the same, the values saved in the variables doen't have to be the same. So if the class in the image above has a non-static attribute named attributeName, a.attributeName and b.attributeName doesn't have to be the same.
An example:
public class Add {
public static int sum = 0;
public static void addOne() {
sum = sum + 1;
}
}
public class Test {
public static void main(String[] args) {
Add a = new Add();
Add b = new Add();
a.addOne();
b.addOne();
System.out.println("a " + a.sum);
System.out.println("b " + b.sum);
}
}
As you can see, the variable sum is static. This means that a.sum and b.sum are the same. In the main-method, we are calling the method addOne two times, so the two outputs are "a 2" and "b 2".
public class Add {
public int sum = 0;
public void addOne() {
sum = sum + 1;
}
}
public class Test {
public static void main(String[] args) {
Add a = new Add();
Add b = new Add();
a.addOne();
b.addOne();
b.addOne();
System.out.println("a " + a.sum);
System.out.println("b " + b.sum);
}
}
We now have a non-static variable sum in the class Add.
a: We are calling the method addOne one time, so the first output is "a 1".
b: The method addOne is called two times, so the output is "b 2".
Solving the problem
public class Test {
public static void main(String[] args) {
SumOddRange s = new SumOddRange(); //Using class given in PART2 of question
SumOddRange t = new SumOddRange();
System.out.println(s.sumOdd(10,20));
System.out.println(s.sumOdd(10,20));
}
}
This class produces the outputs 75 and 150. This is the case, because s and t use the same variable sum, so the first time, the sum is correct, but the second calculation returns 75+sumOdd(10,20) = 75+75 = 150 as the result.
As we now know, the main problem is that the variable(s) are static. This brings up the idea to just use non-static variables, which is the best idea here:
public class SumOddRange {
public boolean isOdd(int number) {
if((number > 0) && (number % 2 != 0)) {
return true;
}
else {
return false;
}
}
int startOne = 0;
int sum = 0;
public int sumOdd(int start, int end) {
sum = 0;
if ((end >= start) && (end > 0) && (start > 0)) {
for (startOne = start; startOne <= end; startOne++) {
if (isOdd(startOne)) {
sum += startOne;
}
}
return sum;
} else {
return -1;
}
}
}
Another option is to just reset the variable sum before actually calculating the sum. The disadvantage of this approach is that you will not be able to access earlier results anymore:
static int startOne = 0;
static int sum = 0;
public static int sumOdd(int start, int end) {
sum = 0;
if ((end >= start) && (end > 0) && (start > 0)) {
for (startOne = start; startOne <= end; startOne++) {
if (isOdd(startOne)) {
sum += startOne;
}
}
return sum;
} else {
return -1;
}
}
if (numberContentUnits % 4 == 0 == quantity >= 4){
getAddToCartMethod(code, quantity);
}
here i want check dynamically numberContentUnits and quantity.i don't want take 4 like static vlaue could please anyone help me...
I cannot understand the question exactly, but want to help you. Here is a simple of possible examples from your question:
Case 1.
public class NewClass2 {
public static void main(String[] args) {
int quantity = 10;
int code = 5;
int four = 4;
for (int numberContentUnits = 0; numberContentUnits < 50; numberContentUnits++) {
if (numberContentUnits % four == 0 == quantity >= 4) {
int res = getAddToCartMethod(code, quantity);
System.out.println("Res: " + res);
}
}
}
private static int getAddToCartMethod(int code, int quantity) {
return code + quantity;
}
}
As you can see you can your "4" *variable four) is not static.
Case 2.
public class NewClass2 {
static int four = 4;
public static void main(String[] args) {
int quantity = 10;
int code = 5;
for (int numberContentUnits = 0; numberContentUnits < 50; numberContentUnits++) {
if (numberContentUnits % four == 0 == quantity >= 4) {
int res = getAddToCartMethod(code, quantity);
System.out.println("Res: " + res);
}
}
}
private static int getAddToCartMethod(int code, int quantity) {
return code + quantity;
}
}
Here it is already static.
What is your question?
I am not exactly sure about the expected outcome of this code.
int val = 4; //you have an option of taking this value as method parameter
if ( (numberContentUnits % val == 0) && (quantity >= val) ){
getAddToCartMethod(code, quantity);
}
input:
123
output:
6 >>> (It is the sum of all digits)
I want the output will:
321
That means each digit separately
What is wrong in the code?
The code:
public class t4 {
public static void main(String[] args) {
System.out.println(ReverseNum(123));
}
public static int ReverseNum(int num) {
int dig = 0;
if (num == 0)
return dig;
dig = dig * 10 + num % 10;
return ReverseNum(num / 10) + dig;
}
}
thank's
Try this.
public static void reverseMethod(int number) {
if (number < 10) {
System.out.println(number);
return;
}
else {
System.out.print(number % 10);
reverseMethod(number/10);
}
}
You can try:
public class t4 {
public static void main(String[] args) {
System.out.println(ReverseNum(123));
}
public static String ReverseNum(int num) {
if (num == 0)
return "";
return "" + num % 10 + ReverseNum(num / 10);
}
}
Find the largest power of ten smaller than the number first and use it to for reversing the number. This allows you to "move the digits to the right places":
public static int findPow10(int num) {
if (num < 10) {
return 1;
} else {
return 10 * findPow10(num / 10);
}
}
private static int reverseHelper(int num, int factor) {
if (num == 0) {
return 0;
} else {
return factor * (num % 10) + reverseHelper(num / 10, factor / 10);
}
}
public static int reverse(int num) {
return reverseHelper(num, findPow10(num));
}
public static void main(String[] args) {
System.out.println(reverse(123));
}
Rather than printing the values, I'm trying to return the number. This is what I could come up with so far. I think someone else might be able to do a better job. It's not that elegant with the while loop inside.
public static int ReverseNum(int num) {
if (num < 10){
return num;
}
int val = 1; int n = num;
while(n > 10){
n = n/10;
val = val * 10;
}
return (num % 10)*val + ReverseNum((num - num % 10)/10);
}
class Solution
{
//A method for reverse
public static void reverseMethod(int number)
{
if (number < 10)
{
System.out.println(number);
}
else {
System.out.print(number % 10); // 123 % 10 = 3
//Method is calling itself: recursion
reverseMethod(number/10); //123/10 = 12 integer ignore decimal number
}
}
public static void main(String args[])
{
reverseMethod(123);
}
}
import java.lang.Math;
import java.text.*;
public class Problem4 {
public static int reverse( int n ) {
int i = 0;
while ( n != 0 ) {
int r = n % 10;
i = (i * 10) + r;
n /= 10;
}
return i;
}
public static boolean isPalindrome( int n ) {
return ( n == reverse(n) ) ? true : false;
}
public static void main( String[] args ) {
int jHi=0, jlow=0, dec=0;
int P=1;
int i=999, j=1;
for ( i=999; i <= 100; i = i - 1 )
{
if ( i % 11 == 0 )
{
jHi = 999;
jlow = 100;
dec = 1;
}
else
{
jHi = 990;
jlow = 100;
dec = 11;
}
for ( j = jHi; j >= jlow; j = j - dec )
{
P = i * j;
if ( isPalindrome(P) )
{
break;
}
else
{
continue;
}
}
}
System.out.println( "Largest Palindrome is " + P );
}
}
Your for loop does not execute because the loop condition i<=100 is never met with an initial value of i=999.
Since you want your loop to count downwards, change
for(i=999; i<=100; i=i-1)
to
for(i=999; i>=100; i=i-1)
i=999; i<=100; i=i-1 --change it as i=999; i>=100; i=i-1
This means "start with i as 999 and do it while i is less or equal than 100 decreasing i by one in each step":
for(i=999; i<=100; i=i-1)
Your for loop will not execute for very first time and hence no operation. Always use proper condition.