Hello i am having a tough time trying to write a function that can create an array that holds integers, that equal my simple math problem.
my problem is not adding integers into the array but finding the correct integers that could add up to a math problem.
for example i have a simple math problem like: 10 + 10 = ? we know it equals 20
so i want my array to hold up to ten integers, that when added all together equal 20.
this is what i have been trying in code but not getting the results i want.
while (totalCount != answer
&& count < setCount) {
randomNumber = rand.nextInt((int) answer / 2) + 1;
if(count < setCount) {
sumOfBalloons.add(randomNumber);
totalCount += randomNumber;
count++;
}
if(totalCount > answer) {
count = 0;
totalCount = 0;
sumOfBalloons.clear();
}
}
i am trying to find random numbers that add up to the math problems answer so i can draw them on balloons. problem is i can never get ten numbers to equal the answer in my while loop.
does anyone know some way of doing something like this?
need array to hold 3 - 10 integers that equals my math problems answer.
** update on code thanks to the advice i received i managed to fix my while loop now it looks like this
had to post like this cause my rep is very low. sorry.
while (totalCount != answer) {
randomNumber = rand.nextInt((int) answer / 2) + 1;
if(totalCount + randomNumber > answer) {
randomNumber = rand.nextInt((int) answer - totalCount) + 1;
}
if(count + 1 == setCount) {
randomNumber = answer - totalCount;
}
if(count < setCount) {
sumOfBalloons.add(randomNumber);
totalCount += randomNumber;
count++;
}
if(totalCount > answer
|| totalCount == answer
&& count < setCount
|| totalCount != answer
&& count == setCount) {
count = 0;
totalCount = 0;
sumOfBalloons.clear();
}
}
this is what i got in my console from this code
Total count = 10
Total totalCount = 20
sumOfBalloons 0 = 2
sumOfBalloons 1 = 3
sumOfBalloons 2 = 3
sumOfBalloons 3 = 2
sumOfBalloons 4 = 1
sumOfBalloons 5 = 4
sumOfBalloons 6 = 2
sumOfBalloons 7 = 1
sumOfBalloons 8 = 1
sumOfBalloons 9 = 1
I think there are a few options here re: generating random numbers that sum to 20.
Here's one possible solution:
Create an array of length 4, for example.
Generate random number between 1 and 6 for each of the first 3 indices of your array.
At this point you'll have an array of the form: { 4, 5, 2, _ } (where our 4th element hasn't been chosen yet).
Sum our first 3 elements: 4 + 5 + 2 = 11. Determine 4th element by calculating 20 - current_total (11) = 9.
Set myArray[3] = 9;
A few things to note:
You may need to modify the range of possible random numbers ( 1-6 ) I've given. Consider what happens if the array we generate turns out to be { 2, 1, 2, _ }...then there's no digit that will ensure the elements sum to 20.
Another option is to use an arrayList instead of an array. The benefit to this is that you can keep adding elements to your arrayList until you either hit 20 (then you're done) or go over (in which case you delete the most recent element and begin adding again). You also won't need (or be able) to know the length of your arrayList in advance.
Related
Not sure if anyone can explain this to me or help me.
I have a 15 Digit Number of which I want to multiply each even number by 2 unless the even number is greater than 9. If it is this needs to be subtracted by 9 to give me an integer that again I can multiply by 2. Once I have all the even numbers multiplied by 2 i need to add them all together with the odd numbers.
Does that make sense.
UPDATE ***
so i have a number say 49209999856459. for that number I am looking to get the even integer so for example the first even one would be 4 then the second would be 2 and so on.
If one of those even numbers are multiplied by 2 then it might be above 9 so I want to subtract 9 to then use the remainder as the even number in its place.
SO !!!
Multiply by 2 the value of each even digit starting from index 0 and then each even index. In each case, if the resulting value is greater than 9, subtract 9 from it (which reduces larger values to a single digit). Leave the values of the digits at the odd indexes unchanged.
public String calculateCheckNumber()
String firstFifteen = longNumber.substring(0,15) ;
int i, checkSum = 0, totalSum = 0;
for (i = 0; i<firstFifteen.length(); i += 2) {
while (i < 9)
i *= 2;
if (i > 9)
i -= 9 ;
}
Was one option I was trying but it honestly I cant seem to get my head around it.
Any Help would be greatly appreciated.
Well, here is one approach. This uses the ternary (?:) operator to condense the operations. Edited base on clarification from the OP. The example you gave is actually a 14 digit string. But the following will work with any number of digits if they start out in a string. If you have a long value, then you can create the character array using:
long v = 49209999856459L;
char[] d = Long.toString(v).toCharArray();
Here is the main algorithm.
String s = "49209999856459";
int sum = 0;
char[] d = s.toCharArray();
for (int i = 0; i < d.length; i++) {
int v = d[i] - '0';
// The even digit will only be greater than 9 after
// doubling if it is >= 5 before.
sum += ((i % 2) == 1) ? v : (v >= 5) ? v+v-9 : v+v;
}
System.out.println(sum);
Prints
86
So I'm kind of new to Java and decided to create a sliding number puzzle of some sort. Here's what I have :
int[] puz = {1,2,3,
4,5,6,
7,8,9}
for(int i=0; i<puz.length; i++){
System.out.println(puz[i]);
}
The 1 is supposed to be the blank spot but I'll figure that out later. My problem is that the code prints:
1
2
3
4
5
6
7
8
9
when I want it to print:
1 2 3
4 5 6
7 8 9
I've also tried doing a nested loop that I'm too embarrassed to show on here due to how hideous it was.
Would I try using a 2d array instead?
I guess you could try...
int puz = {1,2,3,4,5,6,7,8,9};
int n = Math.ceil(Math.sqrt(puz.length));
for (int i = 0; i < puz.length; i++) {
System.out.print(puz[i] + ((i + 1) % n == 0 ? "\r\n" : " ");
}
Try creating a variable counter and increment it every time you iterate through the loop. Using a modulus operator, divide it by 3 and when remainder is 0, create a new line.
int puz = {1,2,3,4,5,6,7,8,9};
int counter = 1;
for(int i=0; i<puz.length; i++){
System.out.print(puz[i]);
if (counter % 3 == 0){
System.out.println("");
}
counter++;
}
The trick here is to use the modulus operator. This operator divides one number by another, and returns the remainder. In java (and everywhere else as far as I know), % is the modulus operator. If you want every third number to have a line break after it, simply divide by three using modulus division, like so:
int[] puz = {1,2,3,4,5,6,7,8,9};
//For what it's worth, you don't have this semicolon in your question, so I added it in.
for(int i=0; i<puz.length; i++){
System.out.print(puz[i] + " ");
if(i % 3 == 2){//It's equal to 2 because you start at 0 and not 1.
System.out.println("");
}
}
This code, when executed, prints the following, which is what you wanted:
1 2 3
4 5 6
7 8 9
/* when I run this code there is no error in fact output generated is also correct but I want to know what is the logical error in this code? please can any one explain what is the logical error. */
class abc
{
public static void main(String arg[]){
int sum=0;
//for-loop for numbers 50-250
for(int i=50;i<251;i++){
// condition to check if number should be divided by 3 and not divided by 9
if(i%3==0 & i%9!=0){
//individual number which are selected in loop
System.out.println(i);
//adding values of array so that total sum can be calculated
sum=sum+i;
}
}
//final display output for the code
System.out.println("the sum of intergers from 50 to 250 that are multiples of 3 and not divisible by 9 \n"+sum);
}
}
My philosophy is "less code == less bugs":
int sum = IntStream.rangeClosed(50, 250)
.filter(i -> i % 3 == 0)
.filter(i -> i % 9 != 0)
.sum();
One line. Easy to read and understand. No bugs.
Change this:
if(i%3==0 & i%9!=0){
to this:
if(i%3==0 && i%9!=0){
& = bitwise and operator
&& = logical operator
Difference between & and && in Java?
The only problems I saw were:
The variable sum was undeclared
Use && in place of &
int sum = 0;
for (int i = 50; i <= 250; i++) {
if (i % 3 == 0 && i % 9 != 0) {
System.out.println(i);
sum = sum + i;
}
}
System.out.println("the sum of intergers from 50 to 250 that are multiples of 3 and not divisible by 9 \n" + sum);
Well, instead of touching every single value from 50 to 250 like you would do here for(int i=50;i<251;i++), you can consider something like this...
int i = 48;
int sum = 0;
while(i < 250) {
i += 3;
if(i%9 != 0)
sum += i;
}
This is somewhat optimized in the sense that I am skipping over values that I know are not possible candidates.
But, there is a much bigger issue in your code. The following code block prints true, sure. But, it is a bad idea to depend on the & since that is not its job. The & is for bitwise AND whereas the && is for logical AND, which is what you are trying to do.
boolean t = true;
boolean f = false;
System.out.println(f&t);
Why?
In Java, if it is a && operation, as soon as you find the first false, you are sure that the expression will evaluate to false. Meanwhile, in your implementation, it would need to evaluate both sides. f&t will evaluate to false, but the JVM would need to look at both the f and t variables. Meanwhile, on using &&, it wouldn't even need to look at the t.
I get some number from URL, if the number is b/w 1 to 4 then I want's the result to be 4, .. and number b/w 4 to 8 then I want result 8 ......And so on.
This is my code. and this is get from url in count value.
adltavailable = Integer.parseInt(count.get(i).toString());
for(int x =0; x<adltavailable; x++)
{
c = "Adultavailable";
category.add(c);
}
//Here is assign the table
int k = 0;
int size = category.size();
while(k < size)
{
for(int z=0; z<size; z++)
{
if(category.get(z).equals("Adultavailable"))
{
mycirimgs[k].setBackgroundResource(R.drawable.adultadd);
}
k++;
}
}
I get total seats value from url .And the value is assigned in table.If suppose i got 3 seats means I assign the table in 3 seats is not look like good.But this three seats assign 4 instead of 3.like wise.So I want the result If I get total seats 1 or 2 or 3 or 4 means I assign the table in 4 seats and 5 or 6 or 7 or 8 means I assign the table in 8 seats like wise. Thanks giving ur support.
I get some number from URL, if the number is b/w 1 to 4 then I want's the result to be 4, .. and number b/w 4 to 8 then I want result 8 ......And so on.
To round x to the next multiple of 4, write
(x + 3) & ~3
where + 3 rounds up and & ~3 clears the bottom two bits making it a multiple of 4.
To round up your input to the next multiple of 4, you can try the following:
Integer result;
if (input % 4 == 0) //Input is already a multiple of 4.
{
result = input
}
else // round up
{
result = ((input / 4) + 1)*4
}
Hope this is what you were looking for.
Lets say I have a number 1-5, now if I have 2, I want 4 as an output, if I had 3 then have 3 as the output, if I have 1 then 4 as the output. Here is a chart of what I want:
1-10 Chart:
Give 1 return 9
Give 2 return 8
Give 3 return 7
Give 4 return 6
Give 5 return 5
What algorithm do I use for such a thing?
I don't see that you need an algorithm as much. What you have is:
InverseNumber = (myCollection.Length - MySelection);
Thats all you need for even numbers.
With a collection of 1 - 6 for example:
Give 2; 6 - 2 = 4. Also if given 4, 6 - 4 = 2.
You will need a slightly different problem for odds:
1 - 5; with 1 given 1 is at index 0, the opposite is 5, 2 given and the inverse ( 5 - 2) is 3. But if 3 is given, there is no inverse. So you might want to also add a catch for:
if (((myCollection.Length *.5).Round) == mySelection) { //Inverse does not exist!!!}
If you are using just integers, and not arrays of numbers then just replace the myCollection.Length with the upperbound integer.
I think the following code will work for what you need:
int a[] = new a[length_needed];
int counter = length_needed;
for(int c = 0; c < length_needed; c++) {
a[c] = counter;
counter--;
}
int number_inputed;
for(int c = 0; c < length needed; c++) {
if(c == number_inputed) System.out.println(a[c]);
}
Let's say you are giving max number as input. Then you are going to have 0-n numbers. For ex., if 9 is the max number you will have 0-9.
Then you can do something like this:
public static void main(String[] a) {
int max = a[0]; // read values from cmd line args
int forWhichNum = a[1]; //for which number we need its inverse
Sop(max- forWhichNum);
}
Integer value = 2;
Integer maxValue = 6;
Integer reverseCounter = 0;
for (int i = maxValue; i > 0; i--) {
reverseCounter++;
if (i == value) {
return reverseCounter;
}
}