Skip to content

n个数值是否可以组成n边形

n个数值是否可以组成n边形。

示例

示例1

输入:[1, 1, 2]

输出:false

示例2

输入:[1, 2, 2]

输出:true

示例3

输入:[1, 1, 1, 4]

输出:false

示例4

输入:[1, 2, 3, 4]

输出:true

代码

javascript
// n个数值是否可以组成n边形

export function nNumberCanNPolygon(nNumber) {
  const nNumberLength = nNumber.length
  if (nNumberLength < 3) return false
  const nNumberSort = nNumber.sort((a, b) => a - b)
  let sum = 0
  for (let index = 0; index < nNumberLength - 1; index++) {
    sum += nNumberSort[index]
  }
  if (sum <= nNumberSort[nNumberLength - 1]) return false
  return true
};
typescript
// n个数值是否可以组成n边形

export function nNumberCanNPolygon(nNumber: number[]): boolean {
  const nNumberLength = nNumber.length
  if (nNumberLength < 3) return false
  const nNumberSort = nNumber.sort((a, b) => a - b)
  let sum = 0
  for (let index = 0; index < nNumberLength - 1; index++) {
    sum += nNumberSort[index]
  }
  if (sum <= nNumberSort[nNumberLength - 1]) return false
  return true
};

测试代码

ts
import { expect, test } from 'vitest'
import { nNumberCanNPolygon } from './typescript.ts'
import { nNumberCanNPolygon as nNumberCanNPolygonJs } from './javascript.js'

test(`[1, 1, 2] toBe false`, () => {
  expect(nNumberCanNPolygon([1, 1, 2])).toBe(false)
})

test(`[1, 2, 2] toBe true`, () => {
  expect(nNumberCanNPolygon([1, 2, 2])).toBe(true)
})

test(`[1, 1, 1, 4] toBe false`, () => {
  expect(nNumberCanNPolygon([1, 1, 1, 4])).toBe(false)
})

test(`[1, 2, 3, 4] toBe true`, () => {
  expect(nNumberCanNPolygon([1, 2, 3, 4])).toBe(true)
})


test(`[1, 1, 2] toBe false`, () => {
  expect(nNumberCanNPolygonJs([1, 1, 2])).toBe(false)
})

test(`[1, 2, 2] toBe true`, () => {
  expect(nNumberCanNPolygonJs([1, 2, 2])).toBe(true)
})

test(`[1, 1, 1, 4] toBe false`, () => {
  expect(nNumberCanNPolygonJs([1, 1, 1, 4])).toBe(false)
})

test(`[1, 2, 3, 4] toBe true`, () => {
  expect(nNumberCanNPolygonJs([1, 2, 3, 4])).toBe(true)
})