平衡词


33

这项挑战已发布在DailyProgrammer subreddit上,我认为这将是进行代码高尔夫挑战的最佳人选。确定字母是否平衡是基于其到平衡点的距离以及字母的值。字母的值可以通过采用字母的一个索引位置或从ASCII值中减去64来确定。此外,字母的值乘以它与平衡点的距离。让我们看一个例子STEAD

STEAD   -> 19, 20, 5, 1, 4 ASCII values
           This balances at T, and I'll show you why!
S T EAD -> 1*19 = 1*5 + 2*1 + 3*4
           Each set of letters on either side sums to the same value, so
           T is the anchor.

但是,应注意,并非所有单词都是平衡的。例如,该词WRONG在任何配置中都不平衡。同样,单词必须在一个字母上保持平衡,而不是两个字母之间。例如,SAAS如果两个字母中间有一个字母,则将保持平衡A,但是由于没有字母,它将不平衡。

任务

您应该创建一个程序或函数,该程序或函数大写字母作为输入或函数参数,然后生成两个输出之一:

  1. 如果单词平衡,则单词的左侧,空格,锚字母,另一个空格和右侧应打印出来。

    function (STEAD) -> S T EAD

  2. 如果单词不平衡,则应打印出单词,然后是 DOES NOT BALANCE

    function (WRONG) -> WRONG DOES NOT BALANCE

您可以假定所有输入都是大写字母,并且只有字母字符。

示例I / O

function (CONSUBSTANTIATION) -> CONSUBST A NTIATION
function (WRONGHEADED)       -> WRO N GHEADED
function (UNINTELLIGIBILITY) -> UNINTELL I GIBILITY
function (SUPERGLUE)         -> SUPERGLUE DOES NOT BALANCE

这是,因此最短的答案以字节为单位。


我们可以省略单个字母单词输出中的空格吗,例如function (A)-> A代替->`A`?
nimi

1
@nimi是的,您可以省略空格。
卡德,2015年

是否应该完全考虑单个字符输入的平衡?
用户

1
@someuser是的,因为两边的“权重”都是0。–
Kade

14
BALANCE DOES NOT BALANCE
Optimizer

Answers:


6

Pyth,49个字节

jd.xcz,Jhf!s*Vm-Cd64zr_TlzUzhJ,z"DOES NOT BALANCE

示范。

说明:

jd.xcz,Jhf!s*Vm-Cd64zr_TlzUzhJ,z"DOES NOT BALANCE

                                    Implicit: z = input(), d = ' '
         f                Uz        Filter T over range(len(z)).
              m     z               Map the characters in z to
               -Cd64                their ASCII values - 64.
            *V                      Vectorized multiplication by
                     r_Tlz          range(-T, len(z)).
                                    This is equivalent to putting the fulcrum at T.
           s                        Sum the weights.
          !                         Logical not - filter on sum = 0.
        h                           Take the first result.
                                    This throws an error if there were no results.
       J                            Save it to J.
      ,J                    hJ      Form the list [J, J+1].
    cz                              Chop z at those indices, 
                                    before and after the fulcrum.
  .x                                If no error was thrown, return the above.
                              ,z".. If an error was thrown, return [z, "DOES N..."]
jd                                  Join the result on spaces and print.

12

纯bash(无coreutils或其他实用程序),125

使用关于原点的矩来计算标准质心:

