Skip to content

Add square-root #1587

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Apr 28, 2025
Merged
Show file tree
Hide file tree
Changes from 2 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
8 changes: 8 additions & 0 deletions config.json
Original file line number Diff line number Diff line change
Expand Up @@ -416,6 +416,14 @@
"time"
]
},
{
"slug": "square-root",
"name": "Square Root",
"uuid": "bf4a0802-334b-4ed7-9ade-a3ef5fa6878e",
"practices": [],
"prerequisites": [],
"difficulty": 2
},
{
"slug": "reverse-string",
"name": "Reverse String",
Expand Down
18 changes: 18 additions & 0 deletions exercises/practice/square-root/.docs/instructions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Instructions

Your task is to calculate the square root of a given number.

- Try to avoid using the pre-existing math libraries of your language.
- As input you'll be given a positive whole number, i.e. 1, 2, 3, 4…
- You are only required to handle cases where the result is a positive whole number.

Some potential approaches:

- Linear or binary search for a number that gives the input number when squared.
- Successive approximation using Newton's or Heron's method.
- Calculating one digit at a time or one bit at a time.

You can check out the Wikipedia pages on [integer square root][integer-square-root] and [methods of computing square roots][computing-square-roots] to help with choosing a method of calculation.

[integer-square-root]: https://en.wikipedia.org/wiki/Integer_square_root
[computing-square-roots]: https://en.wikipedia.org/wiki/Methods_of_computing_square_roots
10 changes: 10 additions & 0 deletions exercises/practice/square-root/.docs/introduction.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# Introduction

We are launching a deep space exploration rocket and we need a way to make sure the navigation system stays on target.

As the first step in our calculation, we take a target number and find its square root (that is, the number that when multiplied by itself equals the target number).

The journey will be very long.
To make the batteries last as long as possible, we had to make our rocket's onboard computer very power efficient.
Unfortunately that means that we can't rely on fancy math libraries and functions, as they use more power.
Instead we want to implement our own square root calculation.
19 changes: 19 additions & 0 deletions exercises/practice/square-root/.meta/config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"authors": [
"BNAndras"
],
"files": {
"solution": [
"square-root.ts"
],
"test": [
"square-root.test.ts"
],
"example": [
".meta/proof.ci.ts"
]
},
"blurb": "Given a natural radicand, return its square root.",
"source": "wolf99",
"source_url": "https://github.com/exercism/problem-specifications/pull/1582"
}
12 changes: 12 additions & 0 deletions exercises/practice/square-root/.meta/proof.ci.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
export function squareRoot(radicand: number): number {
if (radicand === 1) {
return 1
}

let guess = Math.floor(radicand / 2)
for (let i = 0; i < 10; i++) {
guess = Math.floor((guess + radicand / guess) / 2)
}

return guess
}
28 changes: 28 additions & 0 deletions exercises/practice/square-root/.meta/tests.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# This is an auto-generated file.
#
# Regenerating this file via `configlet sync` will:
# - Recreate every `description` key/value pair
# - Recreate every `reimplements` key/value pair, where they exist in problem-specifications
# - Remove any `include = true` key/value pair (an omitted `include` key implies inclusion)
# - Preserve any other key/value pair
#
# As user-added comments (using the # character) will be removed when this file
# is regenerated, comments can be added via a `comment` key.

[9b748478-7b0a-490c-b87a-609dacf631fd]
description = "root of 1"

[7d3aa9ba-9ac6-4e93-a18b-2e8b477139bb]
description = "root of 4"

[6624aabf-3659-4ae0-a1c8-25ae7f33c6ef]
description = "root of 25"

[93beac69-265e-4429-abb1-94506b431f81]
description = "root of 81"

[fbddfeda-8c4f-4bc4-87ca-6991af35360e]
description = "root of 196"

