Sequence 1, 3, 8, 18, 38, 78 from a recursive function - recursion

I'm trying to write a recursive function in Java that would display the n element in a mathematical number sequence (1 3 8 18 38 78).
This is what I've managed to do so far:
public static int recfunc(int i) {
if(i==1) { return 1; }
if(i==2) { return 2+recfunc(i-1); }
if(i==3) { return 5+recfunc(i-1); }
if(i>3) { return ((2^(i-3))*5)+recfunc(3); }
return 0;
}
To calculate n(>3), you simply add together 2^(i-3) from each step(i>3) and then add 8 in the end. So, for the 6th element, you would have to do this calculation: 40 + 20 + 10 + 8 = 78.
The problem with the above code is that it successfully calculates the increase in a number between two n(s) and then ads 5 + 2 + 1 (8) to it, but it doesn't apply all the previous steps (20 + 10).
Update:
I'm getting somewhere, but it still doesn't do what it should.
public static int recfunc(int i, boolean param) {
if(param==false) {
if(i==1) { return 1; }
if(i==2) { return 2+recfunc(i-1, false); }
if(i==3) { return 5+recfunc(i-1, false); }
if(i>3) { param = true; }
}
if(param==true) {
if(i==4) {
return ((2^(i-3))*5)+recfunc(i-1, false); }
else {
return ((2^(i-3))*5)+recfunc(i-1, true); }
}
return 0;
}

The problem is with your power function. ^ in java does not mean to raise to a power. It means XOR.
You can use java's Math.pow()
int recfunc(int i) {
if(i==1) { return 1; }
if(i==2) { return 2+recfunc(i-1); }
if(i==3) { return 5+recfunc(i-1); }
if(i>3) {
return ((Math.pow(2,(i-3))*5)+recfunc(i-1));
}
return 0;
}
Hope this helps.

This code works fine now. Thanks for your help!
public static int recfunc(int i, boolean param) {
if(param==false) {
if(i==1) { return 1; }
if(i==2) { return 2+recfunc(i-1, false); }
if(i==3) { return 5+recfunc(i-1, false); }
if(i>3) { param = true; }
}
if(param==true) {
if(i==4) {
return (int)Math.pow(2.0f,(double)(i-3))*5+(int)(recfunc(i-1, false)); }
else {
return (int)Math.pow(2.0f,(double)(i-3))*5+(int)(recfunc(i-1, true)); }
}
return 0;
}

Related

Detect jailbroken bypass in Xamarin forms

My Xamarin based iOS application should not run in jailbroken devices. This is due to a IS audit. I have implemented the jailbroken detect mechanism. But I cannot find a way to detect whether someone using a jailbroken bypass method like for example A-bypass, shadow tweaks. Anyone with these tweaks can easily by pass the jailbroken detect code.
This is the class I used,
[assembly: Dependency(typeof(CheckHardware))]
namespace CustApp.iOS
{
public class CheckHardware : IHardwareSecurity
{
public CheckHardware()
{
}
public bool IsJailBreaked()
{
if (isPath() || canCreateFile() || isOpenLink())
{
return true;
}
else
{
return false;
}
}
private bool isPath()
{
bool res = false;
List<string> pathList = new List<string>
{
"/Applications/Cydia.app",
"/Applications/Checkra1n.app",
"/Applications/FakeCarrier.app",
"/Applications/Icy.app",
"/Applications/IntelliScreen.app",
"/Applications/MxTube.app",
"/Applications/RockApp.app",
"/Applications/SBSettings.app",
"/Applications/WinterBoard.app",
"/Applications/blackra1n.app",
"/Library/MobileSubstrate/DynamicLibraries/LiveClock.plist",
"/Library/MobileSubstrate/DynamicLibraries/Veency.plist",
"/Library/MobileSubstrate/MobileSubstrate.dylib",
"/System/Library/LaunchDaemons/com.ikey.bbot.plist",
"/System/Library/LaunchDaemons/com.saurik.Cydia.Startup.plist",
"/etc/apt",
"/private/var/lib/apt",
"/private/var/lib/apt/",
"/private/var/lib/cydia",
"/private/var/mobile/Library/SBSettings/Themes",
"/private/var/stash",
"/private/var/tmp/cydia.log",
"/usr/bin/sshd",
"/var/cache/apt",
"/var/lib/apt",
"/usr/libexec/sftp-server",
"/usr/sbin/sshd",
"/bin/bash",
"/Library/MobileSubstrate/MobileSubstrate.dylib",
"/var/lib/cydia"
};
foreach (var fullPath in pathList)
{
if (File.Exists(fullPath))
{
res = true;
}
}
return res;
}
private bool canCreateFile()
{
try
{
File.WriteAllText("/private/jailbreak.txt", "This is a test.");
return true;
}
catch (UnauthorizedAccessException)
{
return false;
}
}
private bool isOpenLink()
{
if (UIApplication.SharedApplication.CanOpenUrl(NSUrl.FromString("cydia://package/com.example.package")))
{
return true;
}
else
{
return false;
}
}
public bool IsInEmulator()
{
bool isSimulator = Runtime.Arch == Arch.SIMULATOR;
return isSimulator;
}
}
}

