如何用ruby统计数组或哈希中不同元素的个数

Python014

如何用ruby统计数组或哈希中不同元素的个数,第1张

得到不同数据的值:

%w(a b c a c d).uniq

得到各个元素出现的个数:

count_hash = {}

%w(a b c a c d).each do |item|

key = item.to_sym

if count = count_hash[key]

count_hash[key] = count + 1

else

count_hash[key] = 1

end

end

数组

array = [[1],[2],[3],[0],[1,2],[1,0],[0,1]]

希望排序整个数组,先按照数组 元素个数 ,如果个数相同再 按照首个元素大小

array.sort_by {|a| [a.size, a[0]] }

public static void main(String[] args)

{

int [] num =new int[]{1,2,3,4,5,6,7,8,9,10}

Scanner input = new Scanner(System.in)

int temp=0

System.out.println("请输入你要删除的元素:")

int de=input.nextInt()

for(int i =0i<num.lengthi++)

{

if(num[i]==de)

{

for(int j = ij<num.length-1j++)

{

num[j]=num[j+1]

}

temp=1

break

}

}

if(temp==1)

{

System.out.println("删除此对象后数组值为:")

for(int i = 0i<num.length-1i++)

{

System.out.print(num[i]+"\t")

}

}

else

{

System.out.println("未找到你要删除的对象")

}

}