Non Stop Loop in Divide and Conquer Algorithm - r

I am doing 'find majority element' using R. And when the function me is running, it would not stop and got "Error: C stack usage 7971200 is too close to the limit"
I have checked single majority element comparison and it works.
So which step i went wrong?
library(Dict)
maj.com <- function(a,b) {
if (is.null(a)&& is.null(b)) {
return(NULL)
}
if (!(is.null(a)) && is.null(b)) {
return(a)
}
if (is.null(a) && !(is.null(b)) ){
return(b)
}
if (unlist(a[1]) == unlist(b[1])) {
a[2] = as.integer(a[2])+ as.integer(b[2])
return(a)
}
if (unlist(a[1]) != unlist(b[1]) && as.integer(a[2]) > as.integer(b[2])) {
a[2] = as.integer(a[2]) - as.integer(a[2])
return(a)
}
if (unlist(a[1]) != unlist(b[1]) && as.integer(a[2]) < as.integer(b[2])) {
b[2] = as.integer( b[2] )- as.integer(a[2])
return(b)
}
if (unlist(a[1]) != unlist(b[1]) && as.integer(a[2]) == as.integer(b[2])) {
return(NULL)
}
}
mydict <- function(key,value) {
return(list(key,value))
}
me <- function(arr) {
n = length(arr)
m = round(n/2)
if (n>1) {
return(maj.com(me(arr[1:m]),me(arr[m+1:n])))
}
else {
print(arr)
return(mydict(arr,1))
}
}

Related

R user-defined function called but not running

I am new to R, and I am trying to create a user-defined function and run it inside a for loop. The function is defined in the same script before it is called. However, when the function is called, the code inside the function doesn't run. No syntax errors occur.
Here is the function definition:
placeInVector <- function(subjectID, morpho) {
if (morpho == "Alg") {
algVec <- c(algVec, subjectID)
}
else if (morpho == "Anem") {
anemVec <- c(anemVec, subjectID)
}
else if (morpho == "Barn") {
barnVec <- c(barnVec, subjectID)
}
else if (morpho == "Biv") {
bivVec <- c(bivVec, subjectID)
}
else if (morpho == "BrBryo") {
brbryoVec <- c(brbryoVec, subjectID)
}
else if (morpho == "ColTuni") {
coltuniVec <- c(coltuniVec, subjectID)
}
else if (morpho == "EnBryo") {
enbryoVec <- c(enbryoVec, subjectID)
}
else if (morpho == "Nothing") {
nothingVec <- c(nothingVec, subjectID)
}
else if (morpho == "SolTuni") {
soltuniVec <- c(soltuniVec, subjectID)
}
else if (morpho == "Spng") {
spngVec <- c(spngVec, subjectID)
}
else if (morpho == "TubeWm") {
tubewmVec <- c(tubewmVec, subjectID)
}
}
Here is where the function is called later on in the script:
for (subject in subjects$SubjectID) {
currentRow <- finalIDs %>%
filter(SubjectID == subject)
morphoID <- as.character(currentRow$FinalIDs1)
if (morphoID != "NONE") {
placeInVector(subject, morphoID)
}
}
Note: all of the vectors referenced in the function definition (algVec, anemVec, etc.) are defined as empty vectors.
As far as I understand, you are trying to add elements to vectors. Because I don't have a reproducible example, I will use my own. Here, add_to_vector adds elements to a and b:
a <- c(1,2)
b <- c("a","b")
add_to_vector <- function(vec, to_add){
vec <- c(vec, to_add)
return(vec)
}
a <- add_to_vector(a, 3)
b <- add_to_vector(b, "c")
Hopefully, this gives you an idea of how R works.
Output
> a
[1] 1 2 3
> b
[1] "a" "b" "c"

Loop returns error: 'argument is of length zero'