[c03d0532-8368-4734-a8e0-f96a9eb7fc1d]
description = "root of 65025"
7 changes: 7 additions & 0 deletions exercises/practice/square-root/.vscode/extensions.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"recommendations": [
"arcanis.vscode-zipfs",
"dbaeumer.vscode-eslint",
"esbenp.prettier-vscode"
]
}
7 changes: 7 additions & 0 deletions exercises/practice/square-root/.vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"cSpell.words": ["exercism"],
"search.exclude": {
"**/.yarn": true,
"**/.pnp.*": true
}
}
3 changes: 3 additions & 0 deletions exercises/practice/square-root/.yarnrc.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
compressionLevel: mixed

enableGlobalCache: true
5 changes: 5 additions & 0 deletions exercises/practice/square-root/babel.config.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
module.exports = {
// eslint-disable-next-line @typescript-eslint/no-require-imports
presets: [[require('@exercism/babel-preset-typescript'), { corejs: '3.38' }]],
plugins: [],
}
26 changes: 26 additions & 0 deletions exercises/practice/square-root/eslint.config.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// @ts-check

import tsEslint from 'typescript-eslint'
import config from '@exercism/eslint-config-typescript'
import maintainersConfig from '@exercism/eslint-config-typescript/maintainers.mjs'

export default [
...tsEslint.config(...config, {
files: ['.meta/proof.ci.ts', '.meta/exemplar.ts', '*.test.ts'],
extends: maintainersConfig,
}),
{
ignores: [
// # Protected or generated
'.git/**/*',
'.vscode/**/*',

//# When using npm
'node_modules/**/*',

// # Configuration files
'babel.config.cjs',
'jest.config.cjs',
],
},
]
22 changes: 22 additions & 0 deletions exercises/practice/square-root/jest.config.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
module.exports = {
verbose: true,
projects: ['<rootDir>'],
testMatch: [
'**/__tests__/**/*.[jt]s?(x)',
'**/test/**/*.[jt]s?(x)',
'**/?(*.)+(spec|test).[jt]s?(x)',
],
testPathIgnorePatterns: [
'/(?:production_)?node_modules/',
'.d.ts$',
'<rootDir>/test/fixtures',
'<rootDir>/test/helpers',
'__mocks__',
],
transform: {
'^.+\\.[jt]sx?$': 'babel-jest',
},
moduleNameMapper: {
'^(\\.\\/.+)\\.js$': '$1',
},
}
38 changes: 38 additions & 0 deletions exercises/practice/square-root/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
{
"name": "@exercism/typescript-square-root",
"version": "1.0.0",
"description": "Exercism exercises in Typescript.",
"private": true,
"repository": {
"type": "git",
"url": "https://github.com/exercism/typescript"
},
"type": "module",
"engines": {
"node": "^18.16.0 || >=20.0.0"
},
"devDependencies": {
"@exercism/babel-preset-typescript": "^0.6.0",
"@exercism/eslint-config-typescript": "^0.8.0",
"@jest/globals": "^29.7.0",
"@types/node": "~22.7.6",
"babel-jest": "^29.7.0",
"core-js": "~3.38.1",
"eslint": "^9.12.0",
"expect": "^29.7.0",
"jest": "^29.7.0",
"prettier": "^3.3.3",
"tstyche": "^2.1.1",
"typescript": "~5.6.3",
"typescript-eslint": "^8.10.0"
},
"scripts": {
"test": "corepack yarn node test-runner.mjs",
"test:types": "corepack yarn tstyche",
"test:implementation": "corepack yarn jest --no-cache --passWithNoTests",
"lint": "corepack yarn lint:types && corepack yarn lint:ci",
"lint:types": "corepack yarn tsc --noEmit -p .",
"lint:ci": "corepack yarn eslint . --ext .tsx,.ts"
},
"packageManager": "[email protected]"
}
34 changes: 34 additions & 0 deletions exercises/practice/square-root/square-root.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { describe, it, expect, xit } from '@jest/globals'
import { squareRoot } from './square-root.ts'

