将矢量转换为 2D 网格显示:如何找到一个(整数)面积与给定整数最匹配的矩形?

  • 本文关键字:整数 一个 2D 转换 网格 显示 何找 r
  • 更新时间 :
  • 英文 :


hans rosling的灵感,https://www.tel.com/talks/hans_rosling_shows_the_bestrongtats_you_ve_ve_ve_ever_seen#t-103612

我试图以易于理解和有趣的图形形式表示统计信息。作为这样做的一步,我想解决这个问题。

给定一个Interger X,我想找到一个矩形R,其区域(l * w)最紧密地匹配X/

例如,如果X=7,则R应该具有l=2&w=4(区域= 8)。

我尝试了:

len1 <- 7
m1 <-  ceiling(sqrt(len1))
m1

m2 <-  ceiling(len1 /m1)
m2

,但这给出了3 * 3,而最佳解决方案是2 *4。

这对您的示例有效,并且可能在一般中起作用

# get the first dimension
dim1 <- floor(sqrt(len1))
# fill out the second dimension
dim2 <- (len1 %/% dim1 + (len1 %% dim1 != 0))

要测试,将其放入函数

dimGet <- function(x) {
  dim1 <- floor(sqrt(x))
  dim2 <- (x %/% dim1 + (x %% dim1 != 0))
  return(c(dim1=dim1, dim2=dim2))
}

现在,将其与1到10

运行
sapply(1:10, dimGet)
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
dim1    1    1    1    2    2    2    2    2    3     3
dim2    1    2    3    2    3    3    4    4    3     4

我不太清楚您想要什么,但这可能起作用

getrect = function(x = 7){
    f = floor(sqrt(x))
    if(f^2 == x){
        return(c(f,f))
    }
    d = max(2,(f - 500)):(f + 500) #decrease 500 to improve speed, increase 500 to improve accuracy
    d = data.frame(t(combn(d,2)))   
    d$M = d$X1 * d$X2
    d = d[d$M >= x,]
    d$diff = abs(d$X1-d$X2)
    d$M_diff = abs(d$M-x)
    d = d[with(d, order(M_diff, diff)), ]
    return( c(d[1,1], d[1,2]) )
}
sapply(1:25, getrect)
#     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13] [,14] [,15] [,16] [,17] [,18] [,19] [,20] [,21] [,22] [,23] [,24] [,25]
#[1,] 1    2    2    2    2    2    2    2    3    2     3     3     3     3     3     4     3     3     4     4     3     4     4     4     5    
#[2,] 1    3    3    2    3    3    4    4    3    5     4     4     5     5     5     4     6     6     5     5     7     6     6     6     5    

最新更新