How can I input two digits in a single line using space like 5 6?
c code:
int a=0,b=0;
printf(" Input a and b in digits: \'use space\' ");
scanf("%d%d",&a,&b);
R single line input multiple values used space 4 5 without press enter:
sum_of_total_number <- function (first,second){
first <- as.numeric(first)
second <- as.numeric(second)
return (first + second )
}
main <- function(a,b){
{ a <- readline("Input value a: "); b <- readline("INput value b: ")}
print(sum_of_total_number(a,b))
}
main()
You can use the scan() function to read multiple values.
main <- function(){
vals <- scan(n=2, what=numeric(), quiet=TRUE)
print(sum(vals))
}
main()
Related
i am tasked with the following two questions, however for some reason my codes dont work.
Problem 1
Write a function (named FizzBuzz_function) that takes a number from the user (named n) and prints the numbers from 1 to n. However, for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”.
Problem 2
Write a function that takes a number from the user (named n) and returns nth Fibonacci number.
Please check your function: When n is 20, the Fibonacci number (F20) is 6765 (I assume F1=1, F2=1).
Here are my answers but I am not getting any outputs
1.
n <- readline(prompt="Enter your number: ")
# define the function
fizz_buzz <- FizzBuzz_function(n){
if(n%%3 == 0 & n%%5 == 0) {
print('FizzBuzz')
}
else if(n%%3 == 0) {
print('Fizz')
}
else if (n%%5 == 0){
print('Buzz')
}
else {
print(n)
}
}
n <- readline(prompt="Enter your number: ")
vast=function(n){
vast=vector()
vast[1]=1
vast[2]=1
for(i in 3:n){vast[i]=vast[i-1]+vast[i-2]}
return(vast)
}
I am trying to run a simple loop that will count my points. You can see the code is very simple. I think there's something I am missing here about saving the values within loops to objects. Most information I find is for more complex loops. Feels like this should be a simple solution that I just don't understand yet.
test <- function(){
number <- 2
loop <- function(){
entry <- as.numeric(readline(prompt = "Enter Number:"))
if(entry == number){
points <- 2 * points
cat("You have " ,points, " points!", sep ="")
print("Double points!")
}else{
print("Lose a point.")
points <- points - 1
cat("You have " ,points, " points!", sep ="")
if(points > (0)){
loop()
}else{
print("You lose!")
}
}
}
loop()
}
test()
When this runs, user enters 3 and the points become 9 and the loop begins again. If user enters 3 again it should subtract 1 point from 9 to make 8. But the object points value is 9 and will not go less than that.
You should use the current value of points as an input to the loop function. And when you call loop(), if it's not the first call, pass in the current value.
test <- function() {
number <- 2
starting_points <- 10
loop <- function(points) {
entry <- as.numeric(readline(prompt = "Enter Number:"))
if (entry == number) {
points <- 2 * points
cat("You have " , points, " points!", sep = "")
print("Double points!")
} else{
print("Lose a point.")
points <- points - 1
cat("You have " , points, " points!", sep = "")
if (points > (0)) {
loop(points)
} else{
print("You lose!")
}
}
}
loop(points = starting_points)
}
test()
I'd also suggest not mixing cat() and print() - they have different behavior in some cases. (I'd avoid cat() unless you are, e.g., writing to log files or trying to avoid auto-formatting done by print - generally print() or message() is more appropriate.)
### Instead of this:
cat("You have " , points, " points!", sep = "")
## use this:
print(paste0("You have " , points, " points!"))
## or this:
print(sprintf("You have %s points", points))
You didn't assign any value to variable points.
I need to create a vector with multiple inputs (integers) from user.
The intent is to create a list and verify if it has a mode and where is its median.
I am using this code:
ReadVector <- function()
{
x <- 0
while(x<16) {
n <- readline(prompt="Input one integer: ")
return(as.integer(n))
VectorUser <- c(n)
x <- x+1
}
print(VectorUser)
}
ReadVector()
And I can only get one integer, I dont know if my mistake is in the while loop or(and) in the concatenate command after it. Can you help me?
Does this work for you?
ReadVector <- function()
{
x <- 0
myvector = vector()
while(x<16) {
n <- readline(prompt="Input one integer: ")
myvector = c(myvector,n)
x <- x+1
}
return (as.integer(myvector))
}
You need yo save your values in a vector, and keep it (without returning inside the loop), until you completed it.
Hope it helps
ff=function(){
d=c()
while (TRUE){
int = readline('ENTER to quit > ')
if(nchar(int)==0) {
if(length(d)>0)cat("The numbers you entered are:",d)
else(cat("You did not enter any number!!"));break}
else{
value=suppressWarnings(as.integer(int))
if(!is.na(value)){cat(value);d=c(d,value)} else cat(ran[sample(6,1)])
}}
ff()
So, In a string containing multiple 1's,
Now, it is possible that, the number
'1'
appears at several positions, let's say, at multiple positions. What I want is
(3)
This is not a complete answer, but some ideas (partly based on comments):
z <- "1101101101"
zz <- as.numeric(strsplit(z,"")[[1]])
Compute autocorrelation function and draw plot: in this case I'm getting the periodicity=3 pretty crudely as the first point at which there is an increase followed by a decrease ...
a1 <- acf(zz)
first.peak <- which(diff(sign(diff(a1$acf[,,1])))==-2)[1]
Now we know the periodicity is 3; create runs of 3 with embed() and analyze their similarities:
ee <- embed(zz,first.peak)
pp <- apply(ee,1,paste,collapse="")
mm <- outer(pp,pp,"==")
aa <- apply(mm[!duplicated(mm),],1,which)
sapply(aa,length) ## 3 3 2 ## number of repeats
sapply(aa,function(x) unique(diff(x))) ## 3 3 3
The following code does exactly what you ask for. Try it with str_groups('1101101101'). It returns a list of 3-vectors. Note that the first triple is (1, 3, 4) because the character at the 10th position is also a 1.
Final version, optimized and without errors
str_groups <- function (s) {
digits <- as.numeric(strsplit(s, '')[[1]])
index1 <- which(digits == 1)
len <- length(digits)
back <- length(index1)
if (back == 0) return(list())
maxpitch <- (len - 1) %/% 2
patterns <- matrix(0, len, maxpitch)
result <- list()
for (pitch in 1:maxpitch) {
divisors <- which(pitch %% 1:(pitch %/% 2) == 0)
while (index1[back] > len - 2 * pitch) {
back <- back - 1
if (back == 0) return(result)
}
for (startpos in index1[1:back]) {
if (patterns[startpos, pitch] != 0) next
pos <- seq(startpos, len, pitch)
if (digits[pos[2]] != 1 || digits[pos[3]] != 1) next
repeats <- length(pos)
if (repeats > 3) for (i in 4:repeats) {
if (digits[pos[i]] != 1) {
repeats <- i - 1
break
}
}
continue <- F
for (subpitch in divisors) {
sublen <- patterns[startpos, subpitch]
if (sublen > pitch / subpitch * (repeats - 1)) {
continue <- T
break
}
}
if (continue) next
for (i in 1:repeats) patterns[pos[i], pitch] <- repeats - i + 1
result <- append(result, list(c(startpos, pitch, repeats)))
}
}
return(result)
}
Note: this algorithm has roughly quadratic runtime complexity, so if you make your strings twice as long, it will take four times as much time to find all patterns on average.
Pseudocode version
To aid understanding of the code. For particulars of R functions such as which, consult the R online documentation, for example by running ?which on the R command line.
PROCEDURE str_groups WITH INPUT $s (a string of the form /(0|1)*/):
digits := array containing the digits in $s
index1 := positions of the digits in $s that are equal to 1
len := pointer to last item in $digits
back := pointer to last item in $index1
IF there are no items in $index1, EXIT WITH empty list
maxpitch := the greatest possible interval between 1-digits, given $len
patterns := array with $len rows and $maxpitch columns, initially all zero
result := array of triplets, initially empty
FOR EACH possible $pitch FROM 1 TO $maxpitch:
divisors := array of divisors of $pitch (including 1, excluding $pitch)
UPDATE $back TO the last position at which a pattern could start;
IF no such position remains, EXIT WITH result
FOR EACH possible $startpos IN $index1 up to $back:
IF $startpos is marked as part of a pattern, SKIP TO NEXT $startpos
pos := possible positions of pattern members given $startpos, $pitch
IF either the 2nd or 3rd $pos is not 1, SKIP TO NEXT $startpos
repeats := the number of positions in $pos
IF there are more than 3 positions in $pos THEN
count how long the pattern continues
UPDATE $repeats TO the length of the pattern
END IF (more than 3 positions)
FOR EACH possible $subpitch IN $divisors:
check $patterns for pattern with interval $subpitch at $startpos
IF such a pattern is found AND it envelopes the current pattern,
SKIP TO NEXT $startpos
(using helper variable $continue to cross two loop levels)
END IF (pattern found)
END FOR (subpitch)
FOR EACH consecutive position IN the pattern:
UPDATE $patterns at row of position and column of $pitch TO ...
... the remaining length of the pattern at that position
END FOR (position)
APPEND the triplet ($startpos, $pitch, $repeats) TO $result
END FOR (startpos)
END FOR (pitch)
EXIT WITH $result
END PROCEDURE (str_groups)
Perhaps the following route will help:
Convert string to a vector of integers characters
v <- as.integer(strsplit(s, "")[[1]])
Repeatedly convert this vector to matrices of varying number of rows...
m <- matrix(v, nrow=...)
...and use rle to find relevant patterns in the rows of the matrix m:
rle(m[1, ]); rle(m[2, ]); ...
I'm trying to implement following thing in R, but I'm new in R and my code doesn't work.
I have matrix A, I did coordinates changes .
I want to write two function:
1) give the element of matrix, given coordinates
2) give the coordinates given number.
the pseudo code is right, the only problem is my syntax. can somebody correct it ?
f<- as.numeric(readline(prompt="Please enter 10 to get coordinate of number,and 20 to get the number > "));
if(p==10){
# give the number, given coordinates
i<- as.numeric(readline(prompt="Pleae enter i cordinate > "));
j<- as.numeric(readline(prompt="Pleae enter j cordinate > "));
if (i>0&j<0) return A[5+i,5+j]
if (i>0&j>0) return A[5+i,5+j]
if (i<0&j>0) return A[5+i,5-j]
if (i<0&j<0) return A[5+i,5-j]
}else if (p==20){
#give the cordinate, given number
coordinate <- which(A==number)
[i,j]<-A[2-coordinate[0],coordinate[1]-2]
}
}
Warning: what if i or j is equal to zero? Next, make a single variable which is the decimal representation of binary i,j, That is,
if(p==10){
x <- (i>0) + 2*(j>0) +1
# x takes on values 1 thru 5. This is because switch requires nonnegative integer
switch(x,
return A[5+i,5+j],
return A[5+i,5+j],
return A[5+i,5+j],
return A[5+i,5+j]) # change the +/- indices as desired
}else{
#etc.
And, finally, you should make this a function, not a collection of commands.
Edit - I skipped this before, but: you cannot call an index of 0 so you need to fix a number of things in the line [i,j]<-A[2-coordinate[0],coordinate[1]-2]
The syntax is as follows:
x <- 4
if (x == 1 | x == 2) print("YES")