Translating a formula into recursion - formula

See picture here
Hello,
I need to convert the formula above to code (Java or C#)
I did a lot of tries without success.
Can anyone help?

Here's your answer in Java:
public static int f(int n) {
if(n == 0)
return 1;
int sum = 0;
for(int i = 0; i < n; i++)
sum += f(i) * f(n - 1 - i);
return sum;
}
Enjoy.

Below code is in php, in java or c# would have same logic
assuming f(x) return x+1, for n=3, sum would be 10
<?php
function fun($x)
{
echo $x+1;
return $x+1;
}
$n=3;
$sum=0;
if($n>0)
{
$i = $n-1;
while($i>=0)
{
$sum = $sum +(fun($i) * fun($n-1-$i));
$i= $i-1;
}
}
else if($n=0)
{
$sum = 1;
}
echo $sum;
?>

Related

SYCL kernel cannot call an undefined function without SYCL_EXTERNAL attribute

I am trying to calculate the euclidean distance for KNN but in parallel using dpc++. the training dataset contains 5 features and 1600 rows, while I want to calculate the distance between the current test point and each training point on the grid in parallel, but I keep getting an error regarding sycl kernal.
code for the function:
code
std::vector<double> distance_calculation_FPGA(queue& q,const std::vector<std::vector<double>>& dataset,const std::vector<double>& curr_test) {
range<1> num_items{ dataset.size()};
std::vector<double>res;
res.resize(dataset.size());
buffer dataset_buf(dataset);
buffer curr_test_buf(curr_test);
buffer res_buf(res.data(), num_items);
q.submit([&](handler& h) {
accessor a(dataset_buf, h, read_only);
accessor b(curr_test_buf, h, read_only);
accessor dif(res_buf, h, write_only, no_init);
h.parallel_for(num_items, [=](auto i) {
for (int j = 0; j <(const int) a[i].size(); ++j) {
dif[i] += (a[i][j] - b[j]) * (a[i][j] - b[j]) ;
}
});
});
for (int i = 0; i < res.size(); ++i) {
std::cout << res[i] << std::endl;
}
//old distance calculation (serial)
//for (int i = 0; i < dataset.size(); ++i) {
// double dis = 0;
// for (int j = 0; j < dataset[i].size(); ++j) {
// dis += (curr_test[j] - dataset[i][j]) * (curr_test[j] - dataset[i][j]);
//}
//res.push_back(dis);
//}
return res;
}
the error I am receiving:
SYCL kernel cannot call a variadic function
SYCL kernel cannot call an undefined function without SYCL_EXTERNAL attribute
Would be extremely grateful for any help!
Thanks
We tried running your code by creating dummy 'dataset' and 'curr_test' variables. We were able to run the program successfully. Please refer this thread
Please refer to the complete code attached below.
#include <CL/sycl.hpp>
#include <iostream>
using namespace sycl;
std::vector<double> distance_calculation_FPGA(queue& q,const std::vector<std::vector<double>>& dataset,const std::vector<double>& curr_test)
{
range<1> num_items{ dataset.size()};
std::vector<double>res;
res.resize(dataset.size());
buffer dataset_buf(dataset);
buffer curr_test_buf(curr_test);
buffer res_buf(res.data(), num_items);
q.submit([&](handler& h) {
accessor a(dataset_buf, h, read_only);
accessor b(curr_test_buf, h, read_only);
accessor dif(res_buf, h, write_only, no_init);
h.parallel_for(num_items, [=](auto i) {
for (int j = 0; j <(const int) a[i].size(); ++j) {
// dif[i] += (a[i][j] - b[j]) * (a[i][j] - b[j]) ;
dif[i]+=a[i][j];
}
});
});
q.wait(); //We have added this line of code for synchronization.
for (int i : res) {
std::cout <<i<< std::endl;
}
return res;
}
int main(){
std::vector<std::vector<double>> dataset;
for(int i=0;i<5;i++)
{
std::vector<double> d;
for(int j=0;j<1600;j++)
{
d.push_back((double)j);
}
dataset.push_back(d);
}
std::vector<double> curr_test;
for(int i=0;i<1600;i++)
{
curr_test.push_back((double)i);
}
queue q;
std::cout << "Running on "<<
q.get_device().get_info<sycl::info::device::name>()<< std::endl;
//print the device name as a test to check the parallelisation
distance_calculation_FPGA(q,dataset,curr_test);
return 0;
}

Sum using recursion

Apologies for the basic question, I'm new to java and have been stuck on this for days.
I need firstly to convert letters to numbers and then using recursion to get the sum of those numbers. I think I am close but I'm also aware it very messy
public static void main(String[] arg) {
String str= "11";
//////////////////////////
String s = "helloworld";
String t = "";
for (int i = 0; i < s.length(); ++i) {
char ch = s.charAt(i);
if (!t.isEmpty()) {
t += " ";
}
int n = (int)ch - (int)'a' + 1;
t += String.valueOf(n);
}
System.out.println(t);
//////////////////////////////
int sum=0;
int x=Integer.parseInt(t);
int y=recursion(x);
System.out.println("The Sum of the digits is: "+ y);
}
public static int recursion(int y) {
if(y/10>=1) {
int tempvar =y%10;
int remain=y/10;
return tempvar + recursion(remain);
}
else {
return y;
}
}}
Ok so first of all, this line: int x=Integer.parseInt(t); will crash the program in runtime because the string t has spaces in it. So you need to remove this:
if (!t.isEmpty()) {
t += " ";
}
Second, parsing the string t to int is a problem, because the number in string t can get like very, very large. Parsing this very..very large number to an int will also produce an exception during runtime. So a better way to do this is leaving it as a string, loop over it and just add the digits in it.
I have two solutions here:
I loop on t and add the digits.
I assume you have some constraint on the size of t so as it can be parsed to int (or long), and then use recursion as you want.
public class Main {
public static void main(String[] args) {
String s = "hew";
String t = "";
for (int i = 0; i < s.length(); ++i) {
char ch = s.charAt(i);
int n = (int)ch - (int)'a' + 1;
t += String.valueOf(n);
}
System.out.println("t: "+t);
System.out.println("sum using string: " + getSumUsingString(t));
System.out.println("sum using int: " + getSumUsingLong(Long.parseLong(t), 0));
}
// the string function
private static long getSumUsingString(String t) {
long sum = 0;
for (int i = 0; i < t.length(); i++) {
sum += t.charAt(i)-48;
}
return sum;
}
// recursive function
private static long getSumUsingLong(long num, long sum) {
if (num==0) return sum;
sum += num % 10;
return getSumUsingLong(num / 10, sum);
}
}
Note:
You can use for example, BigInteger class in Java to deal with very large numbers if you really need to parse this string t to a number.

