Hosoya Triangle in java - java

Objective: Individually, create a recursive representation of Hosoya’s triangle.
Your task: Haru Hosoya, a famous mathematician described a triangle (seen below) which is a triangular arrangement of numbers based on the Fibonacci numbers. Get a height from the user and use an array to store the values on each line. Print out the appropriate number of levels of Hosoya’s triangle using a recursive method. Do NOT assume that the input will be good. You should also implement try…catch blocks to catch erroneous input.
Here is the code I have so far:
public class HosoyaTri {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
boolean continueLoop = true;
int num = s.nextInt();
do {
try {
System.out.println("How many levels?");
System.out.println(num + " levels");
continueLoop = false;
} catch (InputMismatchException im) {
System.err.println("I said INTEGER, try again");
s.nextLine();
} catch (Exception e) {
System.err.println("What did you do?");
}
} while (continueLoop);
int triangle[][] = new int[num][num];
for (int i = 0; i < num; i++) {
for (int j = 0; j < num; j++) {
triangle[i][j] = 0;
}
}
for (int i = 0; i < num; i++) {
triangle[i][0] = 1;
}
for (int i = 1; i < num; i++) {
for (int j = 1; j < num; j++) {
triangle[i][j] = triangle[i - 1][j - 1] * triangle[i - 1][j];
}
}
for (int i = 0; i < num; i++) {
for (int j = 0; j <= i; j++) {
System.out.print(triangle[i][j] + " ");
}
System.out.println();
}
}
}