i <- 2
j <- 0
for (i in 2:1000) {
if(return.prime(i)){j = j + 1}
i = i + 1
}
I want to check how many prime numbers there are in 1 to 1000 using my own function return.prime which returns TRUE when the number input is a prime and FALSE when the number input is not prime. The return.prime function is the function below and it is correct.
return.prime <- function(d){
if(d ==1 ){print(FALSE)}
if (d == 2){
print(TRUE)
}
if(d !=2 && d!=1){
if(any(d %% (2:(d-1)) == rep(0,d-2))==TRUE){
print(FALSE)}
else
print(TRUE)
}
}
The problem is when I run my program it says:
[1] TRUE
Error in if (return.prime(i)) { : argument is of length zero
I do not know what causes the length zero.
R doesn't work that way. You're just having the function print the word "TRUE" or "FALSE". Instead, you need to ?return TRUE or FALSE. Consider:
return.prime <- function(d){
if(d==1){ return(FALSE) }
if(d==2){ return(TRUE) }
if(d !=2 && d!=1){
if(any(d %% (2:(d-1)) == rep(0,d-2))==TRUE){
return(FALSE)
} else{
return(TRUE)
}
}
}
i <- 2
j <- 0
for (i in 2:1000) {
if(return.prime(i)){j = j + 1}
i = i + 1
}
j # [1] 168

save from the IF function the variable

I have functions and would like to save from the IF function the variable "sick [i]" to take advantage of it
for(i in 1:licznik){
print_func <- function(a, b)
{
if(a > b)
{
print('wspolczynnik jest wiekszy' )
print(sick[i])
}
}
print_func(a[i], b[i])
}
How to do it
?
Try this from R for Data Science.
out <- vector("list", length(licznik))
for (i in seq_along(licznik)) {
if(a[[i]] > b[[i]]) {
print('wspolczynnik jest wiekszy')
print(sick[[i]])
out[[i]] <- sick[[i]]
}
}
str(unlist(out))

Explanation for crashing at n = 16

I am having a trouble in completing a homework of mine in C.The task is given an integer n print all the binary numbers with the length n that do not have 2 consecutive zeros int them and that includes leading zeros, note that at least one of the functions has to be recursive. Here is an example if n is 4 then the binary number 10 is treated 0010 and therefore wont be printed because it has 2 leading zeros. My problem is that my code crashes if n = 16 and I do not know why even though I have done a lot of debugging. Here is my code, Thanks for any help here.
void binaries_n_digits_no_00(int n)
{
if(n < 0)
{
return;
}
print_binaries_n_digits_no_00(0,n);
}
void print_binaries_n_digits_no_00(long int current_binary_index,int n)
{
int num_of_leading_zeros;
if((current_binary_index > (power(2,n) - 1)) || n == 0)
{
return;
}
num_of_leading_zeros = n - binary_num_length(current_binary_index);
if((binary_not_contain_00(current_binary_index) == 1) &&
(num_of_leading_zeros == 1 || num_of_leading_zeros == 0)){
if(current_binary_index == 0 && n == 1)
{
printf("\n0");
}
else if(num_of_leading_zeros == 1)
{
if(current_binary_index != 0)
{
printf("\n0");
print_binary(current_binary_index);
}
}
else{
printf("\n");
print_binary(current_binary_index);
}
}
print_binaries_n_digits_no_00(current_binary_index+1,n);
}
int binary_not_contain_00(long int num)
{
if(num/2 == 0)
{
return 1;
}
if(((num%2) == 0) && (((num/2) % 2) == 0))
{
return 0;
}
return binary_not_contain_00(num/2);
}
void print_binary(long int num)
{
if(num > 1)
{
print_binary(num/2);
}
printf("%d",num%2);
}
int binary_num_length(long int num)
{
if(num <= 1)
{
return 1;
}
else{
return (1 + binary_num_length(num/2));
}
}
long int power(int m, int n)
{
if(n == 0)
{
return 1;
}
return m * power(m,n-1);
}

Why is break() not working in this loop? (but stop is)

I am trying to build a matrix model which ends if certain conditions are invoked - however for some reason the break() command isn't working, although stop() does. Unfortunately stop() is not what I need as I need to run the model a number of times.
The first break command in the model works, but I have left it in with dth>100 so that you can see for yourselves
n.steps <- 200
ns <- array(0,c(14,n.steps))
ns[13,1]<-rpois(1,3)
ns[14,1] <- 1
k<-0
for (i in 1:n.steps){
k<-k+1
ns[13,1]<-rpois(1,2)
death<-sample(c(replicate(1000,
sample(c(1,0), prob=c(surv.age.a, 1-surv.age.a), size = 1))),1)
ns[14,k] <- death
if (death == 0) {
dth <- sample(1:100, 1)
if (dth > 100) {
ns[14,k]<-0
print("stop.1")
break()
} else {
while (death == 0) {
if (ns[13, k] > 0) {
rep.vec[i]<-ns[13,k]
ns[13, k] <- ns[13, k] - 1
ns[14,k+1]<-1
print("replace")
} else {
if (ns[13, k] == 0) {
print("stop.2")
ns[14,k+1]<-0
break()
}
}
}
}
}
}
Try this (only showing the relevant portions):
for (i in 1:n.steps){
# ...
break.out.of.for <- FALSE
while (death == 0) {
if (ns[13, k-1] > 0) {
# ...
} else {
if (ns[13, k] == 0) {
# ...
break.out.of.for = TRUE
break
}
}
if (break.out.of.for) {
break
}
}

Resources