# Find how “smooth” a number is based on binary

I haven't been on PP&CG for a while, so I thought I would post something!

Your task is to find how "smooth" a natural number is. Your method is to:

1: Convert the number to binary
2: Find the number of changes / switches
3: Find the length of the string (in binary)
4: Divide length by changes

So, an example. 5.
Starting at step one, we wind up with 101 for binary.
Step two is where we count the "switches". This is how many times a digit changes, so 100001 would count 2 switches. 101 counts 2, too.
Step three has a length of three in binary. Step four gives us 3/2, or 1.5.
Doing this for 10 is also simple: Step one results with 1010, two with three, three with four, and a final result has 1.33333333... repeating.

If the inputs output infinity (examples: 1, 3, and 7), you need to output something that tells you infinity, like $$\\infty\$$ or Infinity.

Now, you might ask, "what about scoring?" or something like that: You are scored in characters, so feel free to use a lot of code golfing languages. (I'm looking at you, Jelly)
If you round the output "smoothness factor" to 3 decimal places (4/3 is now 1.333, 5/3 is 1.667) your score is now x0.95, and being able to not only return a smoothness factor but also be able to compare two numbers (etc: putting in 5 and 10 returns > because 5's smoothness factor is greater than 10's) multiplies your value by x0.7. Command-line flags don't count for anything.
Have fun!

This challenge ends the 19th of March.
Current placeholders: The functional language holder, with 45 chars, Nahuel Fouilleul, and the code golf language holder, with 7 chars, Luis Mendo.

• It would be a bit clearer if both examples were given separately. Also, I don't think the bonuses add much to the challenge. – Arnauld Mar 5 at 16:15
• welcome to PPCG! You've been around for a month or so, but I would suggest using The Sandbox to get feedback on your challenges before posting them. – Giuseppe Mar 5 at 16:16
• What is the reason for the complexity around scoring? – Jonathan Allan Mar 5 at 16:55
• Hi, I downvoted this challenge due to the complexity around the scoring and the ambiguous-ness related to it. – AdmBorkBork Mar 5 at 17:10
• I would suggest that if you are going to select an accepted answer at least wait 1 week – Luis felipe De jesus Munoz Mar 5 at 18:47

# Perl 5 (-p -Mbignum), 45 bytes

$_=sprintf"%b",$_;$_=y///c/(s/(.)(?!\1)//g-1)  TIO # MATL, 7 characters Btnwdz/  Try it online! ### Explanation B % Convert to binary t % Duplicate n % Number of elements w % Swap d % Consecutive differences z % Number of nonzeros / % Divide  • Honestly, how it it possible to incorporate 7 ASCII characters to make a complicated program like the one I described. I don't understand code golf anymore. – Ethan Slota Mar 5 at 16:36 • @Ethan Wait for the 4-byte Jelly or 05AB1E answers... – Luis Mendo Mar 5 at 16:38 • Note that in my original post I said you would be counted by chars, not bytes. Still stands. – Ethan Slota Mar 5 at 16:42 • @EthanSlota MATL is at least pretty easy to understand, since for the most part, each command is a MATLAB or Octave command and there's a parser built in Octave / MATLAB. This would translate to something like @(x,b=dec2bin(x))numel(b)/nnz(diff(b)) but it uses Luis' much terser language to achieve the same result. – Giuseppe Mar 5 at 16:47 • @EthanSlota: Counting by chars instead of bytes can only make the scores even lower. – recursive Mar 5 at 17:06 # Japt, 8 bytes NULL for infinity ¤Ê/¢ä¦ x  Try it online! # Jelly, 8 bytes, score 8 Maybe there is a terser way... edit: I don't think there is. BL÷BITLƲ  Infinity is given as inf. Try it online! ...other 8's are possible too, for example BµITL÷@L or BL÷BnƝSƊ. • Here’s a version to get the bonuses: Try it online! score 16 x 0.95 x 0.7 = 10.64 – Nick Kennedy Mar 5 at 18:32 • Shouldn't inf be greater than all other values? If we can identify inf as less than all others we could accept a list of either one or two numbers and have BL÷BITLƲ),M for 11 * 0.7 = 7.7. (Maybe this comparison should be fixed...) – Jonathan Allan Mar 5 at 18:50 • ...BTW that isn't doing what you think IṠ$ is acting on the input list itself so it's just telling you that 10 is greater than 5 rather than comparing the smoothness of the two numbers. – Jonathan Allan Mar 5 at 18:59
• Thanks - still getting my head around Jelly. This seems better: tio but is two bytes longer – Nick Kennedy Mar 5 at 19:21

# 05AB1E, 8 bytes/characters

bgIbγg</


Or alternatively:

b©g®¥ÄO/


Outputs 0.0 for the INF cases.

With both bonuses score: 11.97 (18 bytes/characters * 0.95 * 0.7):

εbgybγg</3.ò}DÆ.±)


Outputs 1 if the first input is larger than the second; -1 if vice-versa; 0 if they are equal.
NOTE: Because I output 0.0 for the INF cases, they are considered lower than non-infinity test cases. Let me know if this has to be fixed..

Explanation:

