Problem with output, Java - java

I need for my output to be the first 100 pentagonal numbers, ten per row , counting in succession. As it stands my output just repeats itself, i am sure this is a simple answer but i cant seem to come up with it. This was homework and already graded but i would like to figure it out for me to learn. Thanks in advance for any input and help.
package chapter_5;
/**
*
* #author jason
*/
public class Five_One {
public static void main(String[] args) {
for (int k = 1; k < 11; k++) {
for (int n = 1; n < 11; n++) {
System.out.print(getPentagonalNumber(n)+ "\t");
}
System.out.println();
}
}
public static int getPentagonalNumber(int n) {
return n * (3 * n - 1) / 2;
}
}

you are repeatedly calling getPentagonalNumber() with numbers in range [1,10], instead of calling numbers in increasing range. can be solved by adding 10*k [and running k from 0 to 10 instead 1 to 11]
public static void main(String[] args) {
for (int k =0; k < 10; k++) { //range is [0,10) instead [1,11)
for (int n = 1; n < 11; n++) {
System.out.print(getPentagonalNumber((10*k)+n)+ "\t"); //10*k + n instead of n
}
System.out.println();
}
}

It should be:
System.out.print(getPentagonalNumber((k-1) * 10 + n) + "\t");
because if not, you are writing the first 10 pentagonal numbers, ten times.
In any case, I'd rather try to focus on creating a code that is as easy to read/maintain as possible, so I'd use only one loop:
for (int i = 0; i < 100; i++) {
System.out.print(getPentagonalNumber(i + 1) + "\t");
if (i % 10 == 0) {
System.out.println();
}
}

If you need the first 100 pentagonal numbers, you only need one for-loop going from 1 to 100.
Hope this helps.

Your output contains
getPentagonalNumber(n)
where n is the column number. Thus each row is the same.
You'll have to incorporate the row number k also in you calculation:
getPentagonalNumber((k-1) * 10 + n)
i.e. from row to row your index is increased by 10.

Related

Array is printing more numbers than intended?

I'm supposed to create and initialize a 100-element array, then make the 7th element the number "7", and finally print the array, starting a new line every 20 elements. I've been trying to figure this out for a long time and I can't.
My code right now is:
public class Array {
public static void main(String args[]) {
int [] array = new int[100];
for (int a = 0; a < array.length; a++) {
if (array[a] == 6) {
array[a]=7;
array[a] = a + 1;
}
printArray(array);
}
}
public static void printArray(int[] array){
for (int a=0; a < array.length; a++) {
System.out.print(" " + array[a]);
if ((a - 1) % 20 == 0) {
System.out.println("");
}
}
}
}
When I run this my output is a lot of zeros, far more than 100. They are separated every 20 characters as intended, but the seventh element is not 7. I think it has to do with the association between int "a" and my array, but I can't figure it out. I know the solution must be simple but I just cannot see it. Thank you all!
Proper indentation of your code, in particular the main method, reveals what is going on. You are calling printArray from within the for loop, so you are printing the array contents 100 times.
for (int a = 0; a < array.length; a++) {
if (array[a] == 6) {
array[a]=7;
array[a] = a + 1;
}
printArray(array);
}
Move the call to printArray after the } ending brace for the for loop.
Now you'll get 100 0s.
Also, I think you meant to have array[a] = a + 1; executed if the index was not 6, e.g.
if (array[a] == 6) {
array[a] = 7;
} else {
array[a] = a + 1;
}
Additionally, you will want to print a newline after 20 numbers, e.g. after indexes 19, 39, etc., so add 1 to a before calculating the remainder, instead of subtracting 1, so that 19 + 1 = 20, whose remainder is 0.
There are many things wrong. However, to answer your question, you are printing the array 100 times since printArray is inside your first loop.
You misplaced an end parenthesis in your main method. The properly formatted method looks like this:
public static void main(String args[]) {
int [] array = new int[100];
for (int a = 0; a < array.length; a++) {
if (array[a] == 6) {
array[a]=7;
}
array[a] = a + 1;
}
printArray(array);
}
First of all your code is organized very badly so it's very easy for u to miss what went where. You have 2 major mistakes, first of all you called printArray()
Inside your for loop and therefore printed it 100 times.
Second, you kept checking if the value inside the array in index a is 6.
You need to check if a is 6 since it is your index like this:
if(a == 6)
array[a] = 7;
Well, I ran your code, and there are a few places that can be corrected.
As for your problem of the many things being printed, that's because you've placed your printarray() inside the for loop, so it's printing the array 100 times.
As for printing it out, i find this code to be more concise:
public static void printArray(int[] array){
int counter = 0;
for(int i = 0; i < array.length; i++){
System.out.print(array[i] + " ");
counter++;
if(counter == 20){
counter = 0;
System.out.print("\n");
}
}
}
Also, I'm not really sure why you're using a for loop to just change the 7th element. You could use this:
array[6] = 7;
I'm not really sure what you're doing in the for loop.
I hope this helped! Good luck!

