Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions logic-exercises/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": [],
Expand Down
29 changes: 29 additions & 0 deletions logic-exercises/src/countNegatives.ts
Original file line number Diff line number Diff line change
@@ -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
}
23 changes: 23 additions & 0 deletions logic-exercises/tests/countNegatives.test.ts
Original file line number Diff line number Diff line change
@@ -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)
})

})