describe('Square Root', () => {
// Root of 1
it('root of 1', () => {
expect(squareRoot(1)).toEqual(1)
})

// Root of 4
xit('root of 4', () => {
expect(squareRoot(4)).toEqual(2)
})

// Root of 25
xit('root of 25', () => {
expect(squareRoot(25)).toEqual(5)
})

// Root of 81
xit('root of 81', () => {
expect(squareRoot(81)).toEqual(9)
})

// Root of 196
xit('root of 196', () => {
expect(squareRoot(196)).toEqual(14)
})

// Root of 65025
xit('root of 65025', () => {
expect(squareRoot(65025)).toEqual(255)
})
})
3 changes: 3 additions & 0 deletions exercises/practice/square-root/square-root.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export function squareRoot(radicand: unknown): unknown {
throw new Error('Remove this statement and implement this function')
}
111 changes: 111 additions & 0 deletions exercises/practice/square-root/test-runner.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
#!/usr/bin/env node

/**
* 👋🏽 Hello there reader,
*
* It looks like you are working on this solution using the Exercism CLI and
* not the online editor. That's great! The file you are looking at executes
* the various steps the online test-runner also takes.
*
* @see https://github.com/exercism/typescript-test-runner
*
* TypeScript track exercises generally consist of at least two out of three
* types of tests to run.
*
* 1. tsc, the TypeScript compiler. This tests if the TypeScript code is valid
* 2. tstyche, static analysis tests to see if the types used are expected
* 3. jest, runtime implementation tests to see if the solution is correct
*
* If one of these three fails, this script terminates with -1, -2, or -3
* respectively. If it succeeds, it terminates with exit code 0.
*
* @note you need corepack (bundled with node LTS) enabled in order for this
* test runner to work as expected. Follow the installation and test
* instructions if you see errors about corepack or pnp.
*/

import { execSync } from 'node:child_process'
import { existsSync, readFileSync } from 'node:fs'
import { exit } from 'node:process'
import { URL } from 'node:url'

/**
* Before executing any tests, the test runner attempts to find the
* exercise config.json file which has metadata about which types of tests
* to run for this solution.
*/
const metaDirectory = new URL('./.meta/', import.meta.url)
const exercismDirectory = new URL('./.exercism/', import.meta.url)
const configDirectory = existsSync(metaDirectory)
? metaDirectory
: existsSync(exercismDirectory)
? exercismDirectory
: null

if (configDirectory === null) {
throw new Error(
'Expected .meta or .exercism directory to exist, but I cannot find it.'
)
}

const configFile = new URL('./config.json', configDirectory)
if (!existsSync(configFile)) {
throw new Error('Expected config.json to exist at ' + configFile.toString())
}

// Experimental: import config from './config.json' with { type: 'json' }
/** @type {import('./config.json') } */
const config = JSON.parse(readFileSync(configFile))

const jest = !config.custom || config.custom['flag.tests.jest']
const tstyche = config.custom?.['flag.tests.tstyche']
console.log(
`[tests] tsc: ✅, tstyche: ${tstyche ? '✅' : '❌'}, jest: ${jest ? '✅' : '❌'}, `
)

/**
* 1. tsc: the typescript compiler
*/
try {
console.log('[tests] tsc (compile)')
execSync('corepack yarn lint:types', {
stdio: 'inherit',
cwd: process.cwd(),
})
} catch {
exit(-1)
}

/**
* 2. tstyche: type tests
*/
if (tstyche) {
try {
console.log('[tests] tstyche (type tests)')
execSync('corepack yarn test:types', {
stdio: 'inherit',
cwd: process.cwd(),
})
} catch {
exit(-2)
}
}

/**
* 3. jest: implementation tests
*/
if (jest) {
try {
console.log('[tests] tstyche (implementation tests)')
execSync('corepack yarn test:implementation', {
stdio: 'inherit',
cwd: process.cwd(),
})
} catch {
exit(-3)
}
}

/**
* Done! 🥳
*/
Loading