0

I want to create a function that will print values of a given vector in a specific order: zeros, ones, numbers divisible by 2, numbers divisible by 3 (not by 2,excl.0), numbers divisible by 5 (not by 2 and 3, excl. 0), etc.

Would it be a good idea to use some vartiation of "bubble sort"? I think that a basic idea is to have if condition based on

if (x[i] %% divisor == 0 && x[i+1] %% divisor != 0)

I also know that I should have a loop that will increase "divisor" values every turn, but besides I don't really know how to start. I was able to comprehend basic "bubble sort" algorithm, but it seems that I have too many gaps to work this out comfortably.

Piotr Koller
  • 599
  • 3
  • 8
  • 17
  • 1
    It would be nice to include some [sample input](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) and the desired output so that possible solutions can be tested. – MrFlick Mar 30 '17 at 18:33
  • On a vector (0:10), the output should be 0 1 2 4 6 8 10 3 9 5 7 – Piotr Koller Mar 30 '17 at 19:31

1 Answers1

0
# generate a vector 

x <- 1:1000

# the function 

order_n <- function(v) 
  {

y <- 1:floor(v/2);

z <- y[v%%y == 0];

z <- z[z!=1];

return(ifelse(is.infinite(min(z)), 0, min(z))) }

# the ordering vector 

xx <- rep(0, length(x))
for (i in 1:length(x)) {xx[i] <- order_n(x[i])}

head(xx,50)


[1] NA  0  0  2  0  2  0  2  3  2  0  2  0  2  3  2  0  2  0  2  3  2  0  2
[25]  5  2  3  2  0  2  0  2  3  2  5  2  0  2  3  2  0  2  0  2  3  2  0  2
[49]  7  2

I should mention that the 0 value in xx means that the number is prime, therefore it should be assigned the highest possible order

Mouad_Seridi
  • 2,666
  • 15
  • 27