Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/clojure/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Clojure 在给定的列数宽度随机宽度中100%拆分_Clojure - Fatal编程技术网

Clojure 在给定的列数宽度随机宽度中100%拆分

Clojure 在给定的列数宽度随机宽度中100%拆分,clojure,Clojure,我想在给定数量的列中100%拆分。但是列的宽度应该是随机的。这是我的第一次尝试。但是它是静态的,只有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

我想在给定数量的列中100%拆分。但是列的宽度应该是随机的。这是我的第一次尝试。但是它是静态的,只有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))))
    

    效果很好。你有办法把一个矩形分割成一定数量的片段吗?@MrD是的,我有办法把一个矩形分割成一定数量的图片。我不知道如何更改代码来处理二维的矩形。你能给我一个提示吗?是的,我能给你一个提示。你的提示是什么?