Trying to create a method that will make an array and assign different numbers from 1 - 9 to each index of the array (nos. cannot be repeated).
please have a look at the boolean comparison i made, this is where the cmd stuck at runtime. I have tried to separate the two but nothing happens.
Please help.
import java.util.ArrayList;
class Testing {
public static void main (String[] args) {
ArrayList<Integer> grid = new ArrayList<Integer>();
int randNum;
int count = 0;
int size=8;
for (int b = 0; b <=size; b++) {
while (count <= size) {
randNum = (int) (Math.random() * 9);
if (grid.contains(randNum) == false & randNum != 0 ) {
grid.add(randNum);
count++;
}
}
System.out.println(grid.get(b));
}
System.out.println("size: " + grid.size());
}
}
Why not use a Fisher-Yates shuffle instead?
That is, fill the array with 1-9 and then Collections.shuffle() it.
Aside: use && not & in your original code.
I agree with Matt Ball, create an array 1-9 and shuffle, but to answer your question, the problem is here:
randNum = (int) (Math.random() * 9);
if (grid.contains(randNum) == false & randNum != 0 ) {
Should be this:
randNum = (int) (Math.random() * 9) + 1;
if (grid.contains(randNum) == false) {
since you multiply Math.random() * 9 you will only get numbers between 0-8, adding 1 will give you 1-9.
You are doing it wrong or unknowingly actually at several places:
& and && are two different things. Use && when you want to continue to check for second condition iff first operand or condition evaluates to true otherwise to evaluate both operands use &.
Why multiplying by 9. Multiply it by 10. As multiply by 9 constrained to 1-8 numbers only.
Why are you printing the grid within a loop and having a special loop for same?. Just print the grid it will show you all the elements.
Below is your corrected program:
import java.util.ArrayList;
public class HelloWorld{
public static void main(String []args){
ArrayList<Integer> grid = new ArrayList<Integer>();
int randNum;
int count = 0;
int size=8;
while (count <= size) {
randNum = (int) (Math.random() * 10);
System.out.println(randNum+"test"+grid);
if (!grid.contains(randNum) && randNum != 0 ) {
System.out.println("grid coming in here"+grid);
grid.add(randNum);
count++;
}
}
System.out.println(grid);
System.out.println("size: " + grid.size());
}
}
Hope it helps!
Related
I am trying to add two binary numbers and then get their sum in binary system. I got their sum in decimal and now I am trying to turn it into binary. But there is problem that when I take their sum (in decimal) and divide by 2 and find remainders(in while loop), I need to put remainders into array in order print its reverse. However, there is an error in array part. Do you have any suggestions with my code? Thanks in advance.
Here is my code:
import java.util.Scanner;
public class ex1 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int m = scan.nextInt();
int k = dec1(n)+dec2(m);
int i=0,c;
int[] arr= {};
while(k>0) {
c = k % 2;
k = k / 2;
arr[i++]=c; //The problem is here. It shows some //error
}
while (i >= 0) {
System.out.print(arr[i--]);
}
}
public static int dec1(int n) {
int a,i=0;
int dec1 = 0;
while(n>0) {
a=n%10;
n=n/10;
dec1= dec1 + (int) (a * Math.pow(2, i));
i++;
}
return dec1;
}
public static int dec2(int m) {
int b,j=0;
int dec2 = 0;
while(m>0) {
b=m%10;
m=m/10;
dec2= dec2 + (int) (b * Math.pow(2, j));
j++;
}
return dec2;
}
}
Here:
int[] arr= {};
creates an empty array. Arrays don't grow dynamically in Java. So any attempt to access any index of arr will result in an ArrayIndexOutOfBounds exception. Because empty arrays have no "index in bounds" at all.
So:
first ask the user for the count of numbers he wants to enter
then go like: int[] arr = new int[targetCountProvidedByUser];
The "more" real answer would be to use List<Integer> numbersFromUsers = new ArrayList<>(); as such Collection classes allow for dynamic adding/removing of elements. But for a Java newbie, you better learn how to deal with arrays first.
Why are you using two different methods to do the same conversion? All you need is one.
You could have done this in the main method.
int k = dec1(n)+dec1(m);
Instead of using Math.pow which returns a double and needs to be cast, another alternative is the following:
int dec = 0;
int mult = 1;
int bin = 10110110; // 128 + 48 + 6 = 182.
while (bin > 0) {
// get the right most bit
int bit = (bin % 10);
// validate
if (bit < 0 || bit > 1) {
throw new IllegalArgumentException("Not a binary number");
}
// Sum up each product, multiplied by a running power of 2.
// this is required since bits are taken from the right.
dec = dec + mult * bit;
bin /= 10;
mult *= 2; // next power of 2
}
System.out.println(dec); // prints 182
An alternative to that is to use a String to represent the binary number and take the bits from the left (high order position).
String bin1 = "10110110";
int dec1 = 0;
// Iterate over the characters, left to right (high to low)
for (char b : bin1.toCharArray()) {
// convert to a integer by subtracting off character '0'.
int bit = b - '0';
// validate
if (bit < 0 || bit > 1) {
throw new IllegalArgumentException("Not a binary number");
}
// going left to right, first multiply by 2 and then add the bit
// Each time thru, the sum will be multiplied by 2 which shifts everything left
// one bit.
dec1 = dec1 * 2 + bit;
}
System.out.println(dec1); // prints 182
One possible way to display the result in binary is to use a StringBuilder and simply insert the converted bits to characters.
public static String toBin(int dec) {
StringBuilder sb = new StringBuilder();
while (dec > 0) {
// by inserting at 0, the bits end up in
// correct order. Adding '0' to the low order
// bit of dec converts to a character.
sb.insert(0, (char) ((dec & 1) + '0'));
// shift right for next bit to convert.
dec >>= 1;
}
return sb.toString();
}
I am trying to make a program that solves Project Euler's First Problem. However I am having trouble returning my sum.
To approach this problem, I am trying to first add up all of the multiples of three and assigning that value of the added multiples to the integer sum. Then I am trying to do the same with the multiples of five accordingly.
Finally I am trying to add the two sums together, the sum of the three multiples and the sum of the five multiples, and them printing out the coalesced value of the two sums via the last sum.
This is the Java code I am trying to use to achieve this.
public class Main {
public static void main(String[] args) {
int sum = 0;
int t = 3;
while (sum < 1000) {
if (sum % 3 == 0)
sum += t;
}
int sum2 = 0;
int f = 5;
while (sum2 < 1000) {
if (sum % 5 == 0)
sum += f;
}
int sum3 = sum + sum2;
System.out.println(sum3);
}
}
I did get one error saying sum2 < 1000 is always true. However, I do not understand how to fix this problem.
Any help is utterly appreciated.
check the comments, hope it helped.
public static void main(String []args){
int sum = 0; //store all the numbers
int t = 3; // the starting point (it can be 3 if you want)
while (t < 1000) { // as long t is lower than 1000
if ( t % 3 == 0 || t % 5 == 0) { //check if t is divided by 3 or 5
sum += t; //add to sum
}
t++; //add 1 to t (t will increase and eventualy be bigger than 1000)
}
System.out.println(sum); //print sum
}
I'm writing a code for an assignment for school but it requires me to compare two int values. For example, if you have the number 123 and the other number is 321, they have the same digits but are in different orders. Is there easy way of comparing them or do i have to make them into a string and compare them as string types? if its the latter, how could i compare two strings? Is there any way of doing this without an array?
By comparing int values, if you mean greater than, less than or equal you can do that like so.
int a = 123, b= 321;
if(a > b)
//a is greater than b (b is less than a)
if(a == b)
// a is equal to b
if(a < b)
// a is less than b (b is greater)
Could use some clarification, if you want to check if the number is reversed like you said in an example its called a palindrome.
You could reverse a number in the following if you had experience with loops and modulo(the %) in the following snippet.
int r = 0;
while(number != 0){
r = r * 10 + number % 10;
number /= 10; }
return r;
r would be that number reversed. If you input let's say 123 you would get 321 back, then you could compare it to the other to see if its just the reverse.
Let me know if you have any more questions and I'll try to answer!
To check if a number is arbitrarily mixed and not reversed to winning number, you could try the following.
Two numbers a and b, a is the winning number and b is the number the user chose.
a is 251 and b is 521.
You could do this on each number to separate them.
int p1,p2,p3;
p1 = num % 10;
p2 = num / 10 % 10;
p3 = num / 100 % 10;
This would separate ex. 251 into 2, 5, and then 1. Then you could add them as so doing the same process for the second. sum is p1 + p2 + p3 and sum2 is p4 + p5 + p6 for the second number. Provided the numbers are not reversed. Use the thing I mentioned before for that case to check if they are flipped.
if(sum == sum2)
//Numbers are mixed but you won!
This should work.
Certainly not the fastest solution, but the code is short and easy to understand.
public boolean arePalindromes(int a, int b){
//convert them to char arrays for easy sorting
char[] aryA = String.valueOf(a).toCharArray();
char[] aryB = String.valueOf(b).toCharArray();
//sort them
Collections.sort(aryA);
Collections.sort(aryB);
//put them back to strings for easy comparison
String strA = new String(aryA);
String strB = new String(aryB);
//compare
return strA.equals(strB);
}
Please try the following code (I have tested it), of which idea is borrowed from here and here. This solution still uses array.
public class CompareInt {
public static void main(String[] args) {
System.out.println(containSameDigits(123, 123));
System.out.println(containSameDigits(123, 321));
System.out.println(containSameDigits(123, 132));
System.out.println(containSameDigits(123, 323));
System.out.println(containSameDigits(123, 124));
System.out.println(containSameDigits(123, 111));
}
public static boolean containSameDigits(int x, int y) {
String xSorted = getSortedString(x);
String ySorted = getSortedString(y);
return xSorted.equalsIgnoreCase(ySorted);
}
public static String getSortedString(int x) {
String xSorted = "";
for (int digit = 0; digit < 9; digit++) {
for (int temp = x; temp > 0; temp /= 10) {
if (temp % 10 == digit) {
xSorted += digit;
}
}
}
return xSorted;
}
}
Output:
true
true
true
false
false
false
it's my first post so DO stomp me if I wrote something stupid.
I've just started IT classes, and today on "while" loops class my tutor gave us the following homework:
Write a program which reads a natural number n and displays in one graphical box all its divisors from the interval [2; n-1].
So far I came up with a code that works but the result is a bit wrong:
import java.util.Arrays;
import javax.swing.JOptionPane;
public class Divisors {
public static void main(String[] args) {
String n = JOptionPane.showInputDialog(null, "Enter a natural number");
Integer i = Integer.parseInt(n);
int d = i - 1;
int x = 2;
int[] dvr = new int[i]; // [i] because bigger numbers need more iterations
while (x >= 2 && x <= d) {
double y = i % x;
if (y == 0) {
dvr[x] = x;
x = x + 1;
} else {
x = x + 1;
}
}
JOptionPane.showMessageDialog(null, "The divisors of " + i + " are:\n" + Arrays.toString(dvr));
}
}
The problem is that the loop fills the array with a lot of zeroes, and the screenshot of tutor's results shows a window listing only the divisors.
I tried to do this with ArrayList, but that's black magic for me right now and my tutor didn't teach us yet how to use anything beyond stuff used in my code anyway.
Any help highly appreciated.
The main problem you're having is that you're going to have an unknown number of values you want to print, but you're using an array to store them, and arrays have a fixed size. Since you have an array of int, it's going to be entirely populated with the default value of zero.
Ideally, you'd only print the first bunch of non-zero values of your array, but you're storing the divisors scattered throughout your array.
dvr[x] = x; stores each value at an index of that value, when really you should just store each new value into the next open spot in the array.
Create a separate index variable, and store each value using it instead:
int index = 0;
while (x >= 2 && x <= d) {
...
if (y == 0) {
dvr[index++] = x;
...
Then when your main loop is done, you can create a new "display array" that holds only the divisors, and not the zeros. At this point, index tells you exactly how large it needs to be:
int[] display = Arrays.copyOf(dvr, index);
JOptionPane.showMessageDialog(null, "The divisors of " + i + " are:\n" + Arrays.toString(display));
In Java the default value of an int is zero. So that is why you see a lot of zeros.
Since you define the size of the array to be i which is more than what is required as the no of divisors would always be less than i.
So instead of printing the entire array you should only print it up to the total no of divisors for which you should a separate variable instead of using x.
Here is the modified version where I am using a separate index variable to keep track of number of divisors which start from 0. In the end you can just print the array up to the index
import java.util.Arrays;
import javax.swing.JOptionPane;
public class Divisors {
public static void main(String[] args) {
String n = JOptionPane.showInputDialog(null, "Enter a natural number");
Integer i = Integer.parseInt(n);
int d = i - 1;
int index = 0;
int x=2;
int[] dvr = new int[i]; // [i] because bigger numbers need more iterations
while (x >= 2 && x <= d) {
double y = i % x;
if (y == 0) {
dvr[index] = x;
x = x + 1;
index= index + 1;
} else {
x = x + 1;
}
}
JOptionPane.showMessageDialog(null, "The divisors of " + i + " are:\n" + Arrays.copyOfRange(drv, 0, index));
}
}
Set datastructure avoids duplicates, you can use that to overcome the problem of duplicate divisors getting added into the data structure.
import java.util.*;
import javax.swing.JOptionPane;
public class Divisors {
public static void main(String[] args) {
String n = JOptionPane.showInputDialog(null, "Enter a natural number");
Integer i = Integer.parseInt(n);
int d = i - 1;
int x = 2;
Set<Integer> divisors = new HashSet<>();
while (x >= 2 && x <= d) {
double y = i % x;
if (y == 0) {
divisors.add(x);
x = x + 1;
} else {
x = x + 1;
}
}
List<Integer> l = new ArrayList<>(divisors);
JOptionPane.showMessageDialog(null, "The divisors of " + i + " are:\n" + l);
}
}
Use ArrayList to create Dynamic Array.
Below Code will help you.
Things to change In your Program.
import java.util.*;
take an ArrayList varible
call toString method on Arraylist Object
import java.util.*;
import javax.swing.JOptionPane;
public class NewClass3 {
public static void main(String[] args) {
String n = JOptionPane.showInputDialog(null, "Enter a natural number");
Integer i = Integer.parseInt(n);
int d = i - 1;
int x = 2;
List<Integer> dvr = new ArrayList<>();
while (x >= 2 && x <= d) {
double y = i % x;
if (y == 0) {
dvr.add(x);
x=x+1;
} else {
x = x + 1;
}
}
JOptionPane.showMessageDialog(null, "The divisors of " + i + " are:\n" + dvr.toString());
}
}
This is the question I've been assigned:
A so-called “star number”, s, is a number defined by the formula:
s = 6n(n-1) + 1
where n is the index of the star number.
Thus the first six (i.e. for n = 1, 2, 3, 4, 5 and 6) star numbers are: 1, 13, 37,
73, 121, 181
In contrast a so-called “triangle number”, t, is the sum of the numbers from 1 to n: t = 1 + 2 + … + (n-1) + n.
Thus the first six (i.e. for n = 1, 2, 3, 4, 5 and 6) triangle numbers are: 1, 3, 6, 10, 15, 21
Write a Java application that produces a list of all the values of type int that are both star number and triangle numbers.
When solving this problem you MUST write and use at least one function (such as isTriangeNumber() or isStarNumber()
or determineTriangeNumber() or determineStarNumber()). Also you MUST only use the formulas provided here to solve the problem.
tl;dr: Need to output values that are both Star Numbers and Triangle Numbers.
Unfortunately, I can only get the result to output the value '1' in an endless loop, even though I am incrementing by 1 in the while loop.
public class TriangularStars {
public static void main(String[] args) {
int n=1;
int starNumber = starNumber(n);
int triangleNumber = triangleNumber(n);
while ((starNumber<Integer.MAX_VALUE)&&(n<=Integer.MAX_VALUE))
{
if ((starNumber==triangleNumber)&& (starNumber<Integer.MAX_VALUE))
{
System.out.println(starNumber);
}
n++;
}
}
public static int starNumber( int n)
{
int starNumber;
starNumber= (((6*n)*(n-1))+1);
return starNumber;
}
public static int triangleNumber( int n)
{
int triangleNumber;
triangleNumber =+ n;
return triangleNumber;
}
}
Here's a skeleton. Finish the rest yourself:
Questions to ask yourself:
How do I make a Triangle number?
How do I know if something is a Star number?
Why do I only need to proceed until triangle is negative? How can triangle ever be negative?
Good luck!
public class TriangularStars {
private static final double ERROR = 1e-7;
public static void main(String args[]) {
int triangle = 0;
for (int i = 0; triangle >= 0; i++) {
triangle = determineTriangleNumber(i, triangle);
if (isStarNumber(triangle)) {
System.out.println(triangle);
}
}
}
public static boolean isStarNumber(int possibleStar) {
double test = (possibleStar - 1) / 6.;
int reduce = (int) (test + ERROR);
if (Math.abs(test - reduce) > ERROR)
return false;
int sqrt = (int) (Math.sqrt(reduce) + ERROR);
return reduce == sqrt * (sqrt + 1);
}
public static int determineTriangleNumber(int i, int previous) {
return previous + i;
}
}
Output:
1
253
49141
9533161
1849384153
You need to add new calls to starNumber() and triangleNumber() inside the loop. You get the initial values but never re-call them with the updated n values.
As a first cut, I would put those calls immediatly following the n++, so
n++;
starNumber = starNumber(n);
triangleNumber = triangleNumber(n);
}
}
The question here is that "N" neednt be the same for both star and triangle numbers. So you can increase "n" when computing both star and triangle numbers, rather keep on increasing the triangle number as long as its less the current star number. Essentially you need to maintain two variable "n" and "m".
The first problem is that you only call the starNumber() method once, outside the loop. (And the same with triangleNumber().)
A secondary problem is that unless Integer.MAX_VALUE is a star number, your loop will run forever. The reason being that Java numerical operations overflow silently, so if your next star number would be bigger than Integer.MAX_VALUE, the result would just wrap around. You need to use longs to detect if a number is bigger than Integer.MAX_VALUE.
The third problem is that even if you put all the calls into the loop, it would only display star number/triangle number pairs that share the same n value. You need to have two indices in parallel, one for star number and another for triangle numbers and increment one or the other depending on which function returns the smaller number. So something along these lines:
while( starNumber and triangleNumber are both less than or equal to Integer.MAX_VALUE) {
while( starNumber < triangleNumber ) {
generate next starnumber;
}
while( triangleNumber < starNumber ) {
generate next triangle number;
}
if( starNumber == triangleNumber ) {
we've found a matching pair
}
}
And the fourth problem is that your triangleNumber() method is wrong, I wonder how it even compiles.
I think your methodology is flawed. You won't be able to directly make a method of isStarNumber(n) without, inside that method, testing every possible star number. I would take a slightly different approach: pre-computation.
first, find all the triangle numbers:
List<Integer> tris = new ArrayList<Integer>();
for(int i = 2, t = 1; t > 0; i++) { // loop ends after integer overflow
tris.add(t);
t += i; // compute the next triangle value
}
we can do the same for star numbers:
consider the following -
star(n) = 6*n*(n-1) + 1 = 6n^2 - 6n + 1
therefore, by extension
star(n + 1) = 6*(n+1)*n + 1 = 6n^2 + 6n +1
and, star(n + 1) - star(n - 1), with some algebra, is 12n
star(n+1) = star(n) + 12* n
This leads us to the following formula
List<Integer> stars = new ArrayList<Integer>();
for(int i = 1, s = 1; s > 0; i++) {
stars.add(s);
s += (12 * i);
}
The real question is... do we really need to search every number? The answer is no! We only need to search numbers that are actually one or the other. So we could easily use the numbers in the stars (18k of them) and find the ones of those that are also tris!
for(Integer star : stars) {
if(tris.contains(star))
System.out.println("Awesome! " + star + " is both star and tri!");
}
I hope this makes sense to you. For your own sake, don't blindly move these snippets into your code. Instead, learn why it does what it does, ask questions where you're not sure. (Hopefully this isn't due in two hours!)
And good luck with this assignment.
Here's something awesome that will return the first 4 but not the last one. I don't know why the last won't come out. Have fun with this :
class StarAndTri2 {
public static void main(String...args) {
final double q2 = Math.sqrt(2);
out(1);
int a = 1;
for(int i = 1; a > 0; i++) {
a += (12 * i);
if(x((int)(Math.sqrt(a)*q2))==a)out(a);
}
}
static int x(int q) { return (q*(q+1))/2; }
static void out(int i) {System.out.println("found: " + i);}
}