I've written this piece of code to simulate a galton box for a school project:
'''
public class GaltonBoxProject {
public static void main(String[]args){
//This will keep track of the final positions and will sort them
int[] finalColumns = {0,0,0,0,0,0,0};
//will track current pos of the ball
//8 tiers
//start from middle of the box
int randChance;
for(int a = 0; a < 100; a++) {
int currentPos = 3;
for (int i = 0; i < 9; i++) {
//resets the number
randChance = (int) (Math.random() * 100) + 1;
//if less than 50 go to the left
//if 0 --> +
//if 8 --> -
if(currentPos == 0 && randChance > 50) {
currentPos++;
}
else if (currentPos == 7 && randChance <= 50) {
currentPos--;
}
else if(currentPos != 7 && currentPos != 0 && randChance > 50){
currentPos++;
}
else if(currentPos != 7 && currentPos != 0 && randChance < 50){
currentPos--;
}
//If you want to know why I got these results
//I genuinely can't find the reason why this pattern happens
//System.out.print(" RAND: " + randChance);
//System.out.println(" POS: " + currentPos);
}
//Also debugging
//System.out.println(a + " CURRENT POS: " + currentPos);
//This will sort the numbers
for(int k = 0; k < 7; k++){
if(k == currentPos){
finalColumns[k]++;
}
}
}
//for(int i = 0; i < 8; i ++) {
// System.out.println("KEY: " + finalColumns[i]);
}
for(int k = 0; k < 7; k++){
System.out.print(k + ": ");
for(int j = 0; j < finalColumns[k]; j++){
System.out.print("*");
}
System.out.println("");
}
}
'''
I get this result:
0: ********
1: ********
2: **********************
3: ***
4: ******************************
5: *****
6: *****************
I should be getting a bell curve and I don't know why the code is doing this
Related
That's the multi dimensional array :
{ 3 13 15 28 30} ,
{55 54 53 27 26} ,
{54 12 52 51 50} ,
{50 10 8 53 11} ,
The output should be if num = 1 : 6 , because from [1][0] to [1][2] its 3 and then from [2][2] to [2][3] its 2 so it will be 6 , num its the slope that the user want , the slope can be to the right or to down , its forbidden to use loop of any kind , only recursion, tried for like 8 hours to solve it but i am so confused , here is my code :
private static int longestSlope (int [][] mat, int num , int i , int j , int count , int temp,int oldi,int oldj,boolean found)
{
System.out.println("oldi " +oldi);
System.out.println("oldj " +oldj);
System.out.println("temp " +temp);
System.out.println("count "+count);
System.out.println("i "+i);
System.out.println("j "+j);
if(i == mat.length-1 && j == mat[0].length-1)
return count;
if(i != mat.length && j != mat[0].length)
{
if(j < mat[0].length-1 && mat[i][j] - num == mat[i][j+1] ) // keep j+
{
if(temp == 0)
{
found = true;
oldj = j;
oldi = i;
}
System.out.println("check2");
if(j == 0)
temp = longestSlope(mat,num,i,j+1,count,temp+1,oldi,oldj,found);
else
temp = longestSlope(mat,num,i,j+1,count,temp+1,oldi,oldj+1,found);
}
else if(i < mat.length-1 && mat[i][j] - num == mat[i+1][j])
{
if(temp == 0)
{
found = true;
oldj = j;
oldi = i;
}
temp = longestSlope(mat,num,i+1,j,count,temp+1,oldi,oldj,found);
}
else if(j < mat[0].length-1)
temp = longestSlope(mat,num,i,j+1,count,temp,oldi,oldj,found);
else if(found)
{
System.out.println(found);
System.out.println("found i "+i);
System.out.println("found j "+j);
found = false;
if(j != mat[0].length-1)
temp = longestSlope(mat,num,oldi,oldj,count,0,oldi,oldj,found);
else if(j == mat[0].length-1 && temp != 0)
temp = longestSlope(mat,num,oldi,oldj,count,0,oldi,oldj,found);
else
temp = longestSlope(mat,num,oldi+1,0,count,0,oldi,oldj,found);
}
}
if(i < mat.length-1 && !found)
{
System.out.println("oldj222222222 "+oldj);
return longestSlope(mat,num,i+1,0,count,0,0,0,found);
}
return 0;
}
I'm doing the Conway's game of life. I'm pretty sure I'm close to finished, but when I run it, I get Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at game.of.life.GameOfLife.generation(GameOfLife.java:77)
at game.of.life.GameOfLife.main(GameOfLife.java:32)
Java Result: 1
I'm assuming when the method that checks neighbors at the edges of the array, there's nothing there so it dies or something. I just don't know how to make it so that doesn't happen. Does anyone have any thoughts? Code below.
package game.of.life;
import java.util.Scanner;
public class GameOfLife {
static boolean[][] current = new boolean[10][10];
static boolean[][] old = new boolean[10][10];
static int population = 10;
public static void main(String[] args) {
String a = " # ";
String b = " ' ";
int choice = 9;
int gencount = 0;
Scanner input = new Scanner(System.in);
System.out.print("Choose population density. i.e. 10 = 10%: ");
population = input.nextInt();
populate();
copy();
for(int r = 0; r < current.length; r++){
for(int c = 0; c < current[r].length; c++){
if(current[r][c] == true){
System.out.print(a);
}
else
System.out.print(b);
}
System.out.println();
}
System.out.print("Generation " + gencount + ".");
while(choice != 0){
System.out.print("Make a selection: 1 - Advance Generation 0 - Exit");
choice = input.nextInt();
if(choice == 1){
generation();
for(int r = 0; r < current.length; r++){
for(int c = 0; c < current[r].length; c++){
if(current[r][c] == true){
System.out.print(a);
}
else
System.out.print(b);
}
System.out.println();
}
copy();
gencount += 1;
System.out.println("Generation" + gencount + ".");
}
}
}
private static void generation(){
for(int r = 0; r < old.length; r++){
for(int c = 0; c < old[r].length; c++){
if (old[r][c] == true){
int neighbors = 0;
if(old[r + 1][c] == true)
neighbors += 1;
if(old[r - 1][c] == true)
neighbors += 1;
if(old[r][c + 1] == true)
neighbors += 1;
if(old[r][c - 1] == true)
neighbors += 1;
if(old[r + 1][c + 1] == true)
neighbors += 1;
if(old[r + 1][c - 1] == true)
neighbors += 1;
if(old[r - 1][c - 1] == true)
neighbors += 1;
if(old[r - 1][c + 1] == true)
neighbors += 1;
if(neighbors != 3 || neighbors != 2)
current[r][c] = false;
}
else if(old[r][c] == false){
int neighbors = 0;
if(old[r + 1][c] == true)
neighbors += 1;
if(old[r - 1][c] == true)
neighbors += 1;
if(old[r][c + 1] == true)
neighbors += 1;
if(old[r][c - 1] == true)
neighbors += 1;
if(old[r + 1][c + 1] == true)
neighbors += 1;
if(old[r + 1][c - 1] == true)
neighbors += 1;
if(old[r - 1][c - 1] == true)
neighbors += 1;
if(old[r - 1][c + 1] == true)
neighbors += 1;
if(neighbors == 3)
current[r][c] = true;
}
}
}
}
private static void populate(){
for(int r = 0; r < current.length; r++){
for(int c = 0; c < current[r].length; c++){
int q = (int)(Math.random() * 100);
if(q < population){
current[r][c] = true;
}
else{
current[r][c] = false;
}
}
}
}
private static void copy(){
for(int r = 0; r < old.length; r++){
for(int c = 0; c < old[r].length; c++)
old[r][c] = current[r][c];
}
}
}
If anyone can help me out it would be much appreciated.
When r is 0, this one is not valid: old[r - 1][c].
Thus you get the exception you posted.
I suggest you simplify it like this.
boolean isValidPosition(int r, int c){
return
0 <= r && r < N &&
0 <= c && c < M;
}
int getNeighboursCount(boolean[][] old, int r, int c){
int neighbors = 0;
for (int i=-1; i<=1; i++){
for (int j=-1; j<=1; j++){
if (i!=0 || j!=0){
if (isValidPosition(r + i, c + j)){
if(old[r + i][c + j])
{
neighbors++;
}
}
}
}
}
return neighbors;
}
As I can see, you basically have two choices:
apply finite bounds, that is, for the cells in the first and last columns and rows, you implement an additional check when counting the number of 'living' neighbours.
apply periodic bounds, that is, the cells on the leftmost column and the cells on the rightmost column are considered as neighbours. With the help of modular arithmetic, these cells don't need to be handled separately from others.
So I have been asked this question and I could only solve the top part of the code, I am stuck on the bottom part.
Write a Java program called EmptyDiamond.java that contains a method that takes an integer n and prints a empty rhombus on 2n − 1 lines as shown below. Sample output where n = 3:
1
2 2
3 3
2 2
1
Here's my code so far:
public static void shape(int n) {
//TOP PART
for (int i = 1; i <= (n - 1); i++) {
System.out.print(" ");
}
System.out.println(1);
for (int i = 2; i <= n; i++) {
for (int j = 1; j <= (n - i); j++) {
System.out.print(" ");
}
System.out.print(i);
for (int j = 1; j <= 2 * i - n + 1; j++) {
System.out.print(" ");
}
System.out.println(i);
}
//BOTTOM PART (The messed up part)
for (int i = n + 1; i <= 2 * n - 2; i++) {
for (int j = 1; j <= n - i; j++) {
System.out.print(" ");
}
System.out.print(i);
for (int j = 1; j <= n; j++) {
System.out.print(" ");
}
System.out.print(i);
}
for (int i = 1; i <= (n - 1); i++) {
System.out.print(" ");
}
System.out.println(1);
}
public static void main(String[] args) {
shape(4);
}
Maybe a little bit late, but because the bottom part of your message is just the first part mirrored you can use a Stack to print the message in reverse order:
public static void main(String[] args) {
int maxNumber = 3;
Stack<String> message = new Stack<>();
// upper part
for (int row = 0; row < maxNumber; row++) {
int prefix = maxNumber - (row + 1);
int spaces = row >= 2 ? row * 2 - 1 : row;
String line = getLine(row, prefix, spaces);
System.out.println(line);
if (row != maxNumber - 1)
message.add(line);
}
// bottom part
while (!message.isEmpty())
System.out.println(message.pop());
}
public static String getLine(int row, int prefix, int spaces) {
StringBuilder line = new StringBuilder("_".repeat(prefix));
line.append(row + 1);
if (row != 0) {
line.append("_".repeat(spaces));
line.append(row + 1);
}
return line.toString();
}
Output:
__1
_2_2
3___3
_2_2
__1
You can of course use any method you want to fill the stack (i.e. to generate the upper part of your message) like with the method this question suggessted. This upper part I describe contains the first line (inclusive) up to the middle line (exclusive).
Here is the program for printing empty diamond:
int n = 3; //change the value of n to increase the size of diamond
int upperCount = 1;
for (int i = n; i >= 1; i--) {
for (int j = i; j >= 1; j--) {
System.out.print(" ");
}
System.out.print(upperCount);
for (int j = 0; j <= upperCount - 2; j++) {
System.out.print(" ");
}
for (int j = 0; j <= upperCount - 2; j++) {
System.out.print(" ");
}
if (upperCount != 1) {
System.out.print(upperCount);
}
upperCount++;
System.out.print("\n");
}
int lowerCount = n - 1;
for (int i = 1; i <= n - 1; i++) {
for (int j = 0; j <= i; j++) {
System.out.print(" ");
}
System.out.print(lowerCount);
for (int j = 0; j <= lowerCount - 2; j++) {
System.out.print(" ");
}
for (int j = 0; j <= lowerCount - 2; j++) {
System.out.print(" ");
}
if (lowerCount != 1) {
System.out.print(lowerCount);
}
lowerCount--;
System.out.print("\n");
}
Do following changes in the Bottom Part of your code:
int lowerCount = n - 1;
for (int i = n - 1; i >= 2; i--) {
for (int j = 1; j <= (n - i); j++) {
System.out.print(" ");
}
System.out.print(i);
for (int j = 1; j <= lowerCount; j++) {
System.out.print(" ");
}
System.out.print(i);
lowerCount -= 2;
}
You can print an empty diamond shape with numbers using two nested for loops over rows and columns from -n to n. The diamond shape is obtained when iAbs + jAbs == n:
int n = 2;
for (int i = -n; i <= n; i++) {
// absolute value of 'i'
int iAbs = Math.abs(i);
for (int j = -n; j <= n; j++) {
// absolute value of 'j'
int jAbs = Math.abs(j);
// empty diamond shape
System.out.print(iAbs + jAbs == n ? jAbs + 1 : " ");
if (j < n) {
System.out.print(" ");
} else {
System.out.println();
}
}
}
Output:
1
2 2
3 3
2 2
1
You can separately define width and height:
int m = 4;
int n = 2;
int max = Math.max(m, n);
for (int i = -m; i <= m; i++) {
// absolute value of 'i'
int iAbs = Math.abs(i);
for (int j = -n; j <= n; j++) {
// absolute value of 'j'
int jAbs = Math.abs(j);
// empty diamond shape
System.out.print(iAbs + jAbs == max ? jAbs + 1 : " ");
if (j < n) {
System.out.print(" ");
} else {
System.out.println();
}
}
}
Output:
1
2 2
3 3
3 3
2 2
1
See also:
• Filling a 2d array with numbers in a rhombus form
• How to print a diamond of random numbers?
java-11
Using String#repeat introduced as part of Java-11, you can do it using a single loop.
public class Main {
public static void main(String[] args) {
int n = 3;
for (int i = 1 - n; i < n; i++) {
int x = Math.abs(i);
System.out.println(" ".repeat(x) + (n - x)
+ " ".repeat(Math.abs((n - x) * 2 - 3))
+ ((i == 1 - n || i == n - 1) ? "" : (n - x)));
}
}
}
Output:
1
2 2
3 3
2 2
1
You can print a variant of the diamond simply by increasing the amount of space by one character:
public class Main {
public static void main(String[] args) {
int n = 3;
for (int i = 1 - n; i < n; i++) {
int x = Math.abs(i);
System.out.println(" ".repeat(x) + (n - x)
+ " ".repeat(Math.abs((n - x) * 2 - 3))
+ ((i == 1 - n || i == n - 1) ? "" : (n - x)));
}
}
}
Output:
1
2 2
3 3
2 2
1
Alternative solution:
public static void main(String[] args) {
int n = 7;
for (int i = -n; i <= n; i++) {
for (int j = -n; j <= n; j++) {
// edge of the diamond
int edge = Math.abs(i) + Math.abs(j);
// diamond shape with numbers
if (edge == n) System.out.print(n - Math.abs(i) + 1);
// beyond the edge && in chessboard order || vertical borders
else if (edge > n && (i + j) % 2 != 0 || Math.abs(j) == n)
System.out.print("*");
// empty part
else System.out.print(" ");
}
System.out.println();
}
}
Output:
** * * 1 * * **
* * * 2 2 * * *
** * 3 3 * **
* * 4 4 * *
** 5 5 **
* 6 6 *
*7 7*
8 8
*7 7*
* 6 6 *
** 5 5 **
* * 4 4 * *
** * 3 3 * **
* * * 2 2 * * *
** * * 1 * * **
See also: How to print a given diamond pattern in Java?
Solution: Java program called EmptyDiamond.java that contains a method that takes an integer n and prints a empty rhombus on 2n − 1 lines.
public class EmptyDiamond {
public static void main(String[] args) {
shape(3); // Change n to increase size of diamond
}
public static void shape(int n) {
int max = 2 * n - 1; // length of the diamond - top to bottom
int loop = 0; // with of each loop. initialized with 0
for (int i = 1; i <= max; i++) {
int val = 0;
if (i <= n) {
loop = n + i - 1;// e.g. when i = 2 and n = 3 loop 4 times
val = i; // value to be printed in each loop ascending
} else {
loop = n + (max - i); //e.g. when i = 4 and n = 3 loop 4 times
val = max - i + 1; // value to be printed in each loop descending
}
for (int j = 1; j <= loop; j++) {
// (value end of loop)
// || (value in the beginning when i <= n)
// || (value in the beginning when i > n)
if (j == loop
|| j == (n - i + 1)
|| j == (n - val + 1)) {
System.out.print(val); // Print values
} else {
System.out.print(" "); // Print space
}
}
System.out.println(); // Print next line
}
}
}
Output when n = 3:
1
2 2
3 3
2 2
1
Stream-only function:
public static void printEmptyDiamond(int n) {
IntStream.range(1, 2*n)
.map(i-> i > n ? 2*n-i : i)
.mapToObj(i -> " ".repeat(n-i) + i + (i>1 ? " ".repeat(2*(i-1)-1)+i : ""))
.forEach(System.out::println);
}
Example output (printEmptyDiamond(7)):
1
2 2
3 3
4 4
5 5
6 6
7 7
6 6
5 5
4 4
3 3
2 2
1
With explainations:
public static void printEmptyDiamond(int n) {
IntStream.range(1, 2*n)
.map(i-> i > n? 2*n-i : i) // numbers from 1 to n ascending, then descending to 1 again
.mapToObj(i -> " ".repeat(n-i) // leading spaces
+ i // leading number
+ (i>1 ? // only when number is > 1
" ".repeat(2*(i-1)-1) // middle spaces
+ i // trailing number
: ""))
.forEach (System.out::println);
}
I did it for fun, here's the code :
import java.util.Scanner;
public class Diamond {
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
int num = read.nextInt();
read.nextLine();
//TOP
for(int i = 1;i<=num;i++) {
//LEFT
for(int k = i; k<num;k++) {
if ( k % 2 == 0 ) {
System.out.print(" ");
}
else {
System.out.print(" ");
}
}
if(i>1) {
for(int j =1;j<=i;j++) {
if (j==1 || j== i) {
for(int u=0;u<j;u++) {
System.out.print(" ");
}
System.out.print(i);
}
else {
System.out.print(" ");
}
}
System.out.println("");
}
else {
System.out.println(" "+i);
}
}
//BOTTOM
for(int i = num-1;i>0;i--) {
for(int k = i; k<num;k++) {
if ( k % 2 == 0 ) {
System.out.print(" ");
}
else {
System.out.print(" ");
}
}
if(i>1) {
for(int j =1;j<=i;j++) {
if (j==1 || j== i) {
for(int u=0;u<j;u++) {
System.out.print(" ");
}
System.out.print(i);
}
else {
System.out.print(" ");
}
}
System.out.println("");
}
else {
System.out.println(" "+i);
}
}
}
}
And the output :
7
1
2 2
3 3
4 4
5 5
6 6
7 7
6 6
5 5
4 4
3 3
2 2
1
Having seen the other answers, there's a whole load of loops I could've skipped. Just decided to wing it at the end and do it as quick as possible.
"Only one while loop should be used to determine all even and odd numbers between 50 and 100."
public class EvenOdd {
public static void main(String args[]) {
int x = 50;
int y = 50;
int i = 0;
int j = 0;
int n = 0;
System.out.print("Even numbers between 50 and 100: ");
while((i != x) || (j != y)) {
n++;
System.out.print(i + x + ", ");
i += 2;
if(i != x)
continue;
System.out.println("100");
System.out.print("\nOdd numbers between 50 and 100: ");
System.out.print((j+1) + y + ", ");
j += 2;
if(j != y)
continue;
}
}
}
The evens print fine but the odds continue on forever. This may be a dumb question, but I'm having the biggest brainfart right now, and I would really appreciate help on this.
Simply try this and let me know. It's based on your code, with just a few minor adjustments:
public class Teste4 {
public static void main(String args[]) {
int x = 50;
int y = 50;
int i = 0;
int j = 1;
int n = 0;
System.out.print("Even numbers between 50 and 100: ");
while((i < x) || (j < y)) {
if(i < x){
System.out.print(i + x + ", ");
i += 2;
continue;
}else if(i == x){
System.out.println("100");
i++;
}
if(j == 1){
System.out.print("\nOdd numbers between 50 and 100: ");
}
System.out.print(j + y + ", ");
j += 2;
}
}
}
Perhaps you should try this
int even_counter = 50;
int odd_counter=51;
System.out.println("Even numbers between 50 and 100: ");
while((even_counter < 100 ) || (odd_counter < 100)){
if(even_counter < 100){
System.out.print(even_counter+ " ");
even_counter+=2;
continue;
}
if(odd_counter < 100){
if(odd_counter == 51){
System.out.println("\nOdd numbers between 50 and 100: ");
}
System.out.print(odd_counter+ " ");
odd_counter+=2;
}
}
I'm sure this is an assignment but i'll add my 2 cents since it's solved. This one will give you an array.
final int EVEN = 0, ODD = 1;
int low = 50, high = 100, current = low;
int[][] numbers = new int[2][];
numbers[EVEN] = new int[((high - low) / 2) + ((high - low) % 2)];
numbers[ODD] = new int[((high - low) / 2)];
while(current < high){
numbers[current % 2][(current - low) / 2] = current++;
}
System.out.println("EVEN" + Arrays.toString(numbers[EVEN]));
System.out.println("ODD " + Arrays.toString(numbers[ODD]));
Alternative approach ,
int current = 50 , end = 100 ;
String odd , even ;
while(current <= 100){
if (current % 2 == 0)
even = even.concat ("," + current);
else
odd = odd.concat("," + current);
current++;
}
System.out.println("Even no are : " + even);
System.out.println("Odd no are : " + odd);
I dont have a compiler now . I think this should be right :) .
Im working on a pyramid on Java. I did it with stars. But i want to do it with decreasing numbers. I'm using an input. Assume input is 5;
5
545
54345
5432345
543212345
My code is;
int size = 11;
for (int i = 1; i <= size; i=i+2) {
int spaceCount = (size - i)/2;
for(int j = 0; j< size; j++) {
if(j < spaceCount || j >= (size - spaceCount)) {
System.out.print(" ");
} else {
System.out.print("*");
}
}
System.out.println();
}
I'm very glad to for your attention. Thanks a lot.
int size = 11;
for (int i = 1; i <= size; i=i+2) {
int spaceCount = (size - i)/2;
for(int j = 0; j< size; j++) {
if(j < spaceCount || j >= (size - spaceCount)) {
System.out.print(" ");
} else {
System.out.print(n);
}
}
System.out.println();
}
Something like this ?
But this only works for numbers of 1 - 9.
int h = 2;
String spacing = h == 1 ? "" : String.format("%" + (h - 1) + "s", "");
StringBuilder s = new StringBuilder(String.valueOf(h));
System.out.printf("%s%s\n", spacing, s);
for(int i = h; i > 1; --i){
System.out.print(spacing.substring(0, i - 2));
s.insert(s.length() / 2 + 1, String.valueOf(i - 1) + String.valueOf(i));
System.out.println(s.toString());
}