One problem is that you are reading the number of levels once, before the input loop. You are then prompting for a level and then printing num without giving the user any chance to provide input! You should fix that. You should also be testing against num <= 0.
As far as how to use recursion goes, the entries in Hosoya's triangle can be defined recursively:
H0, 0 = H1, 0 = H1, 1 = H2, 1 = 1
Hn, j = Hn−1, j + Hn−2, j or
Hn, j = Hn−1, j−1 + Hn−2, j−2
Another (equivalent) definition is:
Hn, i = Fi+1 × Fn−i+1
where Fn is the nth Fibonacci number, defined recursively as:
F0 = 0
F1 = 1
Fn = Fn-1 + Fn-2 (n > 1)
I would suggest using one of these definitions to write a (recursive) static method in your class that calculates the correct value for one entry in the triangle (given n and j as arguments). Then you can eliminate the triangle variable and all the code that initializes it. Simply run your output loop and substitute a call to the recursive method where you now access a specific element of triangle. (If for some reason you need to explicitly build the triangle, simply initialize each element by calling the recursive method. As an aside: there's no need to initialize the elements of triangle to 0; Java does that automatically when the matrix is allocated.)

Related

What would be method to find count which contains only numbers one by one

I have just started my java course so still cannot understand a lot of things, help me out please.
So here is the base code
import java.util.Arrays;
import java.util.Scanner;
public class Main<i> {
public static void main(String[] args ) {
System.out.println (" Enter count of digits: ");
Scanner scanner = new Scanner(System.in);
int size = scanner.nextInt();
int [] sourceNumber = new int [size];
System.out.println("Enter your digits with space");
for (int i = 0; i < size; i++) {
sourceNumber[i] = scanner.nextInt();
[...]
So I have no single idea how to make method to find any count with stepful numbers. Example:
I have counts like: 12405346 534952359 6456934 1234567
so I need system to find 1234567 and print it out
For example I made method to find a count with munimum same numbers like this:
[...]
for (int j = 0; j < 10; j++) {
if (digitsCount[j] > 0)
differentDigitsCount++;
}
mindifferent = differentDigitsCount;
for (int k = 1; k < size; k++) {
int differentDigitsCount1 = 0;
int[] digitsCount1 = new int[10];
while (sourceNumber[k] != 0) {
digitsCount1[(int) (sourceNumber[k] % 10)]++;
sourceNumber[k] /= 10;
}
for (int j = 0; j < 10; j++) {
if (digitsCount1[j] > 0)
differentDigitsCount1++;
}
if (mindifferent <= differentDigitsCount1) {
} else {
mindifferent = differentDigitsCount1;
l = k;
}
}
System.out.println("Digit with minimum same numbers: " + moimassiv[l]);
[...]
This code is huge, but its fine for me now. I just need to make method to find stepful counts
I'm assuming that you want to print those numbers whose digits are sorted from smallest to largest. Is that right?
You can convert the number to String, then you can get each digit by using charAt(int index) method
You can iterate over sourceNumber and call hasSortedNumbers() for each one to know if its digits are sorted.
for (int number : sourceNumber) {
String valueOfNumber = String.valueOf(number);
if (hasSortedNumbers(valueOfNumber)) {
System.out.println(number);
}
}
This is the code for hasSortedNumbers()
public static boolean hasSortedNumbers(String valueOfNumber) {
for (int i = 0; i < valueOfNumber.length() - 1; i++) {
if (valueOfNumber.charAt(i) >= valueOfNumber.charAt(i + 1)) {
return false;
}
}
return true;
}
I'm assuming you're going to use this method from main, so it needs to be static, since main is static.
Basically I'm comparing each digit with the next one, if it turns out that the next one is smaller, it returns false. If not, when it exits the for loop, it returns true.

trying to print out array from random numbers from another class

I have basically finished this piece of code, but when I print out the numbers from the array in the lottery class, I get a bunch of seeming gibberish. How can I fix the problem?
import java.util.Scanner;
public class Hw5pr2
{
public static void main(String[] args)
{
Scanner kb = new Scanner(System.in);
int[] rand = new int[5];
System.out.println("please enter 5 number");
for (int a = 0; a<rand.length; a++)
{
rand[a] = kb.nextInt();
}
Lottery k = new Lottery();
System.out.print("your number are: ");
for (int a = 0; a < rand.length; a++)
{
System.out.print(rand[a]+",");
}
System.out.print("The Winning numbers are: ");
for (int a = 0; a < rand.length; a++)
{
System.out.print(k.getArray()+",");
}
System.out.println("you have " + k.RanInput(rand) + " matching number!!");
}
}
import java.util.Random;
public class Lottery
{
private int[] lotteryNumbers = new int[5];
public Lottery()
{
Random rand = new Random();
for (int a = 0; a<lotteryNumbers.length; a++)
{
lotteryNumbers[a] = rand.nextInt(9)+1;
}
}
public int RanInput(int[] Inran)
{
int b = 0;
for (int a = 0; a<lotteryNumbers.length; a++)
{
if (lotteryNumbers[a] == Inran[a])
{
b++;
}
}
return b;
}
public int[] getArray()
{
return lotteryNumbers;
}
}
for (int a = 0; a < rand.length; a++)
{
System.out.print(k.getArray()+","); //k.getArray() which returns you an entire array
}
You are trying to print the entire array. That's why it may show you the reference instead. You can store the array in a temp array and print the contents of that array.
You may try doing something like this:
int[] winningNum = k.getArray();
for (int a = 0; a < winningNum.length; a++)
System.out.print(winningNum[a] + ",");
try something like
System.out.print("The Winning numbers are: ");
for (int a = 0; a < rand.length; a++)
{
System.out.print(k.getArray()[a]+",");
}
note here
for (int a = 0; a<lotteryNumbers.length; a++)
{
if (lotteryNumbers[a] == Inran[a])
{
b++;
}
}
return b;
this is always return lotteryNumbers.length-1; beacause always two arrays are same
When you print out the array, to the best of my knowledge, it calls the toString method.
This returns a hash of the object, not the values it contains. You can call the static method toString from the Arrays class also to print the string values of the array.
System.out.print(Arrays.toString(k.getArray())+",");
or use a for loop
for (int a = 0; a < k.getArray().length; a++)
{
System.out.print(k.getArray()[a]+",");
}
A few things to note:
As others have mentioned, if you want to print the elements of an array, a simple way to do it is with a for loop. Your code won't work the way you want it to unless you access each element of k's lotteryNumbers array separately:
System.out.print("The winning numbers are: ");
for (int a = 0; a < rand.length; a++)
{
System.out.print(k.getArray()[a]); //make sure to include the [a]
if(a != rand.length - 1) //added to help make prints more readable
System.out.print(", ");
}
Secondly, your RanInput function won't behave the way you want it to, assuming you wanted to see how many of the user's numbers match the lottery numbers. Currently, it just checks if the nth number inputted matches the nth lotto number chosen, which is unlikely to be true. Instead, you should do something like this:
public int RanInput(int[] Inran)
{
int count = 0;
for (int i = 0; i<lotteryNumbers.length; i++)
{
for(int j = 0; j < lotteryNumbers.length; j++) {
if (lotteryNumbers[j] == Inran[i])
{
count++;
}
}
}
return count;
}
It compares each of the inputted numbers with each of the lotto numbers. There are more efficient ways to do this than the code above, but I think it should be good enough for now.
I don't think the code you use to generate the lottery numbers account for duplicates (e.g. the numbers might be 1, 2, 2, 1, 3) so you should fix that.
Finally, here's some error checking you should implement if you want to be thorough:
make sure the user inputs exactly 5 numbers
all positive integers
are below some upper bound (say, 100)

Mathematical notation to programming code

I have difficulties with transcripting the following two functions written in mathematical notation into Java code (the input of both functions is an array with D elements):
Can somebody take a look at the code below and tell me if something is wrong with it?
public double firstFunction(double[] arrayOfElements) {
double sum = 0;
double sumTwo = 0;
for(int i = 0; i < arrayOfElements.length; i++) {
for(int j = 0; j < i; j++){
sumTwo = sumTwo + arrayOfElements[j];
}
sum = sum + Math.pow(sumTwo, 2);
}
return sum;
}
public double secondFunction(double[] arrayOfElements) {
double maximum = Math.abs(arrayOfElements[0]);
for (int i = 0; i < arrayOfElements.length; i++) {
if (Math.abs(arrayOfElements[i]) > maximum) {
maximum = Math.abs(arrayOfElements[i]);
}
}
return maximum;
}
The first method should reset sumTwo to zero in every iteration. Currently it accumulates values from one execution of the outer loop to the next. Otherwise it's OK.
Alternatively, and more efficiently, you could notice that the difference between the sumTwo of one iteration and the next is the new array element. This means you don't need the inner loop.
for(int i = 0; i < arrayOfElements.length; i++) {
sumTwo = sumTwo + arrayOfElements[j];
sum = sum + Math.pow(sumTwo, 2);
}
The second method is supposed to return the index of the element with maximum absolute value, not the element itself. Note the subindex i in max.

How do I sort numbers from an array into two different arrays in java?

I have to create a program that takes an array of both even and odd numbers and puts all the even numbers into one array and all the odd numbers into another. I used a for loop to cycle through all the numbers and determine if they are even or odd, but the problem I'm having is that since the numbers in the original array are random, I don't know the size of either the even or the odd array and therefore can't figure out how to assign numbers in the original array to the even/odd arrays without having a bunch of spots left over, or not having enough spots for all the numbers. Any ideas?
Try using an ArrayList. You can use
num % 2 == 0
to see if num is even or odd. If it does == 0 then it is even, else it is odd.
List<Integer> odds = new ArrayList();
List<Integer> evens = new ArrayList();
for (int i = 0; i< array.length; i++) {
if (array[i] % 2 == 0) {
evens.add(array[i]);
}
else {
odds.add(array[i]);
}
}
to convert the ArrayLists back to arrays you can do
int[] evn = evens.toArray(new Integer[evens.size()]);
(Note: untested code so there could be a few typos)
EDIT:
If you are not allowed to use ArrayLists then consider the following that just uses Arrays. It's not as efficient as it has to do two passes of the original array
int oddSize = 0;
int evenSize = 0;
for (int i = 0; i< array.length; i++) {
if (array[i] % 2 == 0) {
evenSize++;
}
else {
oddSize++;
}
}
Integer[] oddArray = new Integer[oddSize];
Integer[] evenArray = new Integer[evenSize];
int evenIdx = 0;
int oddIdx = 0;
for (int i = 0; i< array.length; i++) {
if (array[i] % 2 == 0) {
evenArray[evenIdx++] = array[i];
}
else {
oddArray[oddIdx++] = array[i];
}
}
You can do it without using arrays or any '%' Just a simple idea
input = new Scanner(System.in);
int x;
int y = 0; // Setting Y for 0 so when you add 2 to it always gives even
// numbers
int i = 1; // Setting X for 1 so when you add 2 to it always gives odd
// numbers
// So for example 0+2=2 / 2+2=4 / 4+2=6 etc..
System.out.print("Please input a number: ");
x = input.nextInt();
for (;;) { // infinite loop so it keeps on adding 2 until the number you
// input is = to one of y or i
if (x == y) {
System.out.print("The number is even ");
System.exit(0);
}
if (x == i) {
System.out.print("The number is odd ");
System.exit(0);
}
if (x < 0) {
System.out.print("Invald value");
System.exit(0);
}
y = y + 2;
i = i + 2;
}
}
Use a List instead. Then you don't need to declare the sizes in advance, they can grow dynamically.
You can always use the toArray() method on the List afterwards if you really need an array.
The above answers are correct and describe how people would normally implement this. But the description of your problem makes me think this is a class assignment of sorts where dynamic lists are probably unwelcome.
So here's an alternative.
Sort the array to be divided into two parts - of odd and of even numbers. Then count how many odd/even numbers there are and copy the values into two arrays.
Something like this:
static void insertionSort(final int[] arr) {
int i, j, newValue;
int oddity;
for (i = 1; i < arr.length; i++) {
newValue = arr[i];
j = i;
oddity = newValue % 2;
while (j > 0 && arr[j - 1] % 2 > oddity) {
arr[j] = arr[j - 1];
j--;
}
arr[j] = newValue;
}
}
public static void main(final String[] args) {
final int[] numbers = { 1, 3, 5, 2, 2 };
insertionSort(numbers);
int i = 0;
for (; i < numbers.length; i++) {
if (numbers[i] % 2 != 0) {
i--;
break;
}
}
final int[] evens = new int[i + 1];
final int[] odds = new int[numbers.length - i - 1];
if (evens.length != 0) {
System.arraycopy(numbers, 0, evens, 0, evens.length);
}
if (odds.length != 0) {
System.arraycopy(numbers, i + 1, odds, 0, odds.length);
}
for (int j = 0; j < evens.length; j++) {
System.out.print(evens[j]);
System.out.print(" ");
}
System.out.println();
for (int j = 0; j < odds.length; j++) {
System.out.print(odds[j]);
System.out.print(" ");
}
}
Iterate through your source array twice. The first time through, count the number of odd and even values. From that, you'll know the size of the two destination arrays. Create them, and take a second pass through your source array, this time copying each value to its appropriate destination array.
I imagine two possibilities, if you can't use Lists, you can iterate twice to count the number of even and odd numbers and then build two arrays with that sizes and iterate again to distribute numbers in each array, but thissolution is slow and ugly.
I imagine another solution, using only one array, the same array that contains all the numbers. You can sort the array, for example set even numbers in the left side and odd numbers in the right side. Then you have one index with the position in the array with the separation ofthese two parts. In the same array, you have two subarrays with the numbers. Use a efficient sort algorithm of course.
Use following Code :
public class ArrayComparing {
Scanner console= new Scanner(System.in);
String[] names;
String[] temp;
int[] grade;
public static void main(String[] args) {
new ArrayComparing().getUserData();
}
private void getUserData() {
names = new String[3];
for(int i = 0; i < names.length; i++) {
System.out.print("Please Enter Student name: ");
names[i] =console.nextLine();
temp[i] = names[i];
}
grade = new int[3];
for(int i =0;i<grade.length;i++) {
System.out.print("Please Enter Student marks: ");
grade[i] =console.nextInt();
}
sortArray(names);
}
private void sortArray(String[] arrayToSort) {
Arrays.sort(arrayToSort);
getIndex(arrayToSort);
}
private void getIndex(String[] sortedArray) {
for(int x = 0; x < sortedArray.length; x++) {
for(int y = 0; y < names.length; y++) {
if(sortedArray[x].equals(temp[y])) {
System.out.println(sortedArray[x] + " " + grade[y]);
}
}
}
}
}

pyramid sequence in Java

I am new to Java. Just now I'm practing. If I give input as 6, output should be like this:
1
2 3
4 5 6
Here I'm posting code that I tried:
import java.util.Scanner;
public class Number {
public static void main(String args[]){
int n;
Scanner in = new Scanner(System.in);
n = in.nextInt();
in.close();
int k = 1;
for (int i = 1; i <= n; i++)
{
// k=i;
for (int j = 1; j <= i; j++)
{
System.out.print(" " + k);
if (n==k)
{
break;
}
k++;
}
System.out.println("\n");
}
}
}
If I input n=4,i t show the output as:
1
2 3
4
4
Your break will only exit the inner loop (the one that loops over j). The outer loop will continue to run, leading to extra numbers being printed.
You need to either replace it with a return; or System.exit(0), or put a label in front of your outer loop (the one that loops over i) and use a labeled break.
Properly indent your code. It helps your brain to understand.
That said, the solution is two loops with three variables.
You need a loop that goes from 1 to n.
An inner loop that goes from 1 to the number of elements per line.
And you need the number of elements per line. This variable increases every time the inner loop is executed.
It's a badly worded question, but I'm going to guess you want to know why the extra 4?
The reason is you have nested loops, so the break only breaks one loop. Here's how you break out of the outer loop:
outer: for (int i = 1; i <= n; i++) {
...
break outer;
The label outer is arbitrary - you can call it fred is you want.
int n = 6; // target
int i = 0;
int nextRowAt = 2;
int currentRow = 1;
while (++i <= n) {
if (i == nextRowAt) {
System.out.println();
nextRowAt = ++currentRow + i;
}
System.out.print("" + i + " ");
}
But unless you understand it and can properly explain the code, you will probably get a fail on your assignment.
My suggestion is to start by creating/understanding on pen and paper. Write out the sequences and figure out how the algorithm should work. THEN you start coding it.
int sum =0;
int n =10;
// n------> number till where you want to print
boolean limtCrossed = false;
for (int i = 0; i < n &&!limtCrossed; i++) {
for(int j=0;j<=i;j++) {
sum++;
if (sum>n) {
limtCrossed = true;
break;
}
System.out.print(+ sum +" " );
}
System.out.println("\n");
}
public static void main(String[] args)
{
int n = 10;
int k = 1;
boolean breakOuter = false;
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= i; j++)
{
System.out.print(" " + k);
if (n==k)
{
breakOuter = true;
break;
}
k++;
}
if(breakOuter) break;
System.out.println("\n");
}
}

Categories

Resources