Error Reading Characters of string - VC++

I got "Error Reading characters of string error" in runtime. And it is not handling with try catch,
void process(const BYTE* pBodyIndexBuffer){
m_pCoordinateMapper->MapCameraPointToDepthSpace(m_pJoints[JointType_ShoulderLeft].Position, &p);
dx = static_cast<int>(p.X + 0.5);
dy = static_cast<int>(p.Y + 0.5);
try
{
if (p.X < 500 && p.X >= 0 && p.Y <= 410 && p.Y >= 0)
{
pPoint = pBodyIndexBuffer[dx + (dy*cDepthWidth)];
while (1) {
if (pPoint == 0xff) break;
pPoint = pBodyIndexBuffer[dx + (dy * cDepthWidth)];
dx -= 1;
dy -= 1;
p.X -= 1;
p.Y -= 1;
OutputDebugString(L"Moved \n");
}
}
m_pBodyEdgeswidth[ShoulderLeft] = getDistance(m_pJoints[JointType_ShoulderLeft].Position, p, distance);
}
catch (const std::exception&)
{
OutputDebugString(L"Error Occured");
}
}
I provided the part of code.
Here is the issue I am facing,
Please explain how to resolve this issue.
But sometimes it starts running without error.
how I am passing is,
BYTE *bodyIndex = NULL;
cm->getBodyIndexStream(&bodyIndex);
if(bodyIndex) process(bodyIndex);
Thanks in advance .
You will need to pass a valid non-null buffer to getBodyIndexStream. You are passing null buffer, which satisfies compiler and will definitely fail at runtime. It is like:
int* ptr = NULL;
// Set value
*ptr = 120; // crash

heapify function recursing endlessly