Does this program use the Sieve of Eratosthenes?

I have an assignment as follows,
: Use the Sieve of Eratosthenes to locate and print out all prime numbers from 1 to 1000.
Follow a procedure similar to this:
Write down, in order, all number to be considered.
Cross out 1, since it is not considered prime.
Go to the next number not crossed out; leave it, but cross out all multiples of that number.
Repeat step 3 until you pas the number which is half of the largest number considered. At that point, all numbers not crossed out are the desired primes.
Your algorithm may vary slightly from the one above but speed is important.
I wrote this program out using the knowledge I have of math and arrays however as I was researching Sieve, I had no clue if this was the method.
public class PrimeSieve
{
public static void main( String[] args)
{
int max=1000;
calcPrimes( max );
}
public static void calcPrimes( int max )
{
// each boolean value indicates whether corresponding index
// position is composite (non-prime)
boolean[] array = new boolean[max +1 ];
// mark composites as true
for (int i = 2; i <= (int) Math.sqrt( max ); i++)
{
for (int j = i*i; j <= max; j += i) array [j ] = true;
{
// print indexes with corresponding false values
for (int k = 2;k <= max; k++)
{
if ( !array[ k ] )
System.out.format( k + "\n" );
}
}
}
}
}
Any help would be nice!
The problem is that you do not complete the process of marking off composites before printing out the results, possibly because your loops are nested in a confused sort of way.
public static void calcPrimes(int max) {
// each boolean value indicates whether corresponding index
// position is composite (non-prime)
boolean[] array = new boolean[max + 1];
// mark composites as true
for (int i = 2; i <= (int) Math.sqrt(max); i++) {
for (int j = i*i; j <= max; j += i) array[j] = true;
}
// print indexes with corresponding false values
for (int k = 2; k <= max; k++) {
if (!array[k]) System.out.println(k);
}
}
In this example, I have moved the code to print the primes outside of the loop that performs the sieve.

Efficient way of generating all combinations of 12 numbers that add to 100 in Java [duplicate]

