From 6ca8d1129759c3ff40429edb8d233498a73b3719 Mon Sep 17 00:00:00 2001 From: Nicole Date: Thu, 1 Apr 2021 11:01:14 -0300 Subject: [PATCH] exercicio e testes --- logic-exercises/package.json | 1 + logic-exercises/src/countNegatives.ts | 29 ++++++++++++++++++++ logic-exercises/tests/countNegatives.test.ts | 23 ++++++++++++++++ 3 files changed, 53 insertions(+) create mode 100644 logic-exercises/src/countNegatives.ts create mode 100644 logic-exercises/tests/countNegatives.test.ts diff --git a/logic-exercises/package.json b/logic-exercises/package.json index 28b8248..3fb1a2e 100644 --- a/logic-exercises/package.json +++ b/logic-exercises/package.json @@ -12,6 +12,7 @@ "ex6": "tsc && node ./build/src/lonelyNumber.js", "ex7": "tsc && node ./build/src/isAnagram.js", "ex8": "tsc && node ./build/src/twoSum.js", + "ex9": "tsc && node ./build/src/countNegatives.js", "test": "node ./node_modules/jest/bin/jest.js" }, "keywords": [], diff --git a/logic-exercises/src/countNegatives.ts b/logic-exercises/src/countNegatives.ts new file mode 100644 index 0000000..6fda36f --- /dev/null +++ b/logic-exercises/src/countNegatives.ts @@ -0,0 +1,29 @@ +type Matrix = number[][] + +export const countNegatives = (m: Matrix): number => { + let negatives: number[] = [] + for (const row of m) { + for (const element of row) { + if (element < 0) { + negatives.push(element) + } + } + } + return negatives.length +} + +export const countNegativesOptmized = (m: Matrix): number => { + const [row, column] = [m.length, m[0].length] + let negativeCount = 0 + let i = row - 1 + let j = 0 + while (j < column && i >= 0) { + if (m[i][j] < 0) { + negativeCount += column - j + i-- + } else { + j++ + } + } + return negativeCount +} \ No newline at end of file diff --git a/logic-exercises/tests/countNegatives.test.ts b/logic-exercises/tests/countNegatives.test.ts new file mode 100644 index 0000000..16b0bfd --- /dev/null +++ b/logic-exercises/tests/countNegatives.test.ts @@ -0,0 +1,23 @@ +import { countNegatives } from '../src/countNegatives' + +describe("Testing countNegatives", () => { + it("Should return 8", () => { + + const result = countNegatives([[4,3,2,-1],[3,2,1,-1],[1,1,-1,-2],[-1,-1,-2,-3]]) + + expect(result).toBe(8) + }) + it("Should return o", () => { + + const result = countNegatives([[3,2],[1,0]]) + + expect(result).toBe(0) + }) + it("Should return 3", () => { + + const result = countNegatives([[1,-1],[-1,-1]]) + + expect(result).toBe(3) + }) + +}) \ No newline at end of file