The following is a recursive heapify function for an array based priority queue/binary heap.
Can anybody tell me why I'm going into an infinite recursion?
private static void heapify(int i){
if(i < b_heap.size()/2){
int left = i * 2;
int right = left++;
if(b_heap.get(i).getP() > b_heap.get(left).getP()){
swap(i,left);
}
if(b_heap.get(i).getP() > b_heap.get(right).getP()){
swap(i,right);
}
heapify(i++);
heapify(i+2);
}
else{
return;
}
}
ok so I fixed the infinite loop, but the function still doesn't heapify correctly.
here is the new code,
private static void heapify(int i){
DecimalFormat df = new DecimalFormat("0.00");
if(i < b_heap.size()/2){
int left = i * 2;
int right = i * 2 +1;
if(b_heap.get(i).getP() > b_heap.get(left).getP()){
swap(i,left);
}
if(b_heap.get(i).getP() > b_heap.get(right).getP()){
swap(i,right);
}
i++;
heapify(i);
}
else{
return;
}
}

How can you print 1 to 10 & 10 to 1 by using recursion with single variable [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I am preparing for my interview tomorrow -- I need the answer to this question:
How can you print 1 to 10 & 10 to 1 by using recursion with single variable
void print_recursive(int n) {
printf("%d\n", n);
if (n < 10)
print_recursive(n+1);
printf("%d\n", n);
}
With one function and one variable only:
void recurs(int num) {
printf("%d\n", num);
if (num < 10) {
recurs(num + 1);
}
printf("%d\n", num);
}
int main() {
recurs(1);
return 0;
}
I'm going to get downvoted I just know it but here is (a) solution. Not the best one but you should be able to make it better yourself.
class Program
{
static void Main(string[] args)
{
printNumDown(10);
}
static void printNumDown(int num)
{
Console.WriteLine(num.ToString());
if (num > 1)
printNumDown(num - 1);
else
printNumUp(num + 1);
}
static void printNumUp(int num)
{
Console.WriteLine(num.ToString());
if (num < 10)
printNumUp(num + 1);
}
}
You should be able to figure this out yourself.
Hint: Make a method that takes a 10 as a parameter, then prints the parameter and calls itself with 9.
Here's a sneaky way:
#include <stdio.h>
static void recur_up (int n) {
if (n > 1)
recur_up (n - 1);
printf ("%d\n", n);
}
static void recur_down (int n) {
printf ("%d\n", n);
if (n > 1)
recur_down (n - 1);
}
int main (void) {
recur_up (10);
recur_down (10);
return 0;
}
which generates:
1
2
3
4
5
6
7
8
9
10
10
9
8
7
6
5
4
3
2
1
It would have been a lot more elegant going down then up since you could do that with a single function:
static void recur_both (int n) {
printf ("%d\n", n);
if (n > 1)
recur_down (n - 1);
printf ("%d\n", n);
}
Javascript version:
printNumber(1);
function printNumber(num){
document.write(num);
if (num < 10)
printNumber(num + 1);
document.write(num);
}
Why are you guys all being so difficult? In Pseudocode:
function recurfunc(n) {
if (n < 10) {
echo (-1 * (floor(abs(n)) - 10));
recurfunc(n+1);
}
}
Then call recurfunc with -9.5 as its start.
Seems kind of obvious to me that the answer is using absolute value.
Here's one in Ruby:
puts (r = ->n=1 { if n<=10 then [n] + r.(n+1) + [n] else [] end }).()
Note: before you conclude that Ruby is an unreadable mess even worse than Perl, let me assure you: this is not idiomatic Ruby. Idiomatic Ruby would be more like
def recursive_count_up_and_down(n=1)
return [] unless n<=10
[n] +
recursive_count_up_and_down(n + 1) +
[n]
end
puts recursive_count_up_and_down
Of course, Ruby is an imperative language, so doing it really idiomatically would not use recursion:
1.upto(10) do |i| puts i end
10.downto(1) do |i| puts i end
Here's another neat one that unfortunately doesn't use recursion, either:
puts Array.new(20) {|i| if i < 10 then i+1 else 20-i end }
BTW: all the solutions so far, including mine, are actually cheating, because technically they use two variables, because
function foo {}
is equivalent to
var foo = λ{}
So, in my example above, there are two variables: recursive_count_up_and_down and n. We could eliminate both of those by writing in a tacit point-free style (for example in the SK-calculus), but I'll leave that as an exercise to the reader. (Meaning I can't figure it out :-) )
#include<stdio.h>
void c(int n)
{
static int i;
if(i<n)
{
i++;
printf("%d",i);
c(n);
}
}
int main()
{
c(5);
}
import java.util.Scanner;
public class PrintNumberFrom1To10{
public static void printNumber(int num){
if(num<=10){
System.out.println(num);
printNumber(num+1);
}
}
public static void main(String[] args) {
System.out.println("Enter Your Number: ");
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
printNumber(num);
}
}

Resources