Skip to content

Instantly share code, notes, and snippets.

@godfat
Created Mar 14, 2009
Embed
What would you like to do?
Star
{-
3
345
34567
345
3
-}
module Main where
star :: Integer -> String
star max = tail $ to_s rectangle where
rectangle :: [[String]]
rectangle = [spaces i ++ row i | i <- [0..max-1]]
spaces i = map (\x->" ") [0..abs (mid-i-1) - 1]
mid = max `div` 2 + 1
row :: Integer -> [String]
row n = [ show i | i <- [mid..( max+mid-2 * abs (mid-n-1) ) - 1] ]
to_s = foldr (\l s -> ("\n" ++ concat l ++ s)) ""
main = putStrLn $ star 5
(*
3
345
34567
345
3
*)
(*
#load "dynlink.cma";;
#load "camlp4/camlp4o.cma";;
#load "camlp4/Camlp4Parsers/Camlp4ListComprehension.cmo";;
*)
let rec range i j = if i > j then [] else i :: range (i+1) j;;
let star max =
let mid = max / 2 + 1 in
let spaces i = List.map (fun x -> " ") (range 0 (abs (mid-i-1) - 1)) in
let row n = List.map string_of_int
(range mid (( max+mid-2 * abs (mid-n-1) ) - 1)) in
let rectangle = List.map (fun i -> List.append (spaces i) (row i))
(range 0 (max-1)) in
let to_s = List.fold_right (fun l s -> "\n" ^ String.concat "" l ^ s) in
let result = to_s rectangle "" in
String.sub result 1 (String.length result - 1);;
print_string ((star 5) ^ "\n");;
# 3
# 345
# 34567
# 345
# 3
from functools import reduce
class Star:
def __init__(self, max):
self.max = max
self.mid = max // 2 + 1
self.result = [ [' '] * abs(self.mid-i-1) +
list(map(lambda x: str(x), list(self.row(i)))) for i in range(max) ]
def row(self, n):
return range(self.mid, self.max + self.mid - 2 * abs(self.mid - n - 1))
def __str__(self):
return reduce(lambda s,l: "\n"+''.join(l)+str(s), self.result, '')[1:]
print(Star(5))
=begin
3
345
34567
345
3
=end
class Star
attr_reader :max, :mid, :result
def initialize max
@max = max
@mid = max / 2 + 1
@result = (0...max).map{ |i| ([' '] * (mid-i-1).abs) + row(i) }
end
def row n
(mid...max + mid - 2 * (mid - n - 1).abs).to_a
end
def to_s
result.inject(''){ |s, l| "\n" + l.join + s }[1..-1]
end
end
puts Star.new((ARGV.first || 5).to_i)
/*
3
345
34567
345
3
*/
class Star(max: Int){
val mid = max / 2 + 1
def row(n: Int): List[Int] =
for (i <- List.range(mid, max + mid - 2 * (mid - n - 1).abs)) yield i
val result =
for (i <- List.range(0, max)) yield
List.range(0, (mid - i - 1).abs).map{s=>' '} ++ row(i)
override def toString: String =
result.foldRight(""){
(l, s) => "\n" + l.mkString + s
}.drop(1).toString
}
println(new Star(5))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment