text:
Duplicate the KOOS Jr. Scoring interval algorithm
Inspired from a real problem; we were looking at this table and said "Hey, now that's a good codegolf problem."
The KOOS Jr. scores converts from a raw number to a percentile score given this table:
Raw summed score  Interval score
(0-28)            (0 to 100 scale)
 0                100.000
 1                 91.975
 2                 84.600
 3                 79.914
 4                 76.332
 5                 73.342
 6                 70.704
 7                 68.284
 8                 65.994
 9                 63.776
10                 61.583
11                 59.381
12                 57.140
13                 54.840
14                 52.465
15                 50.012
16                 47.487
17                 44.905
18                 42.281
19                 39.625
20                 36.931
21                 34.174
22                 31.307
23                 28.251
24                 24.875
25                 20.941
26                 15.939
27                  8.291
28                  0.000

Provide a program, function, expression, or source file generator* that given the input raw number returns the interval score number. You may accept your input as a string or number and may produce your output as a string or number. Trailing zeros after the decimal point may be included or omitted. You may not however use scaled integers: 1 must really return 91.975 not 91975.
*source file generator must output a valid source file for some language you specify; just outputting the table is not allowed.

Note that for some languages, outputting to a file is not possible. I would recommend removing this restriction.

@HyperNeutrino: 1) It's not a restriction - see the or clause; 2) if they output the source file to stdout that's what I expect anyway.

Oh well I should go to sleep then. I must be blind. :P

" I used to be an adventurer like you. Then I took an arrow in the knee." Score: 0.000.

05AB1E, 59 bytes
•G‚Œιã¶&‡Vc–QΩ`ååI~(Ìö{3.ùSÿ{Ćι¯TærÆcï`₃āÀ}ªHÕ¶η•4ô.¥R3°/Iè

