一个很简单的java写的循环,请问如何用ruby实现?对ruby的二维数组完全没概念啊!(Java,Ruby)

windrain_p 2015-01-14 12:05:59
java代码:
package com.ye9;
import java.util.Scanner;
//定义类
public class Yhsj {
public static void main(String[] args) {
new Yhsj().init(); //调用方法
}

//实现方法
public void init(){
int len;
System.out.println("Please enter a number:");
Scanner scan = new Scanner(System.in);
len = scan.nextInt(); //由键盘输入所需的数字

int [][] str =new int[len][len];
for(int i=0;i<len;i++){
for(int j = 0;j <= i;j++){
if(i == 0 ||i == 1 ||j == 0){
str[i][j]=1;
}

else if (i > 0 && j > 0){
str[i][j]=str[i-1][j-1]+str[i-1][j];
}
System.out.print(str[i][j] + " ");
}//end for j
System.out.println();
}//end for i
}
}


结果:Please enter a number:
10
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1

Ruby小白求Ruby实现代码,十分感谢!
...全文
6826 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
yuhan20081021 2016-02-18
  • 打赏
  • 举报
回复
就是ruby实现杨辉三角呗
sevk 2015-08-05
  • 打赏
  • 举报
回复


#!/usr/bin/env ruby                                         
# -*- coding: utf-8 -*-

class Fixnum
  def yhsj
    arr = Array.new(self)
    arr.fill do |i|
      Array.new(i+1).fill do |t|
        if i==0 || i==1 || t==0 || t == i
          1
        else
          arr[i-1][t-1]  + arr[i-1][t]
        end
      end
    end
  end
end

print "Please enter a number: "
len = gets.to_i #由键盘输入所需的数字
puts len.yhsj.map { |e| e.join(" ") }
                                                            


funnyone 2015-07-24
  • 打赏
  • 举报
回复
see

def yhsj
	len = gets.to_i
	arr = Array.new(len)
	arr.fill do |i|
		Array.new(i+1).fill do |t|
			if i==0 || i==1 || t==0 || t == i
				1
			else
				arr[i-1][t-1]  + arr[i-1][t]
			end
		end
	end
end

puts yhsj.map { |e| e.join(" ") }


2,763

社区成员

发帖
与我相关
我的任务
社区描述
Web 开发 Ruby/Rails
社区管理员
  • Ruby/Rails社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