ε       # Map both values of the (implicit) input-list:
b      #  Get the binary-string of the current value
g     #  And get the length of this string
yb     #  Get the binary-string of the current value again
γ    #  Split it into chunks of equal adjacent digits
g<  #  Get the amount of chunks, and subtract 1
/      #  Divide both numbers
3.ò    #  Round the number to 3 decimal values
}D      # After the map: duplicate the resulting list
Æ     # Reduce the duplicated list by subtraction
.±   # And get the sign of that result
)  # Then wrap it into a list with the mapped values
# (and output the result implicitly)

• For clarification, ∞ ≠ 0. – Ethan Slota Mar 5 at 17:48
• @LuisMendo Yes, but 05AB1E doesn't have an infinite value (unless you count the infinite list). And since regular cases which divide x by y can never result in 0 anyway, I use that to indicate infinity (the challenge description states "you need to output something that tells you infinity", which is 0.0 in my answer). If the infinite list or an empty string or something has to be output instead of 0 it's 3 bytes more, although I don't really see the point.. – Kevin Cruijssen Mar 5 at 17:51
• I'll accept this answer as valid as there are no fractions that naturally result in zero. You would need to define something (like 5/1 = 0 = Infinity) to get 0. – Ethan Slota Mar 5 at 17:55
• @KevinCruijssen Ah, I see. Thanks for clarifying – Luis Mendo Mar 5 at 18:10

# JavaScript (ES6),  46 44  40 bytes / characters

Returns Infinity if there's no bit flip.

n=>(g=s=>n&&1+g(x=s-(n^(n>>=1))%2))/~x


Try it online!

### Commented

n => (                  // n = input integer
g = s =>              // g = recursive function taking the number s of bit switches
n &&                //   stop if n is equal to 0
1 +                 //   otherwise, add 1 to the final returned value
g(                  //   and do a recursive call to g:
x =               //     update s and save the result in x:
s -             //       subtract 1 from s if ...
(n ^ (n >>= 1)) //       ... there is a bit switch; and shift n to the right
% 2             //       NB: an extra bit switch is counted on the last bit
)                   //   end of recursive call
)                     // initial call to g with s = [''], which is coerced to 0
// as soon as something is subtracted from it
/ ~x                    // divide the result of g by -(x + 1), which compensates for
// the extra switch


# Kotlin, 83 82 bytes

{s->s.toString(2).run{length.toFloat()/(0..length-2).count{this[it]!=this[it+1]}}}


Try it online!

• Welcome to PPCG! :) – Shaggy Mar 6 at 8:14
• thanks, Shaggy! – Adam Mar 7 at 3:21

# R, 56 bytes

length(y<-(x=scan())%/%2^(0:log2(x))%%2)/sum(diff(y)!=0)


Try it online!

# Charcoal, 24 characters

≔⍘Ｎ²θ≔⁺№θ10№θ01η¿ηＩ∕Ｌθη∞


Try it online! Link is to verbose version of code. Explanation:

≔⍘Ｎ²θ


Input the number and convert it to base 2 as a string.

≔⁺№θ10№θ01η


Calculate the number of of switches by counting the occurrences of 10 or 01 in the string.

¿ηＩ∕Ｌθη∞


If the total is nonzero then output the smoothness otherwise print Infinity.

# 1. Python 3, 131 bytes (154 with file header)

Hi. I know that my code is way longer than others, but I will try it ;) Indentation by tabs.

Script takes sequence of numbers in aguments and prints "smoothness" for each argument on own line. If number of changes is 0, prints "inf".

$./script.py 12 4.0$ ./script.py 12 5 6
4.0
1.5
3.0

\$ ./script.py seq 5
None
2.0
None
3.0
1.5


file header

#!/usr/bin/env python3


code

import sys
for n in sys.argv[1:]:
b=bin(int(n))[2:];c=0;l=b
for o in b:
if o!=l:c+=1
l=o
print(len(b)/c if c>0 else"inf")


## Input single number from STDIN: 102+23 bytes (code + file header)

n=input();b=bin(int(n))[2:];c=0;l=b
for o in b:
if o!=l:c+=1
l=o
print(len(b)/c if c>0 else"inf")


# Ruby, 42 bytes

->n{1.0*(w=(n^n/2).digits 2).size/~-w.sum}


Try it online!

### How?

First step: bitwise XOR of x and x/2. The result will have a bit set to 1 for every switch in the input number plus 1, and so we just need to get the number of digits in base 2, and their sum. Then add some parentheses, and make it a float.

# Python 3, 105 chars

def s(n):b=bin(n)[2:];l=len(b);c=sum([0if b[i]==b[i+1]else 1for i in range(l-1)]);return l/c if c>0else-1


Returns -1 in the case of an infinity.

# Python 3.8 (pre-release), 60 bytes

Port of G B's Ruby answer.

lambda l:(c:=(b:=bin(l^l>>1)).count('1'))>1and(len(b)-2)/~-c


Try it online!

# Python 2, 68 bytes

Returns false if the value is infinite.

k=input()
n=s=0
while k:l=k%2;n+=1.;k/=2;s+=l^k%2
print s>1and n/~-s


Try it online!