class Solution {
public static void main(String[] argh) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
for (int i = 0; i < t; i++) {
int number = 1;
System.out.format("%" + (t - i) * 2 + "s", "");
for (int j = 0; j <= i; j++) {
System.out.format("%4d", number);
// how this formula was derived ???
number = number * (i - j) / (j + 1);
}
System.out.println();
}
}
}
The only thing I want to know is that how the formula for generating each element was derived, it works perfect but how?
number = number * (i - j) / (j + 1)
Just want to derive such expressions in similar questions.
Each row of Pascal's triangle is generated by iterating through the binomial coefficient function, nCr:
Lets compare this to nCr+1:
The second factor on the second line is exactly the factor (i - j) / (j + 1) which you multiply by to obtain the next number in the row. In the code j = r, i = n.
Related
I wrote a code in java for school to compute the median of an array.
We have some test cases for this. The first column is the input, the second the expected and the third the actual output. Is anything special on the case that does not work? I've worked so long on this code now and slowly but surely i am getting frustrated. I really don't know where or why my code does not work in this specific scenario. the code is the following:
/**
* This class calculates the median of a list to use it in quicksort for a runtime of O(log(n));
* #author Niklas
*
*/
public class Median {
/**
* The position i.
*/
private static int positionI = -1;
/**
* a help array for the quicksort algorithm.
*/
private static int[] quicksortArray;
/**
* Computes and retrieves the lower median of the given array of numbers using
* the Median algorithm presented in the lecture.
*
* #param input numbers.
* #return the lower median.
* #throw IllegalArgumentException if the array is {#code null} or empty.
*/
public static int lowerMedian(int[] numbers) {
if (numbers.length == 0 || numbers == null) {
throw new IllegalArgumentException("Array must contain values");
}
// avoiding that positionI is part of the recursion
if (positionI == -1) {
positionI = (int) Math.floor((double) ((numbers.length + 1) / 2));
}
// Step 1: dividing the list into groups.
int[] medians = new int[(int) Math.ceil((float) numbers.length / 5)];
int[] subArray = new int[5];
int positionForMedianArray = 0;
// the end case that the array is < 5.
if (numbers.length <= 5) {
sortArray(numbers);
if (positionI <= numbers.length) {
return numbers[positionI - 1];
}
return numbers.length % 2 == 0 ? numbers[(numbers.length / 2) - 1] : numbers[numbers.length / 2];
}
for (int i = 0; i < numbers.length; i += 5) {
if (numbers.length < i + 5) {
subArray = Arrays.copyOfRange(numbers, i, numbers.length);
} else {
subArray = Arrays.copyOfRange(numbers, i, i + 5);
}
// Step 2: calculate the median of each subArray.
sortArray(subArray);
medians[positionForMedianArray] = subArray.length % 2 == 0 ? subArray[subArray.length / 2 - 1]
: subArray[subArray.length / 2];
positionForMedianArray += 1;
}
// Step 3: calculate x recursively
int x = lowerMedian(medians);
// Step 4: partioniate the lists.
// computing how big the arrays have to be because arraylists doesnt work as
// good in this code.
int countS = 0;
int countG = 0;
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] < x) {
countS += 1;
} else if (numbers[i] > x) {
countG += 1;
}
}
// creating the arrays with the right size.
int[] smaller = new int[countS];
int[] greater = new int[countG];
countS = 0;
countG = 0;
// filling the Arrays (L1 and L2).
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] < x) {
smaller[countS] = numbers[i];
countS += 1;
} else if (numbers[i] > x) {
greater[countG] = numbers[i];
countG += 1;
}
}
int k = smaller.length + 1;
// for testing
// System.out.println("\nnumbers: " + Arrays.toString(numbers));
// System.out.println("position i: " + positionI);
// System.out.println("SubArray " + (positionForMedianArray) + ": " + Arrays.toString(subArray));
// System.out.println("Median Array im Durchlauf " + (positionForMedianArray) + ": " + Arrays.toString(medians));
// System.out.println("x: " + x);
// System.out.println("L1: " + Arrays.toString(smaller));
// System.out.println("L2: " + Arrays.toString(greater));
// System.out.println("Position k: " + k);
if (positionI < k) {
return lowerMedian(smaller);
} else if (positionI > k) {
positionI -= k;
return lowerMedian(greater);
}
return x;
}
/**
* Sorts the given array in an inefficent way.
*
* #param numbers the array to sort.
*/
private static void sortArray(int[] numbers) {
for (int i = 0; i < numbers.length; i++) {
for (int j = 0; j < numbers.length; j++) {
if (numbers[i] < numbers[j]) {
int tempVar = numbers[j];
numbers[j] = numbers[i];
numbers[i] = tempVar;
}
}
}
}
I would appreciate any kind of help!
I'm not sure why your approach for calculating low median is so complicated. All you need to do is sort the list of number and if the list has odd number of values then just return value at <array length> / 2 and if the list has even number of values then return value at (<array_length> / 2) - 1. Regarding the sorting the input list, you can either implement your own quicksort algorithm or use Arrays.sort. Below is a potential approach to calculate lower median using Java built-in sort method.
public static int lowerMedian(int[] numbers) {
Arrays.sort(numbers, 0, numbers.length);
int length = numbers.length;
if (length == 0) {
return 0;
} else if (length % 2 == 0) {
return numbers[(length / 2) - 1];
} else {
return numbers[length / 2];
}
}
I'm trying to write a program using Java, that (outputs) the following pattern depending on an input (integer) (n = 5):
0********1
23******45
678****901
2345678901
As you noticed:
input(3) represent 3 rows
single row digits (n * 2)
Digits should start from 0 to 9 and then repeat until the pattern is fully done
First row should have only 2 numbers (start 0 end 1)
(*) will be in between
Next row should have 4 numbers (start 23 end 45) and so on
How can this program written?
Here is my code:
import java.util.Scanner;
public class b_test_2 {
public static void main (String arug[]) {
String star = "*";
int star_count, digit = 0;
Scanner sc = new Scanner(System.in);
System.out.print("Please type a number (int)");
int n = sc.nextInt();
while (n != 0){
star_count = n * 2 - 2;
for (int i=0; i<n; i++) {
System.out.print(star);
i = i + 1;
}
String stars = star;
n = n - 1;
for (int i2=0; i2<n; i2++) {
System.out.print(star);
i2 = i2 + 1;
int x = 0;
x = digit;
x = x + 1;
if (x == 10){
x = 0;
System.out.print(digit + stars + digit);
}
}
}
}
}
There are any parts missing in your code, but you also seem to make it more complicated than it is.
To illustrate, and hopefully help you to go in the right direction, here is compact code to do it. Do not hand in this code unless you fully understand how it works.
static void printPattern(int n) {
for (int row = 1, digit = 0; row <= n; row++) {
for (int i = 0; i < row; i++, digit = (digit + 1) % 10)
System.out.print(digit);
for (int i = (n - row) * 2; i > 0; i--)
System.out.print('*');
for (int i = 0; i < row; i++, digit = (digit + 1) % 10)
System.out.print(digit);
System.out.println();
}
}
Test
printPattern(4);
Output
0******1
23****45
678**901
23456789
I case you haven't learned it yet, the % operator calculates the remainder after division.
I want to print a grid shape on the output console in Eclipse.
Basically I took an integer from user that is the number of stars in a single border of the grid.
Here the code I have up to now:
public class PrintDiamond {
public static void main(String[] args) {
System.out.print("Enter the number: ");
Scanner scan = new Scanner(System.in);
int num = scan.nextInt();
num--;
for (int i = num; i > 0; --i) {
//Insert spaces in order to center the diamond
for (int n = 0; n < i; ++n) {
System.out.print(" ");
}
System.out.print(" *");
for (int n = i; n < num; ++n) {
System.out.print(" + ");
System.out.print(" ");
}//Ending bracket of nested for-loop
System.out.println();
}//Ending bracket of for loop
//Print out a diamond shape based on user input
for (int i = 0; i <= num; ++i) {//<= to print the last asterisk
//Insert spaces in order to center the diamond
for (int n = 0; n < i; ++n) {
System.out.print(" ");
}
System.out.print(" *");
for (int n = i; n < num; ++n) {
System.out.print(" + ");
System.out.print(" ");
}//Ending bracket of nested for-loop
System.out.println();
}//Ending bracket of for loop
}
}
and the output is (for int. 6):
*
* +
* + +
* + + +
* + + + +
* + + + + +
* + + + +
* + + +
* + +
* +
*
Here is the code:
public static void main(String[] args) {
System.out.print("Enter the number: ");
Scanner scan = new Scanner(System.in);
int num = scan.nextInt();
final char[][] diamond = makeDiamond(num);
for (int i = 0; i < diamond.length; i++) {
for (int j = 0; j < diamond[i].length; j++) {
System.out.print(diamond[i][j]);
}
System.out.println();
}
}
public static char[][] makeDiamond(int n) {
int width = 1 + 4 * (n - 1);
int height = 1 + 2 * (n - 1);
char[][] out = new char[height][width];
int x0 = 2 * (n - 1);
int y0 = n - 1;
for (int i = 0; i < width; i += 2) {
// Top borders
int y1 = Math.abs(y0 - i / 2);
out[y1][i] = '*';
// Bottom borders
int y2 = height - Math.abs(i / 2 - y0) - 1;
out[y2][i] = '*';
if ((x0 - i) % 4 == 0) {
// Plus signs
for (int j = y1 + 1; j < y2; j++) {
out[j][i] = '+';
}
}
}
return out;
}
Some hints for your solution:
Create a method for printing a "diamond row" for a given row width and a given total width of the diamond.
Create a tool method for printing a given number of spaces.
Your main method should have two simple loops: One for the upper, one for the lower half.
The magic is in the method of printing a single diamond row for the given two parameters w and n.
This is always a good approach - reduce your complex problem to a problem with lesser complexity - in this case, by creating methods and using these e.g. in loops.
In your method for printing a single diamond row, you will need to check if you are in an "odd" or "even" row.
Ok, this looks like a school asignment, so I won't write any code.
First you need to understand and write, in pseudo-code or just plain English, what you want to do:
Instructions on how to draw the grid.
How many lines should I print?
How long is each line?
How do I know if I have to print a + or not?
General steps of your program.
Read size of the grid, N.
If N < 1, ask again (or exit program).
If N = 1 or greater, print the grid.
Detailed sub-steps of your program.
Print the grid
Loop for number of lines.
Create empty array/buffer/list/string with correct length for current line.
...
Because right now, it seems like you haven't figured out any of that. And if that's the case, then your problem has nothing to do with Java but rather with basic programming knowledge, which you won't get if we just code the algorith for you.
Two nested for loops from -n to n and one if else statement. The zero point is in the center of a diamond, and the boundary is obtained when:
Math.abs(i) + Math.abs(j) == n
Try it online!
public static void main(String[] args) {
printDiamond(0);
printDiamond(2);
printDiamond(5);
}
static void printDiamond(int n) {
System.out.println("n=" + n);
for (int i = -n; i <= n; i++) {
for (int j = -n; j <= n; j++)
if (Math.abs(i) + Math.abs(j) == n)
System.out.print("* ");
else if (Math.abs(i) + Math.abs(j) < n && j % 2 == 0)
System.out.print("+ ");
else
System.out.print(" ");
System.out.println();
}
}
Output (combined):
n=0
n=2
n=5
*
* * + * * + * * + * *
* * + * * + * * + + + * * + + + * * + + + + + * * + + + * * + + + * * + * * + * *
See also: Print an ASCII diamond of asterisks
Hi can some one please explain me the below derangement/permutation program in a simple way.
From past one week I am banging my head to understand the program. I have understood all the methods but I am not able to understand the "else part". I have tried debugging the program but didn't get clarity to what is happening in the else part.
import java.util.Scanner;
public class Deranged {
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
System.out.println("Enter a number");
int num = s.nextInt();
System.out.println("Number :" + num);
int size = digitSize(num);
System.out.println("Size :" + size);
System.out.println("Permutation :" + fact(size));
int swap = fact(size);
int array[] = digitArray(num, size);
if (size < 3) {
if (size < 2) {
System.out.print(num);
} else {
System.out.println(array[0] + "" + array[1]);
System.out.println(array[1] + "" + array[0]);
}
} else { // NEED CLARITY FROM HERE
int i = 2;
for (int outer = 0; outer <= size - 1; outer++) {
int fix = array[0];
for (int j = 1; j <= swap / size; j++) {
if (i == size) {
i = 2;
}
int temp = array[i - 1];
array[i - 1] = array[i];
array[i] = temp;
i++;
int uniqueNo = fix;
for (int k = 1; k < size; k++) {
uniqueNo = (uniqueNo * 10) + array[k];
}
System.out.println(j + ": " + uniqueNo);
}
int t = array[0];
if ((outer + 1) > size - 1) {
array[0] = array[outer];
array[outer] = t;
} else {
array[0] = array[outer + 1];
array[outer + 1] = t;
}
}
}
}
public static int fact(int num) {
int factNo = 1;
for (int i =num; i > 0; i--)
{
factNo = factNo * i;
}
return factNo;
}
public static int digitSize(int num) {
//int count = String.valueOf(num).length();
// return count;
int count = 0;
while(num>0)
{
num/=10;
count++;
}
return count;
}
public static int[] digitArray(int num, int size) {
int count[] = new int[size];
int i = size - 1, rem;
while (num > 0) {
rem = num % 10;
count[i] = rem;
num = num / 10;
i--;
}
return count;
}
}
In the code size is the number of digits in your number and swap is the factorial of the number of digits. For example, if you enter a 5 digit number the fact function calculates 5 * 4 * 3 * 2 * 1. array is just a list of the digits you entered, ordered from the least significant digit to the most significant.
So here is the pseudo code for the case where the number of digits is 3 or greater. I've interleaved the code to make it clearer.
i = 2
For each digit in the array of digits indexed by outer
- Set fix to the digit currently stored in the first element of the array
int i = 2;
for (int outer = 0; outer <= size - 1; outer++) {
int fix = array[0];
For each index j from 1 to the factorial of the number of digits divided by number of digits
- If i is equal to the number of digits, set i equal to 2
- Swap digit i-1 with digit i in the digit array
- Increment I
int fix = array[0];
for (int j = 1; j <= swap / size; j++) {
if (i == size) {
i = 2;
}
int temp = array[i - 1];
array[i - 1] = array[i];
array[i] = temp;
i++;
Set uniqueNo to the decimal number that the digit array currently represents, except that fix is the least significant digit
Print the uniqueNo for the current value of j
int uniqueNo = fix;
for (int k = 1; k < size; k++) {
uniqueNo = (uniqueNo * 10) + array[k];
}
System.out.println(j + ": " + uniqueNo);
If the current value of outer is the last element in the digit array
- Swap the first digit with the last digit in the array
Else
- Swap the first digit of the array with the digit at outer+1
int t = array[0];
if ((outer + 1) > size - 1) {
array[0] = array[outer];
array[outer] = t;
} else {
array[0] = array[outer + 1];
array[outer + 1] = t;
}
The code is basically iterating factorial/number of digit times for each digit of the number that was input and rearranging the digits with each iteration in a way that wraps around from the last digit to the first. It's difficult to understand partly because the variable names are uninformative.
The number of permutations of n distinct objects is n! (factorial), so the code is just listing all possible permutations of the digits of the number that was input. If there are only 2 digits, there are only two permutations, and of course 1 digit has only one permutation, so those are special cases. If you iterate through each digit, the maximum number of permutations keeping one digit "fixed" is factorial/number of digits.
I am trying to multiply two strings, but I am getting the wrong answer. Any help will be appreciated:
public class stringmultiplication {
public static void main(String[] args) {
String s1 = "10";
String s2 = "20";
int num = 0;
for(int i = (s1.toCharArray().length); i > 0; i--)
for(int j = (s2.toCharArray().length); j > 0; j--)
num = (num * 10) + ((s1.toCharArray()[i - 1] - '0') * (s2.toCharArray()[j - 1] - '0'));
System.out.println(num);
}
}
public static void main(String[] args) {
String number1 = "108";
String number2 = "84";
char[] n1 = number1.toCharArray();
char[] n2 = number2.toCharArray();
int result = 0;
for (int i = 0; i < n1.length; i++) {
for (int j = 0; j < n2.length; j++) {
result += (n1[i] - '0') * (n2[j] - '0')
* (int) Math.pow(10, n1.length + n2.length - (i + j + 2));
}
}
System.out.println(result);
}
This one should be correct implementation without using integers.
You're multiplying the numbers digit-wise, and you're not handling the powers of 10 correctly.
You need to first parse the strings into integers. You're on the right track here. You can simplify the loop indices, and you only have to call toCharArray once. E.g.:
After parsing, you can multiply the integers.
EDIT: If that's not allowed, you need to implement an algorithm like this one, which is a bit more complicated.
One approach is to make an (n + 1) x (m + n) array (strictly an array of arrays), where m and n are the number of digits in each. It will be initialized to 0, and you can use this as an area to put the rows of the immediate and final results. These are then summed with carry. This is obviously a näive algorithm.
E.g. for the example above:
int[][] intermediates = new int[3][4];
This is an upper bound.
Following is the solution which i suggest, what you forgot doing there is keeping the intermediate value.
public class T{
public static void main(String[] args) {
char[] num1 = "127".toCharArray();
char[] num2 = "32".toCharArray();
int[] intermediate = new int[num1.length];
for (int i = 0 ; i < num1.length ; i++ ) {
for(int j = 0 ; j < num2.length ; j++ ) {
int d1 = num1[num1.length - i - 1]-'0';
int d2 = num2[num2.length - j - 1]-'0';
intermediate[i] += d1 * d2 * (int) Math.pow(10,j);
System.out.printf(" %d X %d = %d\n", d1, d2, intermediate[i]);
}
intermediate[i] *= (int) Math.pow(10,i);
System.out.println(" intermediate : " + intermediate[i]);
}
int sum = 0;
for(int i : intermediate) {
sum += i;
}
System.out.println("Sum is = " + sum);
}
}
I found Peter's Algorithm using the pow function to be a bit confusing.
Here is essentially the same algorithm.
Convert your Strings to char[]'s and then run this.
public static int multiply (char A[], char B[]){
int totalSum = 0, sum = 0;
for (int i = 0; i < A.length; i++){
sum = 0;
for (int j = 0; j < B.length; j++){
sum *= 10;
sum += (A[i] - '0') * (B[j] - '0');
}
totalSum *=10;
totalSum += sum;
}
return totalSum;
}