[英]Split 100% in a given number of columns width random width
我想在給定數量的列中拆分 100%。 但列的寬度應該是隨機的。 這是我的第一次嘗試。 但它是 static 到 5 列。 有什么想法讓它充滿活力嗎?
(defn create-columns []
(let [col1 (int (random/number 14 26))
col2 (int (random/number 14 26))
col3 (int (random/number 14 26))
col4 (int (random/number 14 26))
col5 (- 100 (+ col1 col2 col3 col4))]
[{:width col1, :left 0}
{:width col2, :left (int col1)}
{:width col3, :left (+ col1 col2)}
{:width col4, :left (+ col1 col2 col3)}
{:width col5, :left (+ col1 col2 col3 col4)}]))
結果應該像
[{:width 23, :left 0} {:width 24, :left 23} {:width 23, :left 47} {:width 14, :left 70} {:width 16, :left 84}]
和想法?
這是一個表示為惰性序列操作的算法:
:left
和:width
。這是執行此操作的代碼。
(defn random-cols [total col-count]
(->> #(rand-int (inc total))
(repeatedly (dec col-count))
(into [0 total])
sort
(partition 2 1)
(map (fn [[left right]] {:left left :width (- right left)}))))
(random-cols 100 3)
;; => ({:left 0, :width 21} {:left 21, :width 24} {:left 45, :width 55})
這可以生成寬度小至 0 的列,但是將列限制為某個最小寬度可能是您可能想要做的事情,盡管問題沒有說明這一點:
(defn random-cols-constrained [total col-count min-width]
(let [widths (map #(+ min-width (:width %))
(random-cols (- total (* col-count min-width))
col-count))]
(map (fn [w l] {:width w :left l})
widths
(reductions + 0 widths))))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.