Try it online!
Explanation
•G‚Œιã¶&‡Vc–QΩååI~(Ìö{3.ùSÿ{Ćι¯TærÆcï₃āÀ}ªHÕ¶η• is a compressed version of the input constructed by:

multiplying each element in the input by 1000
reversing the resulting list
calculating deltas
joining to a single base-10 number
compressing to base-255

The rest of the code is then:
4ô          # split in pieces of 4
  .¥        # undelta
    R       # reverse
     3°/    # divide each by 1000
        Iè  # index into list with input

Clever trick with the same-length-4 stuff!

A wild Undelta appears!

Python 2, 166 160 139 bytes
lambda n:sum(int('6533222222211111111111222356EWU1LC74210ZYWTRQPOPRV1BRMO6BGYASWNLUSWQ55ZW96XMM8A2I6VX'[i::28],36)for i in range(28-n))/1e3

Try it online!
Edit: golf 6 bytes from glaring redundancy of 2's...; also saved 21 bytes by switch to base 36 (thanks ovs!) and using 1e3 instead of 1000.
The string is an encoded list of the 28 4-digit deltas.

PHP, 152 bytes
<?=intval(substr("255s1yyv1ta01pnu1mwc1kla1ik01gos1ex61d7k1bin19th183816bc14hd12l810n30ynd0wmh0ukp0shv0qda0o5n0lsr0j6z0g5p0car06eb0",$argn*4,4),36)/1e3;

Try it online!

Python 3, 133 bytes
lambda k:sum(int('5ukygji75mxo64d3f5vstve68rdiq42l8nof8cs35qyb5bdtzihbhk086m8nel1nx3kqxvn',36)//8292**i%8292for i in range(28-k))/1e3

It uses packed differences, and sums them.  To pack efficiently, rather than using binary, it's packed in a number that's effectively base 8292, and that number is embedded in the code as a base 36 literal.

Stax, 59 bytes
â¬∟╧↓┘╟╤éJ{súÇaz░«╝╬°╢=♦Γ┘=▐▬[è2Ü←`‼frl¢£≤kpOy‼5¶^≡%#ßî↕V0Å

Run and debug it

Mathematica, 196 bytes
(100-Accumulate[{0}~Join~IntegerDigits@9753332322223223323323344578])[[#+1]].{0,975,6,914,332,342,704,284,994,776,583,381,14,84,465,"012",487,905,281,625,931,174,307,251,875,941,939,291,0}[[#+1]]&

Python 3, 147 146 bytes
-1 byte thanks to @JörgHülsermann
lambda k:sum((int('9CU7OK2L6V5W6E8QYM3YL0TRGZIJ6Y14N43TRVCAXF6C58HP69ZC4536JNILBUC45C5S8G4DIT0J',36)&2**(14*-~i)-1)>>i*14for i in range(28-k))/1e3

Try it online!

1e3 instead of 1000


text:
Where does the pivot belong?
You will be given a positive integer as input.
The integer is the board of a seesaw.
Th integer will not have leading zeroes. You may take this input however you like.
Your task is to output the location of the pivot point of this seesaw, such that the board would balance.
A board balances if the moments on each side are equal in magnitude. A moment is calculated by multiplying the force by the distance from the pivot point. In this case, the force is equal to the digit.
For the integer 100 with a pivot point below the first 0, the moment on the left is 1x1=1. The moment on the right is 0x1=0. If the pivot point was below the second 0, the moment on the left would be 2x1=2 (because the 1 is now 2 away from the pivot).
For example, for the integer 31532 the pivot goes underneath the number 5. This is because the moments on the left are 3x2 + 1x1 = 7 and on the right the moments are 3x1 + 2x2 = 7.
The output for this integer is 3 because the pivot goes underneath the 3rd digit.
If the integer cannot be balanced, your code does not have to do anything - it can hang, error, output nothing - whatever you want.
Note that a pivot cannot go between two numbers. The pivot location must be an integer.
Test cases:
31532 -> 3
101 -> 2
231592 -> 4
8900311672 -> 5

Standard loopholes apply, this is code golf so shortest answer wins.

Can I not handle the last testcase if it is too large?

Can the output be 0-indexed?

Can the output be indexed from the front of the number?  Your test cases seem to do this.

Related

Is a list of digits a valid input format?

Duplicate? (balancing words on ascii value instead of numbers)

@LeakyNun that’s fine

@Dennis no, 1 indexed please

@WheatWizard it has to be indexed from the left, with the left most digit = 1

Haskell, 64 62 59 57 45 35 31 bytes
d l=sum(zipWith(*)[1..]l)/sum l

Try it online!

(:[]) is pure.

I think testing for <1 instead of ==0 should be enough. We get a list of all not right-heavy seesaws, but we are picking the first element anyway.

@nimi doing (<1) is pretty clever.  Thanks for the tips.

@flawr It feels like I should but $ has lower precedence than < preventing me.

Oh you're right! As an alternative I think you could use until instead of the [x|x<-...]!!0 (not tested: until(\x->sum(zipWith(*)[1-x..]l<1)(+1)0) (coding on the phone is a little bit cumbersome :P)

@flawr That works but costs me a byte.

Huh, I must have counted wrong, sorry=/

Ah I missed a parenthesis, by adding that it has the same length!

R, 66 bytes
sum(1:length(n<-strtoi(strsplit(paste(scan()),"")[[1]]))*n)/sum(n)

Try it online!

You can take input as string by doing scan(,'') instead of using paste.

Jelly, 7 bytes
Dµæ.J:S

Try it online! or verify all inputs at once.

You’ve done this before for some reason?

@Tim No, it's just a formula used in physics - sum of moments / sum of digits.

@Tim He's known for posting answers extremely quickly to questions; sometimes, he posts an answer in the same minute as the question :P

J, 29 bytes
[:>:@(+/%~]+/@:*i.@$)10#.inv]

Try it online!

25 bytes [:(+/<.@%~]+/ .*#\),.&.": using a different method to get the list of digits.

Nice, didn't see this before I posted mine. You beat me by a margin! And @miles made it even better.

In all honesty I don't think I've seen this many J golfers (5) in one place before :P

Brain-Flak, 64 bytes
({({}[((((()()()){}){}){}){}]<>{})<>}<>)({()<({}[({})])>}<>)

Try it online!
60+4 bytes for the -ar flags.
Explanation
 {                                  }     for each digit in input (starting at the end)
   {}                                     get digit as ASCII code
     [((((()()()){}){}){}){}]             subtract 48 to get digit as number
  (                          <>{})<>      add to cumulative sum on second stack
(                                    <>)  push total of all cumulative sums (the sum of moments)

 {              }       while sum of moments != 0
     ({}[({})])         subtract sum of weights
  ()<          >        count the number of iterations needed
(                <>)    push onto first stack and implicitly output

Usually you can save bytes by using BrainHack instead of -a, but BrainHack doesn't have -r yet so you wont be able to this time.

Also because of the flexible input it seems you can take input as a list of ints instead of requiring a string.  This could save you a bunch of bytes.

Python 3, 66 bytes
f=lambda n,a=0,b=0,c=1:n and f(n//10,a+n%10*c,b+n%10,c+1)or c-a//b

Try it online!

+1, Exactly half the length of my answer.... :D

Brachylog, 14 bytes
ẹ⟨{iᶠ×ᵐ+}÷+⟩+₁

Try it online!

GolfScript (24 bytes)
0:i.@{15&.@+@@i):i*+\}//

Online demo

Python 3, 69 bytes
x=[*map(int,input())]
print(sum(v*k for k,v in enumerate(x))//sum(x))

Try it online!
-7 bytes and fixed thanks to ovs

But it doesn't even work

Adding a closing bracket to the first line fixes the syntax, but then 3 is printed instead of 2.

Slightly golfed and fixed

@LeakyNun It outputs 2 for me, which seems to be right to me if this is 0-indexed.

@ovs Thanks for the fix+golf

@LeakyNun Fixed.

C (gcc), 72 bytes
a,b,c;f(long n){a=b=c=0;for(;n;a+=n%10*++c,n/=10)b+=n%10;return-~c-a/b;}

Try it online!

Since a,b,c are declared in an enclosing scope, they can be initialised in the initialiser of the for loop, saving a semicolon.

funnily also a valid solution in JS (slightly altered) f=n=>{for(a=b=c=0;n;a+=n%10*++c,n=n/10|0)b+=n%10;return-~c-a/b}

MATL, 12 bytes
48-ttn:*sws/

Try it online!

Mathematica, 42 bytes
Range@Length@#.#/Total@#&@IntegerDigits@#&

Try it online! (Mathics)

Tr saves 4 byte, but breaks Mathics compatibility.

Pyth, 14 bytes
h/s.e*bkJjQTsJ

Test suite.

Actually, 10 bytes
♂≡;Σ@;r*\u

Try it online!

Cheddar, 63 bytes
n->(a->a.map((x,y)->x*y).sum/a.sum+1)(("%d"%n).bytes=>((-)&48))

Try it online!

Python 2, 132 134 126 112 bytes

Thanks @ovs for 14 bytes.

n,m=map(int,input()),0
z=lambda a,b:sum(n[j]*abs(m-j)for j in range(a,b))
while z(0,m)<z(m,len(n)):m+=1
print-~m

Try it online!

But it prints 4 instead of 5

Yes, it is 0-indexed. Should I change it? 2 bytes trade though..

Some bytes off

Retina, 43 bytes
$
;$`
(?=(.*);)
$1
\d
$*
^(1+)(\1)*;\1$
$#2

Try it online!

Java (OpenJDK 8), 80 bytes
int f(long n){int a=0,b=0,c=0;for(;n>0;a+=n%10*++c,n/=10)b+=n%10;return-~c-a/b;}

Try it online!

You could make this shorter with a lambda expression, n->{...}

05AB1E, 10 bytes
TвÐgL*OsO÷

Try it online!

GolfScript, 33 bytes
{48-}%.[.,,]zip{{*}*}%{+}*\{+}*/)

Try it online!

Retina, 30 bytes

$'¶
1>`¶

.
$*
(1+)¶(\1)+
$#2

Try it online! Link includes test cases. Explanation: The first stage sneakily creates newline-delimited duplicates of all the suffixes of the original string. This means that the each digit appears after the first newline the number of times according to how far away it is from the left, effectively multiplying to give its moment. The second stage deletes all the newlines after the first, completing the calculation of the moments. The third stage converts the digits to unary, summing them, and the fourth stage divides the sums (exact division is assumed to apply here).

J, 29 bytes
(0 i.~]+/ .*[:-/~#\)@(,.&.":)

J executes verbs right-to-left, so let's start at the end and work our way towards the beginning.
Explanation
         ,.&.":      NB. Explode integer into digits
         #\          NB. 0 .. N-1, where N=number of digits
         -/~         NB. Distance table, one row per digit
         ] +/ .* …   NB. Forces at each pivot (F=digit * distance)
         0 i.~ …     NB. Digit index where F=0

Note that J is an index-origin 0 language, so it would be more natural and idiomatic for the answer to 8900311672 to be 4 rather than 5, for 231592 to be 3 rather than 4, etc, and so that's the way this function is written.
But if the index-origin 1 is required for output, then add 1+ before 0 i.~ and add 2 bytes to the score, bringing it up from 29 to 31.

This does not work. Replace #.~&10^:_1 with (,.&.":) to fix.

@rdm Thanks, I originally had (10&#.^:_1) but I wanted to remove the parens, and quick independent testing showed #.~&10^:_1, but of course as you observed the composition doesn't.  I'll fix. Thanks for the shortening.

Python 3, 127 bytes
I am a newbie golfer.  All suggestions and tips are greatly apreciated :).
lambda x:min([(abs(eval("+".join(list(x[:i+1])))-eval("+".join(list(x[i:])))),i+1)for i in range(len(x))],key=lambda x:x[0])[1]

Try it Online!

C# (.NET Core), 84 bytes
a=>{int p=0,q=0,i=1;for(;i<=a.Length;p+=a[i-1],q+=i*a[i++-1]);return q/(q%p>0?0:p);}

Try it online!
Takes in an array of single digits as the 'integer' input. Uses the image moments approach for finding the centre of mass. Throws a divide by zero if the seesaw is unbalanced.
DeGolfed
a=>{
    int p=0, // used to store the image moment of order 0
        q=0, // used to store the image moment of order 1
        i=1; // array index, offset to 1 as 1 based indexing is required

    for (; i <= a.Length; // go through the array
        p += a[i-1],      // getting the order 0 image moment value
        q += i*a[i++-1]); //     and the order 1 image moment value

    // q / p is the centre of mass, but as an exact integer pivot is required,
    // if q is not evenly divisible by p,
    // then throw a divide by zero error.
    // otherwise return q / p
    return q / ( q % p > 0? 0 : p);
}

82 bytes

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Mutation-hardened quine
Your task is to make a program that prints out its own source.
"Hey, we already have this challenge, and tons of variations of it! Why are you making another one?" you may ask, but this one is going to be one of the most difficult ones (hopefully, anyway).
Your quine must be "mutation-hardened", which means the quine, even when any one of its characters are duplicated in place, must output the source code of the original program.
For example, if you have a quine (the following example is not written in any language, it's just pseudocode):
abcd

These programs must all output abcd:
aabcd
abbcd
abccd
abcdd

(In each of those programs, a, b, c and d are each duplicated in-place, which means the duplicated character was placed directly after the original character.)
Rules:

Standard quine rules apply.
A multi-byte character counts as one character, and the character is not "split" into its respective bytes when duplicated.

This is code-golf, so shortest code in bytes wins!

Does this count? 0 and 00 in CJam both output 0.

No, 0 is not a proper quine.

I think it would be much interesting as [tag:code-bowling]

Is the problem of code mutation solvable in general? unless the mutation happens to a character inside a quoted string, it would usually corrupt the program.

Isn't the title a bit misleading? "Mutation" suggests altering a character, not repeating it

@hasen I think this may be impossible in many languages, but after seeing this answer to a similar challenge, I'm ready to be impressed again. (Too bad that poster seems to have left.)

><>, 56 bytes
^
.
+
8
f
0
o
a
o
~
:
?
~
:
?
:
-
*
4
8
:
^
^
}
*
3
d
'

Try it online! or verify all mutations.
How the original program works (outdated)
The interpreter starts in cell (0, 0). ^ sets the direction to upwards, so the instruction pointer (IP) wraps around to cell (0, 20).
' activates string mode: until the next ' is encountered, all characters under the IP are pushed on the stack. The same ' is found again after wrapping around, so we push
d3*}^^:84*=?~oao0f.^

The IP lands at (0, 19), still going upwards. Executing d3*} pushes 13 = 0xd, then 3, multiplies both values (39 / single quote), then rotates the stack to the right. This leaves the stack as follows.
'd3*}^^:84*=?~oao0f.^

The next two instructions (^) do nothing at this point.
:84*= duplicates the top of the stack, pushes 8 and 4, multiplies them (32 / space), then tests the duplicated character for equality with space. For the unaltered program, this will always push 0.
? skips the next instruction if the top of the stack is falsy. For the original program, it always is, so ~ is always skipped.
oao pops and prints the top of the stack, pushes a 10 / linefeed, then pops and prints linefeed.
Finally 0f. jumps to cell (0, 15) (the bottommost ^), starting over with the next character on the stack.
Once the stack is empty, the entire source code has been printed. : will fail and the program exits.
How the mutated programs work (outdated)
Duplicating any non-linefeed character will only extend the program horizontally. Since the program is executed vertically, these extra instructions will never get executed.
Duplicating any linefeed before the bottomost ^ will shift cells (0, 14) and (0, 15) to (0, 15) and (0, 16). 0f. will now jump to the cell before the bottommost ^, which is also a ^, so the program is not affected by the shift.
Finally, any duplicated linefeed character will also alter the string. Short lines are padded with spaces, so a 32 / space will be inserted at the linefeed's position. 84*= will push 1 for space, so ? doesn't skip the next instruction. In this case, ~ pops and discards space, so the following o will print the character above space instead.

You can duplicate any newline and it will still work.

Oh, I didn't read the post properly :P (Dammit Dennis, why are you so good)

Cracked.

@jimmy23013 Should be fixed.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
lastIndexOf in CJam
For the question Find the highest unique digit , here is my answer :
9A,sqfe=W%X#-

At the end I am essentially trying to achieve a lastIndexOf. I do that by reversing my array, using indexOf, and subtracting from 9. This adds 4 (9 W % -) extra bytes to get from indexOf to lastIndexOf.
Furthermore, if I didn't know my array was length 10 the code would be even longer, and secondly, this code returns 10 when indexOf is -1 which may not be acceptable in many situations.
Any suggestions on a shorter way to do the lastIndexOf operation (generally or just as needed for this challenge)?

I want to ask the same thing, but in [tag:pyth] :P

@EriktheOutgolfer Thanks, I changed it to shorter. And I'm interested in solutions for any of the cases: 1) my challenge 2) variable array length 3) -1 case.

@geokavel OK, posting mine as an answer for 3) then. :)

Splitting is sometimes a good way to do this. E.g.
e# Stack: ... haystack needle
a/);S*,

With variants, such as removing the a if both needle and haystack are strings.

Golfed: a/)a*,.

Note: doesn't handle -1 case. Outputs 0 instead.

9 bytes
_,(@@W%#-

Try it online!
You must have ...element list exactly like this in the stack. If W doesn't contain -1 you must replace it with something that does evaluate to -1.

Note: doesn't handle -1 case. Outputs length of array instead.

@geokavel Yeah the -1 case is being worked on...

In the case where the array has a known length, outputting the length could sometimes be usable, since at least it is a unique value that could not be confused with a valid index.