This question already has an answer here:
How to iterate through array combinations with constant sum efficiently?
(1 answer)
Closed 9 years ago.
I have 12 products at a blend plant (call them a - l) and need to generate varying percentages of them, the total obviously adding up to 100%.
Something simple such as the code below will work, however it is highly inefficient. Is there a more efficient algorithm?
*Edit: As mentioned below there are just too many possibilities compute, efficiently or not. I will change this to only having a maximum of 5 or the 12 products in a blend and then running it against the number of ways that 5 products can be chosen from the 12 products.
There is Python code that some of you have pointed to that seems to work out the possibilities from the combinations. However my Python is minimal (ie 0%), would one of you be able to explain this in Java terms? I can get the combinations in Java (http://www.cs.colostate.edu/~cs161/Fall12/lecture-codes/Subsets.java)
public class Main {
public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException {
for(int a=0;a<=100;a++){
for(int b=0;b<=100;b++){
for(int c=0;c<=100;c++){
for(int d=0;d<=100;d++){
for(int e=0;e<=100;e++){
for(int f=0;f<=100;f++){
for(int g=0;g<=100;g++){
for(int h=0;h<=100;h++){
for(int i=0;i<=100;i++){
for(int j=0;j<=100;j++){
for(int k=0;k<=100;k++){
for(int l=0;l<=100;l++){
if(a+b+c+d+e+f+g+h+i+j+k+l==100)
{
System.out.println(a+" "+b+" "+c+" "+d+" "+e+" "+f+" "+g+" "+h+" "+i+" "+j+" "+k+" "+l);
}}}}}}}}}}}}}
}
}
Why make it so difficult. Think simple way.
To explain the scenario simpler, consider 5 numbers to be generated randomly. Pseudo-code should be something like below.
Generate 5 random number, R1, R2 ... R5
total = sum of those 5 random number.
For all item to produce
produce1 = R1/total; // produce[i] = R[i]/total;
Please, don't use nested for loops that deep! Use recursion instead:
public static void main(String[] args) {
int N = 12;
int goal = 100;
generate(N, 0, goal, new int[N]);
}
public static void generate(int i, int sum, int goal, int[] result) {
if (i == 1) {
// one number to go, so make it fit
result[0] = goal - sum;
System.out.println(Arrays.toString(result));
} else {
// try all possible values for this step
for (int j = 0; j < goal - sum; j++) {
// set next number of the result
result[i-1] = j;
// go to next step
generate(i-1, sum + j , goal, result);
}
}
}
Note that I only tested this for N = 3 and goal = 5. It absolutely makes no sense to try generating all these possibilities (and would take forever to compute).
Let's take your comment that you can only have 5 elements in a combination, and the other 7 are 0%. Try this:
for (i = 0; i < (1<<12); ++i) {
if (count_number_of_1s(i) != 5) { continue; }
for (j = 0; j < 100000000; ++j) {
int [] perc = new int[12];
int val = j;
int sum = 0;
int cnt = 0;
for (k = 0; k < 12; ++k) {
if (i & (1 << k)) {
cnt++;
if (cnt == 5) {
perc[k] = 100 - sum;
}
else {
perc[k] = val % 100;
val /= 100;
}
sum += perc[k];
if (sum > 100) { break; }
}
else { perc[k] = 0; }
}
if (sum == 100) {
System.out.println(perc[0] + ...);
}
}
}
The outer loop iterates over all possible combinations of using 12 items. You can do this by looping over all numbers from 1:2^12, and the 1s in the binary representation of that number are the elements you're using. The count_number_of_1s is a function that loops over all the bits in the parameter and returns the number of 1s. If this is not 5, then just skip this iteration because you said you only want at most 5 mixed. (There are 792 such cases).
The j loop is looping over all the combinations of 4 (not 5) items from 0:100. There are 100^4 such cases.
The inner loop is looping over all 12 variables, and for those that have a 1 in their bit-position in i, then it means you're using that one. You compute the percentage by taking the next two decimal digits from j. For the 5th item (cnt==5), you don't take digits, you compute it by subtracting from 100.
This will take a LONG time (minutes), but it won't be nearly as bad as 12 nested loops.
for(int a=0;a<=100;a++){
for(int b=0;b<=50;b++){
for(int c=0;c<=34;c++){
for(int d=0;d<=25;d++){
for(int e=0;e<=20;e++){
for(int f=0;f<=17;f++){
for(int g=0;g<=15;g++){
for(int h=0;h<=13;h++){
for(int i=0;i<=12;i++){
for(int j=0;j<=10;j++){
for(int k=0;k<=10;k++){
for(int l=0;l<=9;l++){
if(a+b+c+d+e+f+g+h+i+j+k+l==100)
{
// run 12 for loops for arranging the
// 12 obtained numbers at all 12 places
}}}}}}}}}}}}}
In Original approach(permutation based), the iterations were 102^12 = 1.268e24. Even though the 102th iteration was false, it did check the loop terminating condition for 102th time.
So you had 102^12 condition checks in "for" loops, in addition to "if" condition checks 101^12 times, so in total, 2.4e24 condition checks.
In my solution(combination based),No of for loop checks reduces to 6.243e15 for outer 12 loops, &
if condition checks = 6.243e15.
Now, the no of for loops(ie inner 12 for loops) for every true "if" condition, is 12^12 = 8.9e12.
Let there be x number of true if conditions. so total condition checks
=no of inner for loops*x
= 8.9e12 * x + 6.243e15
I'm not able to find the value of x. however, I believe it wouldnt be large enough to make total conditon checks greater than 2.4e24

How to print the following sequence, while satisfying these conditions

This was actually an interview question. I had to print the following using Java:
9
9 8 9
9 8 7 8 9
9 8 7 6 7 8 9
. . .
. . .
During the interview, I wrote an embarrassing piece of code, but it worked nonetheless - using an outer loop, two inner loops (one for the decrementing sequence and one for the incrementing sequence!) and a ton of variables. One of the variables was the length of each row.
The interviewer asked me to try and rewrite it using
just one outer and one inner loop
without the row length variable.
Note: After looking at the answers, I think the interviewer didn't really mean the second condition. He might have just wanted me to simplify my code and the second point just bumbled out of his mouth.
So, later back home, I arrived at this:
int rowCnt = 5;
for(int i = 1; i <= rowCnt; i++)
{
int val = 9;
int delta = -1;
int rowLen = i * 2 - 1;
for(int j = 1; j <= rowLen; j++)
{
System.out.print(val + " ");
val += delta;
if(j >= rowLen / 2) delta = 1;
}
System.out.println();
}
Here, I am using just one inner loop. I'm using a delta value to determine whether increment or decrement happens. For each row, I compare the current index to the midpoint of the row and change the delta.
I satisfied the first condition - just one inner loop. But I am not able to do it without using the row length.
How can we print this without finding out the row length?
Many answers were acceptable, But I had to choose one, and picked the one that was simplest to understand for me.
They probably wanted to hear the word 'recursion'.
Here's a recursive solution that doesn't need length:
countDownInMiddle("", 9, "");
private static void countDownInMiddle(String start, int n, String end) {
if (n < 0) {
return;
}
System.out.println(start + n + end);
countDownInMiddle(start + n, n - 1, n + end);
}
How about:
int start = 9;
for (int i = 0; i <= start; i++) {
StringBuilder sb = new StringBuilder((start - i) + " ");
for (int j = start - i; j < start; j++) {
sb.insert(0, (j + 1) + " ");
sb.append((j + 1) + " ");
}
System.out.println(sb.toString());
}
This is simple PHP, hope logic is clear and easily portable to Java:
$rowCount = 10;
$startNum = 9;
for ($idx =0; $idx <$rowCount; $idx ++) {
for ($jdx=0; $jdx < (2*$idx +1); $jdx++) {
if ($idx < $jdx)
echo $startNum -(2*$idx) + $jdx.' ';
else
echo $startNum - $jdx.' ';
}
echo '<br/>';
}
public class Pyramid {
public static void main(String[] args) {
int start = 9;
String left = "";
String right = "";
for (int i=start; i>=0; i--) {
System.out.println(left+i+right);
left = left+i;
right = i+right;
}
}
}
Sample output:
9
989
98789
9876789
987656789
98765456789
9876543456789
987654323456789
98765432123456789
9876543210123456789
This iterative solution is equivalent to the recursive solution. I would prefer to use iteration over recursion since the extra stack memory needed by the recursive solution could be huge when the number of rows grows big.
My non-recursive solution:
for(int i = 0; i < 9; i++) {
for(int j = 0; j < 2*i+1; j++)
System.out.print((Math.abs(j - i) + 9 - i) + " ");
System.out.println();
}

Finding specific number in prime number array

I'm trying to find prime numbers with a specific condition in Java.
The challenge is to show all the prime numbers (under 100.000) which contain a '3' four times.
I already have a code which shows all the prime numbers under 100.000, but I can't seem to figure out how to count the ones that contain the number '3' four times.
I can however count all the prime numbers.
Can someone help me with this?
Here's the code I have, where am I going to put the numbers into strings?
package Proeftentamen;
import java.util.regex.*;
/**
*
* #author Stefan
*/
public class Vraag_6 {
/// priemgetallen waar 4x een 3 in voor komt???? wtf...
public static void main(String[] args) {
boolean[] lijst = new boolean[1000000]; // hoeveelheid getallen
vularray(lijst);
lijst = zeef(lijst);
drukaf(lijst);
}
public static void vularray(boolean[] lijst) {
for (int i = 2; i < lijst.length; i++) {
lijst[i] = true;
}
}
public static boolean[] zeef(boolean[] lijst) {
for (int i = 2; i < lijst.length / 2; i++) {
if (lijst[i]) {
for (int j = 2 * i; j < lijst.length; j += i) {
lijst[j] = false;
}
}
}
return lijst;
}
public static void drukaf(boolean[] lijst) {
int count = 0;
for (int i = 2; i < lijst.length; i++) {
if (lijst[i] == true) {
System.out.println(i + " " + lijst[i]);
count++;
}
}
System.out.println("Aantal priemgetallen: " + count);
}
}
This question really sounds like a homework, so you should write down what you have come up with and what you tried so far.
There are a lot of ways to count numbers. Just to give you a clue, you can use the reminder operation (in Java - %):
56 % 10 = 6
25 % 5 = 0
So, when you divide by 10 and use a reminder operation you can get the last digit of your number. Now use a loop and counter and you'll be fine.
Another option (very ugly, so don't really use it :) ) - to turn your number into a String and iterate (loop) over its characters.
Hope this helps and good luck!
This code generate 50 permutation of numbers that has four '3' in it's digits
so check each number that is prime or not
public void generateNumbers() {
StringBuilder s = new StringBuilder();
s.append("3333");
for (int i = 0; i < 5; i++) {
for (int j = 0; j <= 9; j++) {
if (j%3==0) continue;
s.insert(i,String.valueOf(j));
int number=Integer.parseInt(s.toString());
System.out.println(number);
s.delete(i,i+1);
}
}
}
Iterate across each prime number.
For each prime number, convert it to a string using the Integer.toString(int) static method.
With this string, iterate over every character (use a for loop and the non-static method String.charAt(int index)) and count the number of times that method returns '3'. (The character '3', not the String "3").
Unless you have some other purpose for an array of prime-number Strings, don't bother to store them anywhere outside the loop.
Please refer below code to validate all such prime numbers.
void getPrimes(int num ,int frequency,char digit) {
int count = 0;
String number=Integer.toString(num);
for (int i = 0; i < number.length(); i++) {
if (count < frequency) {
if (number.charAt(i) == digit)
count++;
}
if (count == frequency)
{
System.out.println(number);
return ;
}
}
}
Using the primes function from an exercise on the Sieve of Eratosthenes, as well as the digits and filter functions from the Standard Prelude, this Scheme expression finds the seven solutions:
(filter
(lambda (n)
(= (length
(filter
(lambda (d) (= d 3))
(digits n)))
4))
(primes 100000))
The outer filter runs over all the primes less than 100000 and applies the test of the outer lambda to each. The inner filter computes the digits of each prime number and keeps only the 3s, then the length function counts them and the equality predicate keeps only those that have 4 3s. You can run the program and see the solution at http://codepad.org/e98fow2u.
you only have at most five digits, four of which must be 3. So what can you say about the remaining digit?
It's not hard to just write out the resulting numbers by hand, and then test each one for primality. Since there are no more than 50 numbers to test, even the simplest trial division by odds will do.
But if you want to generate the numbers programmatically, just do it with 5 loops: add 10,000 to 03333 9 times; add 1,000 to 30333 9 times; add 100 to 33033 9 times; etc. In C++:
int results[50];
int n_res = 0;
int a[5] = {13333, 31333, 33133, 33313, 33331};
for( int i=0, d=10000; i<5; ++i, d/=10)
for( int j=1; j<9; ++j, a[i]+=d )
if( is_prime(a[i]) )
results[n_res++] = a[i];

Categories