如何在J中重构它? [英] How to refactor this in J?

查看:95
本文介绍了如何在J中重构它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对欧拉1号项目的新手解决方案

My newbie solution to Project Euler #1

+/((0=3|1+i.1000-1) +. (0=5|1+i.1000-1)) * (1+i.1000-1)

我知道可以将其重构并转换为功能,我不知道该怎么做,我必须阅读所有实验室的知识以了解它.

I know that this can be refactored, and transformed into a function, i don't know how to do it, and I would have to read all the labs to learn it.

推荐答案

不必处理零",因为加零不会改变答案,因此您可以使用i.生成数字列表小于1000,例如:

It isn't necessary to "handle zero" because adding zero won't change the answer so you can just use i. to generate your list of numbers below 1000, for example:

   i. 10
0 1 2 3 4 5 6 7 8 9

J最适合数组,因此您应该能够同时要求3和5的残差(|),可以使用rank(")来控制将参数提供给残差的方式:

J works best with arrays so you should be able to ask for the residue (|) of 3 and 5 at the same time, you can use rank (") to control how the arguments are fed to residue:

   3 5 |"0 1 i. 10
0 1 2 0 1 2 0 1 2 0
0 1 2 3 4 0 1 2 3 4

|"0 1表示一次将一个项目的左侧参数提供给|,而一次一次将其正确的参数提供给|.由于右参数仅由一行组成,因此会重复地馈送到左参数的每个项目.

The |"0 1 says to feed the left argument to | an-item-at-a-time while feeding the right arguments a-line-at-a-time. Because the right argument only consists of one line, it is fed repeatedly to each of the left argument items.

现在我们可以对整个数组执行0=:

Now we can do the 0= to the whole array:

   0 = 3 5 |"0 1 i. 10
1 0 0 1 0 0 1 0 0 1
1 0 0 0 0 1 0 0 0 0

在数组的两个项目(行)之间插入一个OR条件:

Insert an OR condition between the two items (lines) of the array:

  +./ 0 = 3 5 |"0 1 i. 10
1 0 0 1 0 1 1 0 0 1

获取列表/向量中每个1的索引:

Get the index of each 1 in the list/vector:

  I. +./ 0 = 3 5 |"0 1 i. 10
0 3 5 6 9

总和:

 +/ I. +./ 0 = 3 5 |"0 1 i. 10

23

您可以很轻松地使它成为显式函数/动词:

You can make this an explicit function/verb fairly easily:

   euler1=: verb define
+/ I. +./ 0 = 3 5 |"0 1 i. y
)

或者一旦您掌握了默认的J,您就可以定义:

Or once you get the hang of tacit J you could define:

   euler1=: +/@I.@(+./)@(0 = 3 5 |"0 1 i.)

这篇关于如何在J中重构它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