importscala.collection.mutable.ListBuffer
val list =new ListBuffer[Int]()val n =51(1 to n by 2).foreach(list.append(_))(n -2 to 1 by -2).foreach(list.append(_))val rdd = sc.makeRDD(list)val rdd1 = rdd.map(i =>" "*((n - i)/2)+"*"* i)
rdd1.collect.foreach(println)
执行代码,查看结果
二、利用Java完成
导入所需类
(一)右半菱形
List<Integer> data =Arrays.asList(1,3,5,7,9,11,13,15,17,19,21,19,17,15,13,11,9,7,5,3,1);
data ==>[1,3,5,7,9,11,13,15,17,19,21,19,17,15,13,11,9,7,5,3,1]
data.stream().map(i ->"*".repeat(i)).collect(Collectors.toList()).forEach(System.out::println)
执行代码,查看结果
(二)左半菱形
List<Integer> data =Arrays.asList(1,3,5,7,9,11,13,15,17,19,21,19,17,15,13,11,9,7,5,3,1);
data ==>[1,3,5,7,9,11,13,15,17,19,21,19,17,15,13,11,9,7,5,3,1]
data.stream().map(i ->" ".repeat(21- i)+"*".repeat(i)).collect(Collectors.toList()).forEach(System.out::println)
执行代码,查看结果
(三)完整菱形
List<Integer> data =Arrays.asList(1,3,5,7,9,11,13,15,17,19,21,19,17,15,13,11,9,7,5,3,1);
data ==>[1,3,5,7,9,11,13,15,17,19,21,19,17,15,13,11,9,7,5,3,1]
data.stream().map(i ->" ".repeat((21- i)/2)+"*".repeat(i)).collect(Collectors.toList()).forEach(System.out::println)
执行代码,查看结果
(四)输出任意大菱形
由用户确定n
List<Integer> list =newArrayList<>();int n =51;for(int i =1; i <= n; i +=2) list.add(i);for(int i = n -2; i >=1; i -=2) list.add(i);
list.stream().map(i ->" ".repeat((n - i)/2)+"*".repeat(i)).collect(Collectors.toList()).forEach(System.out::println)
执行代码,查看结果
三、利用Scala完成
(一)右半菱形
val list = List(1,3,5,7,9,11,13,15,17,19,21,19,17,15,13,11,9,7,5,3,1)val list1 = list.map("*"* _)
list1.foreach(println)
执行代码,查看结果
(二)左半菱形
val list = List(1,3,5,7,9,11,13,15,17,19,21,19,17,15,13,11,9,7,5,3,1)val list1 = list.map(i =>" "*(21- i )+"*"* i)
list1.foreach(println)
执行代码,查看结果
(三)完整菱形
val list = List(1,3,5,7,9,11,13,15,17,19,21,19,17,15,13,11,9,7,5,3,1)val list1 = list.map(i =>" "*((21- i )/2)+"*"* i)
list1.foreach(println)
执行代码,查看结果
(四)输出任意大菱形
由用户确定n
importscala.collection.mutable.ListBufferval list =new ListBuffer[Int]()val n =51(1 to n by 2).foreach(list.append(_))(n -2 to 1 by -2).foreach(list.append(_))
list.map(i =>" "*((n - i)/2)+"*"* i).foreach(println)