Merging in merge sort algorithm - algorithm
I know the basic concept of the merge sort algorithm but when it comes to implementing it via recursion I am having trouble grasping how it works. From what I understand, the merge sort function splits our current array into two halves and using recursion we keep doing this until we are left with 1 element for each side.
If our array is {38, 27, 43, 3, 9, 82, 10} then our recursion will start by calling itself using the subarray (left side of the original array) and repeat the process each time, halving the array and storing the left most side until we reach 1 element:
38 27 43 3 9 82 10
38 27 43 3 <-split
<---first subroutine/recursion
38 27 <-split
<---second subroutine/recursion
38 <---only 1 element left so we return the value back to the first subroutine that called
Then in our second subroutine we move on to the next line: right = merge_sort(right) which again calls itself to split the subarray and storing the right most side:
38 27 <-split
<---second subroutine/recursion
27
<---only 1 element left so we return the value back to the first subroutine that called
Then in our second subroutine we move on to the next line: result = merge(left, right) which calls the merge function to sort our left and right arrays that are just 38 and 27. The merge function sorts our two values based on which is smaller and then it adds the first one to an array although I'm not sure which array. (I need specification on this; shouldn't we have a new array every time we merge two previous arrays?) Then the merge function returns the "result" to another result variable in our merge sort function from having called the merge function. I am assuming this result is the new array that has 38 and 27 sorted in order. Then it looks like we are returning that result again to whatever called the merge sort function but I am confused because wouldn't that end everything? What about the first subroutine that paused for the left side recursion? I'm not sure what happens to:
38 27 43 3
43 3
43
and
43 3
3
Pseudo-code:
function merge_sort(m)
if length(m) ≤ 1
return m
var list left, right, result
var integer middle = length(m) / 2
for each x in m up to middle
add x to left
for each x in m after middle
add x to right
left = merge_sort(left)
right = merge_sort(right)
result = merge(left, right)
return result
Following writing merge_sort function, then it is required to merge both the left and right lists created above. There are several variants for the merge() function; one possibility is this:
function merge(left,right)
var list result
while length(left) > 0 or length(right) > 0
if length(left) > 0 and length(right) > 0
if first(left) ≤ first(right)
append first(left) to result
left = rest(left)
else
append first(right) to result
right = rest(right)
else if length(left) > 0
append first(left) to result
left = rest(left)
else if length(right) > 0
append first(right) to result
right = rest(right)
end while
return result
http://www.princeton.edu/~achaney/tmve/wiki100k/docs/Merge_sort.html
I'm not sure whether it is what you're looking for, but you can simplify your merge loop by replacing or with and in the main condition:
while length(left) > 0 and length(right) > 0
if first(left) ≤ first(right)
append first(left) to result
left = rest(left)
else
append first(right) to result
right = rest(right)
end while
# You know that one of left and right is empty
# Copy the rest of the data from the other
while length(left) > 0
append first(left) to result
left = rest(left)
end while
while length(right) > 0
append first(right) to result
right = rest(right)
end while
Yes, there are three loops, but only one of the last two is ever executed.
Working C99 code based closely on pseudo-code
Thus code uses C99 variable-length arrays (an optional feature in C11). If compiled with -DDEBUG, you'll get extensive tracing while the program is running. If compiled without, you only get the input (unsorted) and output (sorted) arrays printed. I needed it to diagnose a stupid typo (an r_pos where an l_pos was clearly required). Note the general techniques:
Document entry and exit from functions
Create a diagnostic print function (here dump_array() with one argument a 'tag' (to identify which call is being used) and the other arguments the data structure to be printed.
Call the diagnostic print function at suitable points.
Make it easy to enable or disable diagnostics.
For production quality code, my diagnostic print functions also take a FILE *fp argument and write to the given file; I cheated and used stdout here. The extra generality means the function can be used to write to stderr or a log file as well as, or instead of, stdout.
Space management
The merge_sort() code copies the complete input array into two smaller arrays (left and right) and then sorts the smaller arrays (recursion) and merges the sorted smaller arrays into the input array. This happens at each of log N levels of recursion. Some empirical testing shows that the space used is approximately 2N items — it is O(N) space usage.
Shouldn't we have a new array every time we merge two previous arrays?
In a functional programming language, you would have new arrays. In C, you use the input array as the output array too. The code copies the original input array into separate smaller arrays, sorts those smaller arrays, and merges the sorted smaller arrays into the original array.
My other question is what procedure in the code allows us to go back to before the recursion where we split the left side of our array so we can work on the right side to get 43 a 3 in order to merge them as well.
The splitting process creates a copy of the input array (so the information in the original data is temporarily superfluous). The merging process copies the (now sorted) split arrays back into the original array. (Largely repeating myself.)
Source
#include <stddef.h>
extern void merge_sort(int *array, size_t arrlen);
/* Debug */
#ifdef DEBUG
static void dump_array(const char *tag, int *array, size_t len);
static void enter_func(const char *func);
static void exit_func(const char *func);
#else
#define dump_array(t, a, l) ((void)0)
#define enter_func(f) ((void)0)
#define exit_func(f) ((void)0)
#endif
/*
function merge(left, right)
var list result
while length(left) > 0 and length(right) > 0
if first(left) ≤ first(right)
append first(left) to result
left = rest(left)
else
append first(right) to result
right = rest(right)
end while
# You know that one of left and right is empty
# Copy the rest of the data from the other
while length(left) > 0
append first(left) to result
left = rest(left)
end while
while length(right) > 0
append first(right) to result
right = rest(right)
end while
return result
end function
*/
static void merge(int *left, size_t l_len, int *right, size_t r_len, int *output)
{
size_t r_pos = 0;
size_t l_pos = 0;
size_t o_pos = 0;
enter_func(__func__);
dump_array("Left:", left, l_len);
dump_array("Right:", right, r_len);
while (r_pos < r_len && l_pos < l_len)
{
if (right[r_pos] < left[l_pos])
output[o_pos++] = right[r_pos++];
else
output[o_pos++] = left[l_pos++];
}
while (r_pos < r_len)
output[o_pos++] = right[r_pos++];
while (l_pos < l_len)
output[o_pos++] = left[l_pos++];
dump_array("Output:", output, r_len + l_len);
exit_func(__func__);
}
/*
function merge_sort(m)
if length(m) ≤ 1
return m
var list left, right, result
var integer middle = length(m) / 2
for each x in m up to middle
add x to left
for each x in m after middle
add x to right
left = merge_sort(left)
right = merge_sort(right)
result = merge(left, right)
return result
*/
void merge_sort(int *array, size_t len)
{
if (len <= 1)
return;
int left[(len+1)/2];
int l_pos = 0;
int right[(len+1)/2];
int r_pos = 0;
size_t mid = len / 2;
enter_func(__func__);
dump_array("Input:", array, len);
for (size_t i = 0; i < mid; i++)
left[l_pos++] = array[i];
for (size_t i = mid; i < len; i++)
right[r_pos++] = array[i];
dump_array("Left:", left, l_pos);
dump_array("Right:", right, r_pos);
merge_sort(left, l_pos);
merge_sort(right, r_pos);
merge(left, l_pos, right, r_pos, array);
dump_array("Result:", array, len);
exit_func(__func__);
}
/* Test code */
#include <stdio.h>
#ifdef DEBUG
static void enter_func(const char *func)
{
printf("-->> %s\n", func);
}
static void exit_func(const char *func)
{
printf("<<-- %s\n", func);
}
#endif
/* dump_array is always used */
#undef dump_array
static void dump_array(const char *tag, int *array, size_t len)
{
printf("%-8s", tag);
for (size_t i = 0; i < len; i++)
printf(" %2d", array[i]);
putchar('\n');
}
int main(void)
{
int array[] = { 38, 27, 43, 3, 9, 82, 10 };
size_t arrlen = sizeof(array) / sizeof(array[0]);
dump_array("Before:", array, arrlen);
merge_sort(array, arrlen);
dump_array("After:", array, arrlen);
return 0;
}
Sample outputs
Non-debugging
Before: 38 27 43 3 9 82 10
After: 3 9 10 27 38 43 82
Debugging
Before: 38 27 43 3 9 82 10
-->> merge_sort
Input: 38 27 43 3 9 82 10
Left: 38 27 43
Right: 3 9 82 10
-->> merge_sort
Input: 38 27 43
Left: 38
Right: 27 43
-->> merge_sort
Input: 27 43
Left: 27
Right: 43
-->> merge
Left: 27
Right: 43
Output: 27 43
<<-- merge
Result: 27 43
<<-- merge_sort
-->> merge
Left: 38
Right: 27 43
Output: 27 38 43
<<-- merge
Result: 27 38 43
<<-- merge_sort
-->> merge_sort
Input: 3 9 82 10
Left: 3 9
Right: 82 10
-->> merge_sort
Input: 3 9
Left: 3
Right: 9
-->> merge
Left: 3
Right: 9
Output: 3 9
<<-- merge
Result: 3 9
<<-- merge_sort
-->> merge_sort
Input: 82 10
Left: 82
Right: 10
-->> merge
Left: 82
Right: 10
Output: 10 82
<<-- merge
Result: 10 82
<<-- merge_sort
-->> merge
Left: 3 9
Right: 10 82
Output: 3 9 10 82
<<-- merge
Result: 3 9 10 82
<<-- merge_sort
-->> merge
Left: 27 38 43
Right: 3 9 10 82
Output: 3 9 10 27 38 43 82
<<-- merge
Result: 3 9 10 27 38 43 82
<<-- merge_sort
After: 3 9 10 27 38 43 82
Related
How do you find which row and column a number belongs to in Floyd Triangle
How do you find which row and column does a number belongs to in Floyd Triangle? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 For example, 33 is in the 8th row and 5th column (input 33 → output 8th row, 5th column) 46 is in the 10th row and 1st column 27 is in the 7th row and 6th column Thank you so much in advance!
Note that n-th row ends with value n*(n+1)/2. So you can make quadratic equation and solve it to get row number for given number k n*(n+1)/2 = k n^2 + n - 2*k = 0 D = 1 + 8*k n_row = Ceil((-1 + Sqrt(D)) / 2) //round float value up For example, for k=33 you can calculate n_row = Ceil((-1 + Sqrt(265)) / 2) = Ceil(7.639) = 8 Having n_row, find the last number of previous row and position of k in the current row n_Column = 33 - n_row * (n_row - 1) / 2 = 33 - 28 = 5 Pseudocode for alternative method of row finding: sum = 0 row = 0 while sum < k do row++ sum = sum + row
I think that this approach is somehow more natural: #include <iostream> size_t getRow(size_t n) { // just count the rows, and when you meet the number, return the row size_t row(0), k(1); for (row = 1; row <= n; row++) { for (size_t j = 1; j <= row; j++) { if (k == n) { goto end; } k++; } } end:return row; } size_t getCol(size_t n) { /* well, we have already found the row, so now knowing that every n-th row starts with n(n-1)/2+1 and ends with n(n+1)/2, just count the columns and when you meet the number (and that surely will happen), just return the column and you're done*/ size_t col(1); size_t r = getRow(n); for (size_t j = r * (r - 1) / 2+1; j <= r*(r+1)/2; j++) { if (j == n) { break; } col++; } return col; } int main() { size_t n; std::cin >> n; std::cout << "Number " << n << " lies in row " << getRow(n) << ", column " << getCol(n) << " of the Floyd's triangle.\n"; return 0; }
In python this looks like this (if you don't want to use sqrt): def rc(n): # rc(1) = (1, 1); rc(33) -> (8, 5) assert n > 0 and int(n) == n sum = 0 row = 0 while sum < n: row += 1 sum += row col = n - sum + row return row, col
How do I make this program work for input >10 for the USACO Training Pages Square Palindromes?
Problem Statement - Given a number base B (2 <= B <= 20 base 10), print all the integers N (1 <= N <= 300 base 10) such that the square of N is palindromic when expressed in base B; also print the value of that palindromic square. Use the letters 'A', 'B', and so on to represent the digits 10, 11, and so on. Print both the number and its square in base B. INPUT FORMAT A single line with B, the base (specified in base 10). SAMPLE INPUT 10 OUTPUT FORMAT Lines with two integers represented in base B. The first integer is the number whose square is palindromic; the second integer is the square itself. NOTE WELL THAT BOTH INTEGERS ARE IN BASE B! SAMPLE OUTPUT 1 1 2 4 3 9 11 121 22 484 26 676 101 10201 111 12321 121 14641 202 40804 212 44944 264 69696 My code works for all inputs <=10, however, gives me some weird output for inputs >10. My Code- #include<iostream> #include<cstdio> #include<cmath> using namespace std; int baseToBase(int num, int base) //accepts a number in base 10 and the base to be converted into as arguments { int result=0, temp=0, i=1; while(num>0) { result = result + (num%base)*pow(10, i); i++; num = num/base; } result/=10; return result; } long long int isPalin(int n, int base) //checks the palindrome { long long int result=0, temp, num=n*n, x=n*n; num = baseToBase(num, base); x = baseToBase(x, base); while(num) { temp=num%10; result = result*10 + temp; num/=10; } if(x==result) return x; else return 0; } int main() { int base, i, temp; long long int sq; cin >> base; for(i=1; i<=300; i++) { temp=baseToBase(i, base); sq=isPalin(i, base); if(sq!=0) cout << temp << " " << sq << endl; } return 0; } For input = 11, the answer should be 1 1 2 4 3 9 6 33 11 121 22 484 24 565 66 3993 77 5335 101 10201 111 12321 121 14641 202 40804 212 44944 234 53535 While my answer is 1 1 2 4 3 9 6 33 11 121 22 484 24 565 66 3993 77 5335 110 10901 101 10201 111 12321 121 14641 209 40304 202 40804 212 44944 227 50205 234 53535 There is a difference in my output and the required one as 202 shows under 209 and 110 shows up before 101. Help appreciated, thanks!
a simple example for B = 11 to show error in your base conversion is for i = 10 temp should be A but your code calculates temp = 10. Cause in we have only 10 symbols 0-9 to perfectly show every number in base 10 or lower but for bases greater than that you have to use other symbols to represent a different digit like 'A', 'B' and so on. problem description clearly states that. Hope You will be able to fix your code now by modifying your int baseToBase(int num, int base)function.
Need to find the next greater element of every element in an array [duplicate]
This question already has answers here: Given an array, find out the next smaller element for each element (13 answers) Closed 8 years ago. Description of Algorithm For each element in the input array, the corresponding output is the first number that follows the input element, that is greater than the input element. In other words, for a given input[i], the output[i] is some element input[j] where j is the minimum index such that j > i and input[j] > input[i] Example Input 12 15 22 9 7 2 18 23 27 Output 15 22 23 18 18 18 23 27 -1 For example, the output that corresponds to 9 is 18 since 18 is the first number in the array that meets these requirements follows 9 in the input array is greater than 9 Question Can anyone suggest me an algorithm better than O(n^2)?
This can be done in O(N) time and O(N) extra memory space with the help of two stacks (one for indices and other for values). I'll explain the algorithm with the help of your example. Input 12 15 22 9 7 2 18 23 27 Initialize Output Array O[] as all -1. 1. Start from the first element. Set CurrentElement = A[0] (12). index = 0 2. Push A[index] in a Stack S_values. Push index in a Stack S_indices. 3. Increment index. 4. while ( S_values is not empty && A[index] is > than S_values.top() ) - Set output_index = S_indices.top() - set O[output_index] = A[index]. - S_values.pop() - S_indices.pop(). 5. If index < length(Input)-1 Goto Step 2. 6. Set O[index] = -1. // Last element. This works because the top of the stack S_values shall always have the lowest value and the elements shall be popped out from it in ascending order. Similarly the stack S_indices shall always have the largest value on top and indices shall be popped out in descending order. EDIT: Code in C++ #include <vector> #include <stack> #include <iostream> using std::cout; using std::endl; using std::vector; using std::stack; int main() { vector<int> Input = { 12, 15, 22, 9, 7, 2, 18, 23, 27}; vector<int> Output( Input.size(), -1 ); stack<int> S_values, S_indices; S_values.push( Input[0] ); S_indices.push( 0 ); for ( size_t index = 1; index < Input.size(); ++index ) { while ( !S_values.empty() && Input[index] > S_values.top() ) { size_t output_index = S_indices.top(); Output[ output_index ] = Input[ index ]; S_values.pop(); S_indices.pop(); } S_values.push( Input[index] ); S_indices.push( index ); } for ( auto &x : Output ) cout << x << " "; cout << endl; return 0; } Output: 15 22 23 18 18 18 23 27 -1
One approach is to use a stack, where each entry in the stack is a value:index pair. Iterate through the input array, popping items from the stack whose value is less than the value of the current item in the input array. Once all of the smaller values have been popped from the stack, push the current value:index pair onto the stack. When the end of the input array is reached, any remaining entries in the stack get an output value of -1 to indicate that no larger number was found. Using the example in the question, here's how the algorithm would work input item 12 stack = 12:0 input item 15 pop 12:0 and set output[0] = 15 stack = 15:1 input item 22 pop 15:1 and set output[1] = 22 stack = 22:2 input item 9 stack = 9:3, 22:2 input item 7 stack = 7:4, 9:3, 22:2 input item 2 stack = 2:5, 7:4, 9:3, 22:2 input item 18 pop 2:5 and set output[5] = 18 pop 7:4 and set output[4] = 18 pop 9:3 and set output[3] = 18 stack = 18:6, 22:2 input item 23 pop 18:6 and set output[6] = 23 pop 22:2 and set output[2] = 23 stack = 23:7 input item 27 pop 23:7 set output[7]= 27 stack = 27:8 end of array pop 27:8 and set output[8] = -1 done
displayng number pyramid in O(n) execution
How do we print the following with O(n) execution may be using a single for loop? 1 2 3 4 5 n up to n rows all I can do is using nested for loops
Nested for loop doesn't necessarily mean it's not O(n) any more. If what's inside the nested loop gets executed O(n) times, then the nested loop is perfectly fine: cur_num <- 1 cur_step <- 1 while cur_num <= n for i <- 1 to cur_step print cur_num++ cur_step++ print '\n' With a single for loop, it's doable, but slightly less pleasant cur_num <- 1 cur_step <- 1 cur_step_consumed <- 0 for i <- 1 to n print cur_num++ cur_step_consumed++ if cur_step_consumed == cur_step cur_step_consumed <- 0 cur_step++ print '\n'
In C++: size_t amount = 1; size_t count = 0; for(size_t i=1;i<=n;++i){ cout << i << " "; ++count; if (count == amount){ cout << endl; count = 0; ++amount; } } output for n = 29: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 The idea is to track the number of elements to print in the current row, and track the number of elements printed in the current row. When the number of elements we've printed for the current row is the same as the total number of elements to print for that row, reset the count and increment the number of elements to print for the next row. You can mess with the formatting to get prettier output, but this is the gist of how it can be done in O(n) time and O(1) space.
How to efficiently calculate a row in pascal's triangle?
I'm interested in finding the nth row of pascal triangle (not a specific element but the whole row itself). What would be the most efficient way to do it? I thought about the conventional way to construct the triangle by summing up the corresponding elements in the row above which would take: 1 + 2 + .. + n = O(n^2) Another way could be using the combination formula of a specific element: c(n, k) = n! / (k!(n-k)!) for each element in the row which I guess would take more time the the former method depending on the way to calculate the combination. Any ideas?
>>> def pascal(n): ... line = [1] ... for k in range(n): ... line.append(line[k] * (n-k) / (k+1)) ... return line ... >>> pascal(9) [1, 9, 36, 84, 126, 126, 84, 36, 9, 1] This uses the following identity: C(n,k+1) = C(n,k) * (n-k) / (k+1) So you can start with C(n,0) = 1 and then calculate the rest of the line using this identity, each time multiplying the previous element by (n-k) / (k+1).
A single row can be calculated as follows: First compute 1. -> N choose 0 Then N/1 -> N choose 1 Then N*(N-1)/1*2 -> N choose 2 Then N*(N-1)*(N-2)/1*2*3 -> N choose 3 ..... Notice that you can compute the next value from the previous value, by just multipyling by a single number and then dividing by another number. This can be done in a single loop. Sample python. def comb_row(n): r = 0 num = n cur = 1 yield cur while r <= n: r += 1 cur = (cur* num)/r yield cur num -= 1
The most efficient approach would be: std::vector<int> pascal_row(int n){ std::vector<int> row(n+1); row[0] = 1; //First element is always 1 for(int i=1; i<n/2+1; i++){ //Progress up, until reaching the middle value row[i] = row[i-1] * (n-i+1)/i; } for(int i=n/2+1; i<=n; i++){ //Copy the inverse of the first part row[i] = row[n-i]; } return row; }
here is a fast example implemented in go-lang that calculates from the outer edges of a row and works it's way to the middle assigning two values with a single calculation... package main import "fmt" func calcRow(n int) []int { // row always has n + 1 elements row := make( []int, n + 1, n + 1 ) // set the edges row[0], row[n] = 1, 1 // calculate values for the next n-1 columns for i := 0; i < int(n / 2) ; i++ { x := row[ i ] * (n - i) / (i + 1) row[ i + 1 ], row[ n - 1 - i ] = x, x } return row } func main() { for n := 0; n < 20; n++ { fmt.Printf("n = %d, row = %v\n", n, calcRow( n )) } } the output for 20 iterations takes about 1/4 millisecond to run... n = 0, row = [1] n = 1, row = [1 1] n = 2, row = [1 2 1] n = 3, row = [1 3 3 1] n = 4, row = [1 4 6 4 1] n = 5, row = [1 5 10 10 5 1] n = 6, row = [1 6 15 20 15 6 1] n = 7, row = [1 7 21 35 35 21 7 1] n = 8, row = [1 8 28 56 70 56 28 8 1] n = 9, row = [1 9 36 84 126 126 84 36 9 1] n = 10, row = [1 10 45 120 210 252 210 120 45 10 1] n = 11, row = [1 11 55 165 330 462 462 330 165 55 11 1] n = 12, row = [1 12 66 220 495 792 924 792 495 220 66 12 1] n = 13, row = [1 13 78 286 715 1287 1716 1716 1287 715 286 78 13 1] n = 14, row = [1 14 91 364 1001 2002 3003 3432 3003 2002 1001 364 91 14 1] n = 15, row = [1 15 105 455 1365 3003 5005 6435 6435 5005 3003 1365 455 105 15 1] n = 16, row = [1 16 120 560 1820 4368 8008 11440 12870 11440 8008 4368 1820 560 120 16 1] n = 17, row = [1 17 136 680 2380 6188 12376 19448 24310 24310 19448 12376 6188 2380 680 136 17 1] n = 18, row = [1 18 153 816 3060 8568 18564 31824 43758 48620 43758 31824 18564 8568 3060 816 153 18 1] n = 19, row = [1 19 171 969 3876 11628 27132 50388 75582 92378 92378 75582 50388 27132 11628 3876 969 171 19 1]
An easy way to calculate it is by noticing that the element of the next row can be calculated as a sum of two consecutive elements in the previous row. [1, 5, 10, 10, 5, 1] [1, 6, 15, 20, 15, 6, 1] For example 6 = 5 + 1, 15 = 5 + 10, 1 = 1 + 0 and 20 = 10 + 10. This gives a simple algorithm to calculate the next row from the previous one. def pascal(n): row = [1] for x in xrange(n): row = [l + r for l, r in zip(row + [0], [0] + row)] # print row return row print pascal(10)
In Scala Programming: i would have done it as simple as this: def pascal(c: Int, r: Int): Int = c match { case 0 => 1 case `c` if c >= r => 1 case _ => pascal(c-1, r-1)+pascal(c, r-1) } I would call it inside this: for (row <- 0 to 10) { for (col <- 0 to row) print(pascal(col, row) + " ") println() } resulting to: . 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1 1 6 15 20 15 6 1 1 7 21 35 35 21 7 1 1 8 28 56 70 56 28 8 1 1 9 36 84 126 126 84 36 9 1 1 10 45 120 210 252 210 120 45 10 1 To explain step by step: Step 1: We make sure that if our column is the first one we always return figure 1. Step 2: Since each X-th row there are X number of columns. So we say that; the last column X is greater than or equal to X-th row, then the return figure 1. Step 3: Otherwise, we get the sum of the repeated pascal of the column just before the current one and the row just before the current one ; and the pascal of that column and the row just before the current one. Good Luck.
Let me build upon Shane's excellent work for an R solution. (Thank you, Shane!. His code for generating the triangle: pascalTriangle <- function(h) { lapply(0:h, function(i) choose(i, 0:i)) } This will allow one to store the triangle as a list. We can then index whatever row desired. But please add 1 when indexing! For example, I'll grab the bottom row: pt_with_24_rows <- pascalTriangle(24) row_24 <- pt_with_24_rows[25] # add one row_24[[1]] # prints the row So, finally, make-believe I have a Galton Board problem. I have the arbitrary challenge of finding out percentage of beans have clustered in the center: say, bins 10 to 15 (out of 25). sum(row_24[[1]][10:15])/sum(row_24[[1]]) Which turns out to be 0.7704771. All good!
In Ruby, the following code will print out the specific row of Pascals Triangle that you want: def row(n) pascal = [1] if n < 1 p pascal return pascal else n.times do |num| nextNum = ((n - num)/(num.to_f + 1)) * pascal[num] pascal << nextNum.to_i end end p pascal end Where calling row(0) returns [1] and row(5) returns [1, 5, 10, 10, 5, 1]
Here is the another best and simple way to design a Pascal Triangle dynamically using VBA. `1 11 121 1331 14641` `Sub pascal() Dim book As Excel.Workbook Dim sht As Worksheet Set book = ThisWorkbook Set sht = book.Worksheets("sheet1") a = InputBox("Enter the Number", "Fill") For i = 1 To a For k = 1 To i If i >= 2 And k >= 2 Then sht.Cells(i, k).Value = sht.Cells(i - 1, k - 1) + sht.Cell(i- 1, k) Else sht.Cells(i, k).Value = 1 End If Next k Next i End Sub`
I used Ti-84 Plus CE The use of –> in line 6 is the store value button Forloop syntax is :For(variable, beginning, end [, increment]) :Commands :End nCr syntax is :valueA nCr valueB List indexes start at 1 so that's why i set it to R+1 N= row R= column PROGRAM: PASCAL :ClrHome :ClrList L1 :Disp "ROW :Input N :For(R,0,N,1) :N nCr R–>L1(R+1) :End :Disp L1 This is the fastest way I can think of to do this in programming (with a ti 84) but if you mean to be able to calculate the row using pen and paper then just draw out the triangle cause doing factorals are a pain!
Here's an O(n) space-complexity solution in Python: def generate_pascal_nth_row(n): result=[1]*n for i in range(n): previous_res = result.copy() for j in range(1,i): result[j] = previous_res[j-1] + previous_res[j] return result print(generate_pascal_nth_row(6))
class Solution{ public: int comb(int n,int r){ long long c=1; for(int i=1;i<=r;i++) { //calculates n!/(n-r)! c=((c*n))/i; n--; } return c; } vector<int> getRow(int n) { vector<int> v; for (int i = 0; i < n; ++i) v.push_back(comb(n,i)); return v; } }; faster than 100% submissions on leet code https://leetcode.com/submissions/detail/406399031/
The most efficient way to calculate a row in pascal's triangle is through convolution. First we chose the second row (1,1) to be a kernel and then in order to get the next row we only need to convolve curent row with the kernel. So convolution of the kernel with second row gives third row [1 1]*[1 1] = [1 2 1], convolution with the third row gives fourth [1 2 1]*[1 1] = [1 3 3 1] and so on This is a function in julia-lang (very simular to matlab): function binomRow(n::Int64) baseVector = [1] #the first row is equal to 1. kernel = [1,1] #This is the second row and a kernel. row = zeros(n) for i = 1 : n row = baseVector baseVector = conv(baseVector, kernel) #convoltion with kernel end return row::Array{Int64,1} end
To find nth row - int res[] = new int[n+1]; res[0] = 1; for(int i = 1; i <= n; i++) for(int j = i; j > 0; j++) res[j] += res[j-1];