for((;i<${#1};w=36#${1:i:1}-9,m+=w,M+=w*++i)){ :;}
((M%m))&&echo $1 DOES NOT BALANCE||echo ${1:0:M/m-1} ${1:M/m-1:1} ${1:M/m}

测试输出:

$ for t in \
> STEAD \
> CONSUBSTANTIATION \
> WRONGHEADED \
> UNINTELLIGIBILITY \
> SUPERGLUE
> do ./wordbal.sh $t; done
S T EAD
CONSUBST A NTIATION
WRO N GHEADED
UNINTELL I GIBILITY
SUPERGLUE DOES NOT BALANCE
$ 

10

Python 3、124

w=input()
i=a=b=0
for c in w:n=ord(c)-64;a+=n;b+=n*i;i+=1
m=b//a
print(*[w[:m],w,w[m],"DOES NOT BALANCE",w[m+1:]][b%a>0::2])

此代码不会测试潜在的支点,而是找到“质心”并检查它是否为整数。它是通过将总质量a与位置加权质量相加而得出质量b中心的m=b/a。然后,它打印在position处分割的字符串m"DOES NOT BALANCE"[_::2]列表切片技巧选择的字符串plus 。



7

的JavaScript(ES6),211个 200 160字节

f=w=>{for(j=-w.length;j++;)if(![...w].reduce((p,v,i)=>p+(parseInt(v,36)-9)*(j+i),0))return w.slice(0,-j)+` ${w[-j]} `+w.slice(1-j);return w+` DOES NOT BALANCE`}

上一次尝试,200字节

感谢edc56和nderscore帮助我打高尔夫球

f=w=>{for(j=0,r=(a,z)=>[...a][z||`reverse`]().reduce((p,v,i)=>p+(parseInt(v,36)-9)*++i,0);j++<w.length;)if(r(a=w[s=`slice`](0,j))==r(b=w[s](j+1),s))return a+` ${w[j]} `+b;return w+` DOES NOT BALANCE`}

演示版

仅限于Firefox和Edge,因为它是ES6

f=w=>{for(j=1-w.length;j++;)if(!([...w].reduce((p,v,i)=>p+(parseInt(v,36)-9)*(j+i),0)))return w.slice(0,-j)+` ${w[-j]} `+w.slice(1-j);return w+` DOES NOT BALANCE`}

// DEMO
console.log = function(a) {
  document.body.innerHTML += a + "<br>";
}

console.log(f('STEAD'));
console.log(f('CONSUBSTANTIATION'));
console.log(f('WRONGHEADED'));
console.log(f('UNINTELLIGIBILITY'));
console.log(f('SUPERGLUE'));


3
尝试数组理解[for(v of w)v.charCode ....],对于字符串,它通常比.map短1个字节
edc65

@ edc65谢谢!每天学习新的东西
rink.attendant.15年

1
@ edc65数组理解技术现在已被推送到ES7草案中:(
nderscore 2015年

1
-1字节:j=0在调用中移动到charCodeAt:)
nderscore 2015年

6

C,236个 198 192 188 180 173字节

a,i,j,k,L;f(char*s){L=strlen(s);for(;i<L;i++){for(a=j=0;j<L;j++)a+=(s[j]-64)*(i-j);if(!a)break;}for(;k<L;k++)printf(k-i?"%c":" %c ",s[k]);if(a)printf(" DOES NOT BALANCE");}

用main()扩展:

#define p printf    
a,i,j,k,L;
f(char*s)
{
    L=strlen(s);
    for(;i<L;i++){
        for(a=j=0;j<L;j++)
            a+=(s[j]-64)*(i-j);
        if(!a)
            break;
    }
    for(;k<L;k++)
        printf(k-i?"%c":" %c ",s[k]);
    if(a)
        printf(" DOES NOT BALANCE");
}
// 83 bytes below
int main(int argc, char **argv)
{
    f(argv[1]);
    printf("\n");
}

验证:

$ ./a.out CONSUBSTANTIATION
CONSUBST A NTIATION
$ ./a.out WRONGHEADED
WRO N GHEADED
$ ./a.out A
 A 
$ ./a.out WRONG
WRONG DOES NOT BALANCE
$ ./a.out SUPERGLUE
SUPERGLUE DOES NOT BALANCE

1
我的解决方案与您的解决方案过于相似,无法发布答案,但我可以将其减少到146个字符:i,l=1,j;g(char*v){for(;v[i]&&l;++i)for(j=l=0;v[j];++j)l+=(i-j)*(v[j]-64);l?printf("%s DOES NOT BALANCE",v):printf("%.*s %c %s",--i,v,v[i],v+i+1);}注意:使用了未定义的行为:)
Cole Cameron

我认为您还是应该发布它。我还意识到我应该摆脱#define,因为它浪费了字节。
用户

我正在竭尽全力用PHP击败C,但我还有点
遗憾

6

CJam,50个字节

r_'@f-_ee::*:+\:+md"X DOES NOT BALANCEX"@?)/()@]S*

使用Java解释器,对于不平衡的单词,这会以STDERR错误退出。

如果您尝试使用CJam解释器中的代码,则只需忽略输出的最后一行即可。

理念

我的“原始想法”原来是@xnor在我之前几个小时发布的方法。尽管如此,它在这里:

给定一个值列表(v 0,…v n,当且仅当满足以下任意一个等效条件时,v_t才是列表的锚点:

  • 电视0 +…+ 1v t-1 == 1v t + 1 +…tv n

  • (0-t)v 0 +…+(n-t)v n == 0

  • 0v 0 +…+ nv n == t(v 0 +…+ v n

  • T:=(0V 0 + ... + NV Ñ)/(V 0 + ... + V Ñ是一个整数。

r     e# Read a whitespace separated token from STDIN.
_'@f- e# Push a copy and subtract '@' from each char (pushes code point - 64). 
_ee   e# Push a copy of the array of values and enumerate them.
::*   e# Multiply each value by its index.
:+    e# Add all results.
\:+   e# Add the unmodified values.
md    e# Perform modular division. Pushes quotient and residue.

"X DOES NOT BALANCEX"

@     e# Rotate the quotient on top of the string.
?     e# If the residue is 0, select the quotient. Otherwise, select the string.

在这一部分,我们开始对重载的运算符有点乐趣。

对于商,会发生以下情况:

)     e# Add 1 to the quotient.
/     e# Split the input string into chunks of that length.
(     e# Shift out the first chunk.
)     e# Pop the last character of the first chunk.
@     e# Rotate the rest of the string on top of the stack.
]S*   e# Wrap all three parts in an array and join them, separating by spaces.

对于字符串,发生这种情况:

)     e# Pop out the last char: "X DOES NOT BALANCE" 'X'
/     e# Split the remainder at X's: ["" " DOES NOT BALANCE"]
(     e# Shift out the first chunk: [" DOES NOT BALANCE"] ""
)     e# Pop out the last char.

此时,由于""没有最后一个字符,因此发生运行时错误。堆栈被打印,执行立即中止。


您链接的代码似乎有所不同(更好)?
aditsu

@aditsu:哦,链接错误。它更短更干净,是的,但是它具有尾随空格...
丹尼斯

5

朱莉娅122字节

s->(v=[int(i)-64for i=s];m=dot(v,1:length(s))/sum(v);m==int(m)?join([s[1:m-1],s[m],s[m+1:end]]," "):s*" DOES NOT BALANCE")

这将创建一个未命名函数,该函数接受字符串作为输入并返回字符串。要给它起个名字,例如f=s->...

我们将单词视为一维系统,需要为其寻找质心。质心计算为质点与其位置的点积除以系统的总质量。如果计算的中心是整数,则它对应于单词中的字母之一。否则,这个词将无法平衡。

取消+说明:

function f(s)
    # Create a vector of ASCII code points -- these are the "masses"
    v = [int(i)-64 for i in s]

    # Compute the center of mass, taking the locations to be the indices
    m = dot(v, 1:length(s)) / sum(v)

    # Check whether the center corresponds to a letter's position
    if m == int(m)
        join([s[1:m-1], s[m], s[m+1:end]], " ")
    else
        m * " DOES NOT BALANCE"
    end
end

例子:

julia> f("WRONG")
"WRONG DOES NOT BALANCE"

julia> f("STEAD")
"S T EAD"

julia> f("CONSUBSTANTIATION")
"CONSUBST A NTIATION"

5

PHP,249174字节

接受一个命令行参数。

<?for($i=-$l=strlen($w=$argv[1]);$i++;){for($k=$q=0;$l>$k;)$q+=($i+$k)*(ord($w[$k++])-64);$q?:exit(substr($w,0,-$i)." {$w[-$i]} ".substr($w,1-$i));}echo"$w DOES NOT BALANCE";

初步尝试:

<?function r($a){for($i=$q=0;strlen($a)>$i;){$q+=(ord($a[$i])-64)*++$i;}return$q;}for($i=0;$i++<strlen($w=$argv[1]);)(strlen($w)<2?exit($w):(r(strrev($a=substr($w,0,$i)))==r($b=substr($w,$i+1)))?exit("$a {$w[$i++]} $b"):0);echo"$w DOES NOT BALANCE";

4

Haskell,161135字节

a#b=a*(fromEnum b-64)
v=sum.zipWith(#)[1..]
h![]=h++" DOES NOT BALANCE"
h!(x:y)|v(reverse h)==v y=h++' ':x:' ':y|1<2=(h++[x])!y
f=([]!)

用法示例:

*Main> putStr $ unlines $ map f ["CONSUBSTANTIATION","WRONGHEADED","UNINTELLIGIBILITY","SUPERGLUE"]
CONSUBST A NTIATION
WRO N GHEADED
UNINTELL I GIBILITY
SUPERGLUE DOES NOT BALANCE

工作原理:f调用辅助函数!,该函数需要两个参数,即单词在给定位置的左右部分。如果两个部分的权重相等(函数v),则停止,或者递归调用自身,而右侧部分的第一个字母移至左侧。DOES NOT BALANCE如果右侧为空,则以消息结尾。


4

C,183134字节

h,i,a=1;c(char*s){for(;s[i++]&&a;)for(a=h=0;s[h];)a+=(s[h]-64)*(h++-i);printf(a?"%.*s DOES NOT BALANCE":"%.*s %c %s",i,s,s[--i],s+i);}

新版本说明:

像其他两个条目一样,它利用一侧的恒定加法和另一侧的减法来希望达到零,这表示平衡。我的原始输出已从第一个答案重新使用,尽管已稍作修改。

l,h,i,a,b;c(char*s){for(l=strlen(s);h++<l&&(a^b|!a);)for(i=a=b=0;i<l;i++)i==h?a=b,b=0:(b+=(s[i]-64)*abs(i-h));printf(a==b?"%.*s %c %s":"%.*s DOES NOT BALANCE",a==b?h:l,s,s[--h],s+h);}

旧版本说明:

第一个循环(h)是字符串长度的主要迭代器。第二个循环(i)累积(b),直到h == i。一旦发生这种情况,将(b)存储在(a)中,重置为0,然后继续直到到达字符串的末尾,将(a)与(b)进行比较。如果存在匹配项,则主迭代器的循环将中断,并输出输出。


3

红宝石175

F=->s{v=->s{(0...s.size).map{|i|(i+1)*(s[i].ord-64)}.inject :+}
r="#{s} DOES NOT BALANCE"
(0...s.size).map{|i|b,a=s[0...i],s[i+1..-1]
v[b.reverse]==v[a]&&r=b+" #{s[i]} "+a}
r}

在线测试:http//ideone.com/G403Fv

这是一个非常简单的Ruby实现。这是可读的程序:

F=-> word {
  string_value = -> str {
    (0...str.size).map{|i|(i+1) * (str[i].ord - 64)}.inject :+
  }

  result = "#{word} DOES NOT BALANCE"

  (0...word.size).map {|i|
    prefix, suffix = word[0...i], word[i+1..-1]
    if string_value[prefix.reverse] == string_value[suffix]
      result = prefix + " #{word[i]} " + suffix
    end
  }

  result
}

3

R,190字节

作为未命名的函数。我想我可以再得到一些,但这必须等待。

function(A){D=colSums(B<-(as.integer(charToRaw(A))-64)*outer(1:(C=nchar(A)),1:C,'-'));if(!length(E<-which(B[,D==0]==0)))cat(A,'DOES NOT BALANCE')else cat(substring(A,c(1,E,E+1),c(E-1,E,C)))}

简要介绍一下

function(A){
D=colSums(  #column sums of the outer function * character values
    B<-(
       as.integer(charToRaw(A))-64)    # character values
       * outer(1:(C=nchar(A)),1:C,'-') # matrix of ranges eg -3:2, -1:4, etc
       )
if(!length(
    E<-which(B[,D==0]==0) # where the colsum = 0, get the index of the zero
    ))
    cat(A,'DOES NOT BALANCE')
else 
    cat(substring(A,c(1,E,E+1),c(E-1,E,C)))  #cat the substrings
}

它不会在末尾添加换行符。

测试运行

> f=
+ function(A){D=colSums(B<-(as.integer(charToRaw(A))-64)*outer(1:(C=nchar(A)),1:C,'-'));if(!length(E<-which(B[,D==0]==0)))cat(A,'DOES NOT BALANCE')else cat(substring(A,c(1,E,E+1),c(E-1,E,C)))}
> 
> f('CONSUBSTANTIATION')
CONSUBST A NTIATION
> f('WRONGHEADED')
WRO N GHEADED
> f('UNINTELLIGIBILITY')
UNINTELL I GIBILITY
> f('SUPERGLUE')
SUPERGLUE DOES NOT BALANCE
> 

2

C,142字节

归功于一些击败我的用户:)

i,l=1,j;g(char*v){for(;v[i]&&l;++i)for(j=l=0;v[j];++j)l+=(i-j)*(v[j]-64);printf(l?"%.*s DOES NOT BALANCE":"%.*s %c %s",l?i:--i,v,v[i],v+i+1);}

1

Java,240字节

String b(String s){for(int i=-1,a=s.length(),l=0,r,m;++i<a;){for(r=i;--r>=0;l+=(s.charAt(r)-64));for(m=r=0;++m+i<a;r+=(s.charAt(m+i)-64)*m);if(l==r)return s.substring(0,i)+" "+s.charAt(i)+" "+s.substring(i+1);}return s+" DOES NOT BALANCE";}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.