Recursive to Iterative method for Binary Search Tree

I'm working on an assignment to get the height of the BST using an iterative method from an recursive method. Below will be the provided recursive code and my code. It is returning one greater than the actual height. For example, the height is suppose to be 4, but it returns 5.
//Provided code
public int getHeight() {
return getHeight(root);
}
private int getHeight(Node node) {
if (node==null) {
return -1;
} else {
int leftHeight = getHeight(node.left);
int rightHeight = getHeight(node.right);
return Math.max(leftHeight, rightHeight) + 1;
}
}
//my code
public int getHeightI() {
return getHeightI(root);
}
private int getHeightI(Node node) {
Node curr = node;
int leftHeight = 0;
int rightHeight = 0;
if (curr!=null) {
while (curr.left!=null) {
leftHeight++;
curr = curr.left;
}
while (curr.right!=null) {
rightHeight++;
curr = curr.right;
}
}
return Math.max(leftHeight, rightHeight)+1;
}
Your Code is returning one more than actual height of Tree. I suggest you to use this code
int height(tree* root)
{
if(!root)
{ return -1;
}
else{
return __max(root->left,root->right);
}
Hope you understand your mistake.

Recursive method which return the sum of the numbers from 0 to int incrementing by 1

Having trouble with a recursive method, it should output the sum of the numbers that increment by 1 to get to whatever is entered in the commandline arguments (sorry if that's worded a little weird)
for example, if 10 is inputed into the args, then it should output 55
Here is my code, the Method in question is sumofNumbers
public class RecursionMethods {
public static void main(String[] commandlineArguments) {
if (commandlineArguments.length == 0) {
System.out.println("Please enter a least one commandline!");
}
else {
Integer number = new Integer(0); // initializes the number
try {
number = Integer.parseInt(commandlineArguments[0]);
} catch (NumberFormatException exception) { // NumberFormatException
System.out.println(exception + " is not a integer.");
System.exit(1); // ends the program
}
String asterisk = asterisks(number); // return address for asterisks
System.out.println(asterisk);
String reverse = reverses(number);
System.out.println(reverse);
String counting = count(number);
System.out.println(counting);
int sums = sumofNumbers(number);
System.out.println(sums);
}
}
public static String asterisks (Integer number) {
if (number == 0) {
return "";
} else {
return "*" + asterisks(number - 1);
}
}
public static String reverses (Integer number) {
if (number == 0) {
return "0";
}
return number + " " + reverses(number - 1);
}
public static String count (Integer number) {
if (number == 0) {
return "0";
}
return count(number - 1) + " " + number;
}
//here is where the recursion im having trouble with would go
public static int sumofNumbers (Integer number) {
if (number == 0) {
return 0;
}
return sum(
}

Regarding (count down) timer for application in asp.net c#

Hi
I have created online quiz. I have added Count-down timer,label for question & radiobuttonlist for answers and next button for next question. I have code for timer but this timer gets start again when i click next button as i want count down timer for whole questions(Quiz).
Count down timer code(Javascript) is as follows:
var hour=0; //specify hours for counter
var min= '<%= Session["timer"] %>'; // specify minutes
var second = '<%= Session["second"] %>'; // specify the seconds
var lab = 'cd'; // id of the entry on the page where the counter(for question) is to be inserted & cd is span id in aspx page where i am displaying countdown timer
function start()
{
displayCountdown(setCountdown(hour,min,second),lab);
}
loaded(lab,start);
var pageLoaded = 0;
window.onload = function() {pageLoaded = 1;}
function loaded(i,f)
{
if (document.getElementById && document.getElementById(i) != null)
f();
else if (!pageLoaded)
setTimeout('loaded(\''+i+'\','+f+')',100);
}
function setCountdown(hour,min,second)
{
if(hour>0)
min=min*hour*60;
c = setC(min,second);
return c;
}
function setC(min,second)
{
if(min>0)
second=min*60*second;
return Math.floor(second);
}
function displayCountdown(countdn,cd)
{
if (countdn < 0)
{
document.getElementById(cd).innerHTML = "Sorry, you are too late.";
__doPostBack('__Page');
}
else
{
var secs = countdn % 60;
if (secs < 10)
secs = '0'+secs;
var countdn1 = (countdn - secs) / 60;
var mins = countdn1 % 60;
if (mins < 10)
mins = '0'+mins;
countdn1 = (countdn1 - mins) / 60;
var hours = countdn1 % 24;
document.getElementById(cd).innerHTML = hours+' : '+mins+' : '+secs;
setTimeout('displayCountdown('+(countdn-1)+',\''+cd+'\');',999);
}
}
You must keep a reference on "present" time relatively of the "start" time and the duration of the quiz. So, you would substract "present" time from start time.
protected int HoursDuration {
get {
if (Session["HoursDuration"] == null) { Session["HoursDuration"] = 0; }
return Convert.ToInt32(Session["HoursDuration"]);
}
set { Session["HoursDuration"] = value; }
}
protected int MinutesDuration {
get {
if (Session["MinutesDuration"] == null) { Session["MinutesDuration"] = 0; }
return Convert.ToInt32(Session["MinutesDuration"]);
}
set { Session["MinutesDuration"] = value; }
}
protected int SecondsDuration {
get {
if (Session["SecondsDuration"] == null) { Session["SecondsDuration"] = 0; }
return Convert.ToInt32(Session["SecondsDuration"]);
}
set { Session["SecondsDuration"] = value; }
}
protected int HoursLeft {
get {
return (this.EndTime - this.BeginTime).Hours;
}
}
protected int MinutesLeft {
get {
return (this.EndTime - this.BeginTime).Minutes;
}
}
protected int SecondsLeft {
get {
return (this.EndTime - this.BeginTime).Seconds;
}
}
protected DateTime EndTime {
get {
if (Session["EndTime"] == null) { Session["EndTime"] = DateTime.Now; }
return Convert.ToDateTime(Session["EndTime"]);
}
set { ViewState["EndTime"] = value; }
}
protected DateTime BeginTime {
get {
if (Session["BeginTime"] == null) { Session["BeginTime"] = DateTime.Now; }
return Convert.ToDateTime(Session["BeginTime"]);
}
set { ViewState["BeginTime"] = value; }
}
protected override void OnInit(EventArgs e) {
this.BeginTime = DateTime.Now; // Present time
if (!IsPostBack) {
// The countdown
this.HoursDuration = 0;
this.MinutesDuration = 10;
this.SecondsDuration = 0;
// Only on !postback, you set up when it ends
this.EndTime = this.BeginTime.AddHours(this.HoursDuration)
.AddMinutes(this.MinutesDuration)
.AddSeconds(this.SecondsDuration);
}
base.OnInit(e);
}
Then, in you javascript, call the HoursLeft, MinutesLeft and secondeLeft. I think this should work.

It throws an stackoverflow exception when I user PropertyInfo.SetValue()

When I use PropertyInfo.SetValue in asp.net , it throws a stackoverflow exception.
That I write this code:
for (int i = 0; i < rivalSeriesIDList.Count; i++)
{
cardb_series rivalSeries = seriesBll.GetSeriesInfoByID(rivalSeriesIDList[i].ToString());
this.GetType().GetProperty("brandid" + (i + 1)).SetValue(this, rivalSeries.brand_id, null);
this.GetType().GetProperty("seriesid" + (i + 1)).SetValue(this, rivalSeries.series_id, null);
}
And brandid+number and seriesid+number is a property of aspx_page. like this:
public int brandid1
{
get
{
if (Request.Form["brandid1"] != null)
return int.Parse(Request.Form["brandid1"]);
if (Request["brandid1"] != null)
return int.Parse(Request["brandid1"]);
return 0;
}
set
{
brandid1 = value;
}
}
when I test the code in a Console Application ,It is all right . But when I test it in a Web Application ,it will cause a stack overflow exception .
I don't know why. Because of web is no-state?
Thanks.
cause you call your property recursively, and will get the same exception even if you will call the property directly
public int brandid1 <- this one
{
get
{
if (Request.Form["brandid1"] != null)
return int.Parse(Request.Form["brandid1"]);
if (Request["brandid1"] != null)
return int.Parse(Request["brandid1"]);
return 0;
}
set
{
and this one -> brandid1 = value;
}
}
I don't know what do you want to do, but try this
private int _brandid1;
public int brandid1 <- this one
{
get
{
if (Request.Form["brandid1"] != null)
return int.Parse(Request.Form["brandid1"]);
if (Request["brandid1"] != null)
return int.Parse(Request["brandid1"]);
return 0;
}
set
{
_brandid1 = value;
}
}

Resources