I am trying to write a class that creates an object of a pascal triangle using multidimensional arrays. Now i do have everything in place (at least i think so) except for the correct Initialization of the array. My program reads as follow:
class Pascal{
//Object variables
int size;
int[][] pascal;
Pascal(int size){ //Constructor
this.size = size; //Defines how many rows/columns the triangle has.
pascal = new int[size][];
//Allocation of the arrays
for(int i=0;i<pascal.length;i++)
pascal[i] = new int[i+1];
pascal[0][0] = 1; //the tip of the triangle is always one. Also you need a value to start with.
//Initialisation of the elements
for(int x=0;x<pascal.length;x++){
for(int y=0;y<pascal[x].length;y++){
if(x>0){
if(y==0 || y == (pascal[x].length)-1)
pascal[x][y] = 1; //Initialisation of the first and last element of the actual array x
else
pascal[x-1][y-1] = pascal[x-1][y] + pascal[x-1][y-1];//Initialisation of all elements in between
}
}
}
}
//The print method needed to display the pascal triangle
void print(){
for(int i=0;i<pascal.length;i++){
for(int k=pascal.length;k>i;k--)
System.out.print(" ");
for(int j=0;j<pascal[i].length;j++)
System.out.print(pascal[i][j]+" ");
System.out.println();
}
}
//main function
public static void main(String... args){
Pascal p = new Pascal(5); //example triangle consisting of 5 rows total
p.print();
}
}
The output in this particiular example (new Pascal(5);) should be:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
And yet it is:
1
2 1
1 1 1
1 0 1 1
1 0 0 0 1
I know the problem must be somewhere in the array initialization part of the code and it's probably a simple mistake, but starring at the monitor doesn't get me anywhere anymore :/
Just in case you don't just want to give me the answer:
From my understanding the array element pascal[1][0] should be 1 instead of 2, because when the for-loops value x is 1 and value y is 0 the if-condition if( y==0 || y==pascal[x].length-1) should apply thus setting pascal[1][0] = 1.
Thanks for your help!
In the constructor, when initializing the 2D array, in the else, your assignment is incorrect. You want to initialize the current element, but the left hand side is incorrect (and inconsistent with the if):
pascal[x-1][y-1] = pascal[x-1][y] + pascal[x-1][y-1];
Try the [x][y] element itself.
pascal[x][y] = pascal[x-1][y] + pascal[x-1][y-1];
Making only this change, I get the correct output:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
Related
This recursive program solves the problem of "In how many ways you can score at least 6 in 6 balls/deliveries?"
The details can be found here, https://stackoverflow.com/questions/60117310
This program works fine. Recently I've generalized the program for any amount of Runs with any amount of Balls/deliveries.
My program works fine but it is very slow even for some moderate inputs like Runs = 20, Balls = 10.
I am trying to avoid recursion with Dynamic Programming approach (DP) but couldn't construct the Table correctly since the total runs will not be exactly 20 (in this case) it could be 20 to 25 (considering a 6 when the score was at 19) and balls could be much less than 10 (considering 6, 6, 6, 6 or some other high scoring options).
Any help will be appreciated.
Here is my modified code,
static long count=0;
static int myTarget=20, balls = 10;
public static void waysToDo(int score, int target, List<Short> waySoFar)
{
if(waySoFar.size() > balls ) return; // total balls
if(score >= target)
{
count++;
return;
}
for(short i=0; i<=6; i++) // scoring options per ball
{
waySoFar.add(i);
waysToDo(score+i, target, waySoFar);
waySoFar.remove(waySoFar.size()-1);
}
}
public static void main(String[] args)
{
waysToDo(0, target, new ArrayList<Short>());
System.out.println("Total ways: "+count);
}
Let start from base case.
What happens if we have only one iteration? Every outcome can be achieved only one way, so:
result[0][0] = 1
result[0][1] = 1
result[0][2] = 1
result[0][3] = 1
result[0][4] = 1
result[0][5] = 1
First index is iteration, second is score. Value is number of possible way to achieve it
On second iteration:
0 can be achieved only 1 way.
1 can be achieved two ways: we can score 1 if previous score was 0 or we can score 0 if previous score was 1
2 can be achieved 3 ways: 2 + 0, 1 + 1 and 0 + 2
and so on.
If we generalize we have on step n result be:
0 only 1 way
1 numbers of way to get 1 on step n-1 plus number of ways to get 0 on step n-1
2: result[n-1][0] + result[n-1][1] + result[n-1][2]
m: sum result[n-1][x] where x is between 0 and m
6: you don't need to take into account previous value for 6. So sum result[n-1][x] where x is between 0 and 5.
So you end up with something like
for(int i=1; i<6; i++){
result[0][i]=1;
}
for(int n=1; n<=maxStep; n++){
for(int i=0; i<6; i++){
result[n][i]=0;
for(int j=0; j<5; j++){
result[n][i] += result[n-1][j];
}
}
}
System.out.println(result[maxStep][5]);
If you noticed we only need current and previous, so there is opportunity for memory optimization.
I am really confused why my java code is not working it is giving TLE on Code Monks on Hacker Earth.
Here is the link to the question - Link to Question
the first question MONK AND ROTATION
import java.util.Scanner;
class TestClass {
static int[] ar=new int[100001];
public static void main(String args[] ){
Scanner in=new Scanner(System.in);
byte t=in.nextByte();
while(--t>0){
int n=in.nextInt();
int k=in.nextInt()%n;
for(int i=0;i<n-k;i++)
ar[i]=in.nextInt();
for(int i=0;i<k;i++)
System.out.print(in.nextInt()+" ");
for(int i=0;i<n-k;i++)
System.out.print(ar[i]+" ");
System.out.println();
}
}
}
I don't know why is it giving TLE I think there is some infinite loop going.
the question at the site is-
Monk and Rotation
Monk loves to perform different operations on arrays, and so being the principal of HackerEarth School, he assigned a task to his new student Mishki. Mishki will be provided with an integer array A of size N and an integer K , where she needs to rotate the array in the right direction by K steps and then print the resultant array. As she is new to the school, please help her to complete the task.
Input:
The first line will consists of one integer T denoting the number of test cases.
For each test case:
The first line consists of two integers N and K, N being the number of elements in the array and K denotes the number of steps of rotation.
The next line consists of N space separated integers , denoting the elements of the array A.
Output:
Print the required array.
Constraints:
1<=T<=20
1<=N<=10^5
0<=K<=10^6
0<=A[i]<=10^6
Sample Input
1
5 2
1 2 3 4 5
Sample Output
4 5 1 2 3
Explanation
Here T is 1, which means one test case.
denoting the number of elements in the array and , denoting the number of steps of rotations.
The initial array is:
In first rotation, 5 will come in the first position and all other elements will move to one position ahead from their current position. Now, the resultant array will be
In second rotation, 4 will come in the first position and all other elements will move to one position ahead from their current position. Now, the resultant array will be
Time Limit: 1.0 sec(s) for each input file
Memory Limit: 256 MB
Source Limit: 1024 KB
Think from a different perspective. Instead of splitting the string and converting it into an array and applying the iterative logic, we can apply a different logic.
The trick is you just need to find the position of the input string where we have to split only once.
By that I mean,
input=>
6 2 //4 is the length of numbers and 2 is the index of rotation
1 2 3 4 5 6 //array (take input as a string using buffered reader)
Here, we just need to split the array string at the 2nd last space i.e. 4th space. So the output can be achieved by just splitting the string once-
5 6 1 2 3 4
first split- 5 6 + space + second split- 1 2 3 4
This logic worked for me and all the test cases passed.
Also don't forget to cover the corner case scenario when array input string is just one number.
Code Snippet-
int count=0;
for(int k=0; k<arr.length(); k++) {
if(arr.charAt(k)==' ')
count++;
if(count==size-rot) {
System.out.println(arr.substring(k+1,arr.length())
+ " " + arr.substring(0,k));
break;
}
}
Problem is here
for(int i=0;i<n-k;i++) //this loop you are using for storing input elements in array
ar[i]=in.nextInt();
for(int i=0;i<k;i++) // here you again taking the input you don't need this loop
System.out.print(in.nextInt()+" ");
for(int i=0;i<n-k;i++)
System.out.print(ar[i]+" ");
You also need to change the condition in while loop while(--t>0) to while(--t >= 0). It should be >= 0 other wise it will not work. Other solution is to use post decrement while(t-- > 0)
You are trying to print right rotation of the array. So you need to start printing the elements from index n - k. Then you need to calculate the end index it is (n - k) + n this is because array has n elements. Then you can access array elements like this arr[i % n].
Here is the complete working solution
class TestClass {
static int[] ar = new int[100001];
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
byte t = in.nextByte();
while (--t >= 0) {
int n = in.nextInt();
int k = in.nextInt() % n;
for (int i = 0; i < n; i++)
ar[i] = in.nextInt();
for (int i = n - k; i < n + (n - k); i++)
System.out.print(ar[i % n] + " ");
System.out.println();
}
}
}
I need to write a method that adds the two last elements of two arrays together and add the sum on another array. But if the two elements are more than 10, then I would need to carry that number to the next array.
This program should be similar to what an odometer does.
Here is my sample code.
int [] sum(int []number1, int []number2)
{
int [] total;
int carry = 0;
for ( int k = numbers1 - 1; k >= 0; k++)
{
sum = number1[k] + number2[k] + carry;
carry = sum/10;
total[k] = sum
}
return total;
}
An example output would be:
0 1 2 3 4
0 8 9 9 9
4 5 7 0 3
5 4 7 0 2
So the top array is just a visual aid that tells where the position for the number is.
The program is suppose to add the next two arrays together. i.e. 9 + 3 = 12
Since 12 is above 9, it carries over the 10 to the next set of arrays, that is why the third array only has a 2 in its place, and that is why the next array is 9 + 0 = 0; because the 10 was carried over.
I am not sure why my code won't work. I don't get the right numbers. Could anyone give any hints or solution to the problem?
-Thanks
I assume numbers1 is the number of elements in the array.
In this case it should be k-- instead of k++ because you are starting from the last element and moving backword.
Full Disclosure: Homework.
Explanation: I cant understand my teacher.
Problem:
Write a method called printSquare that takes in two integer
parameters, a min and a max, and prints the numbers in the range from
min to max inclusive in a square pattern. The square pattern is
easier to understand by example than by explanation, so take a look at
the sample method calls and their resulting console output in the
table below. Each line of the square consists of a circular sequence
of increasing integers between min and max. Each line prints a
different permutation of this sequence. The first line begins with
min, the second line begins with min + 1, and so on. When the
sequence in any line reaches max, it wraps around back to min. You
may assume the caller of the method will pass a min and a max
parameter such that min is less than or equal to max
I cannot for the life of me figure out how to make the numbers stop at the 'max' value and start over in the middle of the line.
This is what I have so far, apologies but I have trouble with for loops.
for(int i = 0; i < row; i++)
{
for(int d = 0; d < row; d++)
{
System.out.print(d+1);
}
System.out.println(i);
}
I know I used row twice, but its the only way i can get the compiler to form a square shape with the loop. Does anyone even remotely understand what i'm trying to do? :/
This is actually a nice mathematical problem. Assume:
int side = to - from + 1; /// the size/width of the square.
the value at any point in the square (row, col) is:
from + ((row + col) % side)
you should be able to put that in your loops and "smoke it".
Edit based on comment asking for explanation.
The trick is to loop through all the positions in the 'matrix'. Given that the matrix is square, the loops are relatively simple, just two loops (nested) that traverse the system:
final int side = to - from + 1;
for (int row = 0; row < side; row++) {
for(int col = 0; col < side; col++) {
... magic goes here....
}
}
Now, in this loop, we have the variables row and col which represent the cell in the matrix we are interested in. The value in that cell needs to be proportional to the distance it is from the origin..... let me explain.... If the origin is the top left (which it is), then the distances from the origin are:
0 1 2 3 4
1 2 3 4 5
2 3 4 5 6
3 4 5 6 7
4 5 6 7 8
The distance is the sum of the row and the column...... (rows and columns start counting from 0).
The values we put in each matrix are limited to a fixed range. For the above example, with a square of size 5, it could have been specified as printSquare(1,5).
The value in each cell is the from value (1 in this example) plus the distance from the origin... naively, this would look like:
1 2 3 4 5
2 3 4 5 6
3 4 5 6 7
4 5 6 7 8
5 6 7 8 9
here the values in the cell have exceeded the limit of 5, and we need to wrap them around... so, the trick is to 'wrap' the distances from the origin..... and the 'modulo' operator is great for that. First, consider the original 'origin distance' matrix:
0 1 2 3 4
1 2 3 4 5
2 3 4 5 6
3 4 5 6 7
4 5 6 7 8
if we instead populate this matrix with 'the remainder of the distance when dividing by 5' (the modulo 5, or %5) we get the matrix:
0 1 2 3 4
1 2 3 4 0
2 3 4 0 1
3 4 0 1 2
4 0 1 2 3
Now, if we add this 'modulo' result to the from value (1), we get our final matrix:
1 2 3 4 5
2 3 4 5 1
3 4 5 1 2
4 5 1 2 3
5 1 2 3 4
in a sense, all you need to know is that the value at each cell is:
the from value plus the remainder when you divide the 'distance' by the width.
Here's the code I tested with:
public static final String buildSquare(final int from, final int to) {
final StringBuilder sb = new StringBuilder(side * side);
final int side = to - from + 1;
for (int row = 0; row < side; row++) {
for(int col = 0; col < side; col++) {
sb.append( from + ((row + col) % side) );
}
sb.append("\n");
}
return sb.toString();
}
public static void main(String[] args) {
System.out.println(buildSquare(1, 5));
System.out.println(buildSquare(3, 9));
System.out.println(buildSquare(5, 5));
System.out.println(buildSquare(0, 9));
System.out.println(buildSquare(0, 3));
}
Since this is homework, I'll just give a hint.
I cannot for the life of me figure out how to make the numbers stop at the 'max' value and start over in the middle of the line.
Here's one way to do it.
Create the first number twice in an array. Taking the printSquare(1, 5) example, create an int array of 1, 2, 3, 4, 5, 1, 2, 3, 4, 5.
Use a loop to loop through the array, starting with element zero and ending with element 4, and another loop to display 5 digits (max - min + 1).
try this
int i,j,k;
for(i=min;i<=max;i++) {
for(j=i;j<=max;j++) {
System.out.print(j);
}
for(k=min;k<i;k++){
System.out.print(k);
}
System.out.println();
}
you can try
loop from min value to max value and put all the numbers in an array
now loop again from min value to max value
each time print the array and do a circular shift (for circular shift you can find lot of example in SO)
I think #rolfl's solution is the cleanest. I'd recommend going with that.
You can find another simple solution by observing that each output in your "square" simply shifts the first element to the end the list of numbers. To imitate this, you can put all the numbers from min to max in a data structure like LinkedList or ArrayDeque where you can easily add/remove items from both ends, then you'd print the contents in order, and shift the first entry to the end. E.g., coll.addLast(coll.removeFirst()). If you repeat that process max - min + 1 times, you should get the desired output.
no array no problem you can easily solve.
it work with any range of number.
static void printSquare(int min, int max){
int len = max - min + 1;
int copy_min = min, permanent_min = min;
for(int i = 0; i < len; i++){
for(int j = 0; j< len; j++){
if(min > max)
if(min % len < permanent_min)
System.out.print((min % len )+ len);
else
System.out.print(min % len);
else
System.out.print(min);
min++;
}
min = ++copy_min;
System.out.println();
}
}
public static void printSquare(int min, int max) {
for (int i = min; i <= (max -min)+min; i++) {
for( int j =i; j <= max ; j++) {
System.out.print(j);
}
for (int j1= min; j1<= i * 1 - 1; j1++) {
System.out.print(j1);
}
System.out.println();
}
}
The Java interview question is:
Without using a temporary buffer, separate the 0's and 1's from an array, placing all 0's to the left and 1's to the right. Print the result as a string. For example, given {0,1,1,0,0,1}, the output is "000111".
And an answer is:
public class ZeroOneSeparator {
public static void zeroOneSeparator(int[] inputArr){
// for each index, store number of 1's up to the index
for (int i = 1; i < inputArr.length; i++) {
inputArr[i] = inputArr[i-1] + inputArr[i];
}
// This is the "magical math" block I don't understand.
// Why does this "work"?
for (int i = inputArr.length - 1; i > 0; i--) {
if (inputArr[i] > 0) {
inputArr[i-1] = inputArr[i] - 1;
inputArr[i] = 1;
} else {
inputArr[i-1] = 0;
}
}
for (int i = 0; i < inputArr.length; i++) {
System.out.print(inputArr[i]);
}
}
public static void main(String[] args) {
int[] inputArr1 = {1,0,1,0,1,1};
ZeroOneSeparator.zeroOneSeparator(inputArr1);
System.out.println();
int[] inputArr2 = {1,1,1,0,0,0,0,0,0,1};
ZeroOneSeparator.zeroOneSeparator(inputArr2);
int[] inputArr3 = {}; // intentionally empty
System.out.println();
ZeroOneSeparator.zeroOneSeparator(inputArr3);
int[] inputArr4 = {0,0,0,0,0,0};
System.out.println();
ZeroOneSeparator.zeroOneSeparator(inputArr4);
int[] inputArr5 = {0,1,0,1,0,1,0,1};
System.out.println();
ZeroOneSeparator.zeroOneSeparator(inputArr5);
int[] inputArr6 = {1,1,1,1,1,1,0,0,0,0,0};
System.out.println();
ZeroOneSeparator.zeroOneSeparator(inputArr6);
}
}
I stepped through this code with a debugger, but I still don't understand why it works. Can someone please walk me through it?
Let's try an example to see what's going on. Suppose we had the following array:
0 1 1 0 1 1 0 0
The first loop (as the comment specifies) counts up the total number of 1's seen so far, where each 1 increases the count, and each 0 leaves it the same. So for our array, we end up with this:
0 1 2 2 3 4 4 4
Note that the final element of the array is now 4, which is the total number of 1s. We use that fact in the next loop.
We start at the last element, and check if it's greater than 0. If it is, then we replace that element with a 1, and then decrement that count by 1 and assign it to the previous element. We keep doing that, filling in 1s as we go, until the count reaches 0. At that point, we set each element we encounter to 0.
What's really happening here is that once we know how many 1s there are, we can "count down" from the end of the array, filling in that number of 1s. At that point, we know the rest of the elements must be 0, so we can set the rest of the elements to 0 at that point.
Visually, it looks like this (with the "current element" surrounded by []'s)
0 1 2 2 3 4 4 [4] ->
0 1 2 2 3 4 [3] 1 ->
0 1 2 2 3 [2] 1 1 ->
0 1 2 2 [1] 1 1 1 ->
0 1 2 [0] 1 1 1 1 ->
0 1 [0] 0 1 1 1 1 ->
0 [0] 0 0 1 1 1 1 ->
0 0 0 0 1 1 1 1
Note that the "countdown" seems very obvious when viewed this way.
Since you have the count of 1's in the array at the last index, you will just loop from the back and replace it with 1's. The trick that is done in the code is that, it reduces the count of 1's and store it in the previous array element in every step, so that in the next step, it knows whether the current element is 0 or 1. It works nicely even in the case of all 1's or almost all 1's (only one 0 in the array), since the count of 1's left when it modifies the element at index 0 is just the right number.
Personally, I would record the count of 1's, derive the count of 0's and use 2 loops to print out/set the numbers in the array.
First for loop counts how many 1s are there to the left of each item. If the input is {0,1,1,0,0,1}, as result of counting, the input array becomes {0,1,2,2,2,3}.
The last index 3 says that there are three 1s in the list. Second for loop walks the list in reverse and marks 1 for the last three items.