Skip to content

Fix linear search#33

Merged
dlesnoff merged 7 commits intoTheAlgorithms:mainfrom
dlesnoff:fix-linear-search
Jun 23, 2023
Merged

Fix linear search#33
dlesnoff merged 7 commits intoTheAlgorithms:mainfrom
dlesnoff:fix-linear-search

Conversation

@dlesnoff
Copy link
Collaborator

@dlesnoff dlesnoff commented Jun 20, 2023

Fix #31 and CI. Ran nimpretty directly.

@dlesnoff dlesnoff requested a review from Panquesito7 as a code owner June 20, 2023 12:41
@dlesnoff dlesnoff marked this pull request as draft June 20, 2023 12:51
@dlesnoff dlesnoff force-pushed the fix-linear-search branch from 93de526 to 454b1ca Compare June 20, 2023 12:53
@dlesnoff dlesnoff marked this pull request as ready for review June 20, 2023 12:54
Copy link
Contributor

@ZoomRmc ZoomRmc left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@beef331 is right. Since the logic has already been changed to iterate the array in ascending manner, better to change the default to Natural(0).

I would also removed the custom type aliases, it trades better locality for shorter lines (that still wrap), so no win as I see it.

What's the reason for changing the func to proc?

@dlesnoff
Copy link
Collaborator Author

dlesnoff commented Jun 20, 2023

What's the reason for changing the func to proc?

I used echo and forgot to change it. Done.

I would also removed the custom type aliases, it trades better locality for shorter lines (that still wrap), so no win as I see it.

Same intent here. Done.

@beef331 is right. Since the logic has already been changed to iterate the array in ascending manner, better to change the default to Natural(0).

I had overlooked that. I completely forget that the index is not retained with openarray[T]. Done.

Copy link
Member

@SatinWukerORIG SatinWukerORIG left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe just do this, to avoid confusion. Overall nim prettify has done illustriously 👍
And indeed, adding type definition to Natural and Option[Natural] looks redundant and verbose. well done!

@pietroppeter
Copy link
Contributor

As a note on linearSearch I think current version is buggy in case of arrays with negative indices (which are allowed for open array), see https://play.nim-lang.org/#ix=4yJs

import std/options

func linearSearch*[T](arr: openArray[T], key: T): Option[Natural] =
  # key is the value we are searching for in the array.
  for i, val in arr.pairs():
    if val == key:
      return some(Natural(i))
  none(Natural) # `key` not found

type
  NegIdxArray = array[-1 .. 1, int]

let
  a: NegIdxArray = [1,2,3]

echo linearSearch(a, 1) # some(0)

Correct answer should be some(-1)

@dlesnoff
Copy link
Collaborator Author

dlesnoff commented Jun 21, 2023

@pietroppeter This is also the case for any array with a custom starting index, isn't it?
This won't fix since I have no way to pass to the procedure the initial arr.low and arr.high apart from giving them explicitely as function parameters.
I will add a comment and call it a day.
I think that it is the caller's responsibility to readapt to the correct indexing afterwards.

echo some(linearSearch(a, 1).get() + a.low)

is a partial fix for the caller. This now raises a UnpackDefect when linearSearch returns none(Natural).

Co-authored-by: Satin Wuker <74630829+SatinWuker@users.noreply.github.com>
@beef331
Copy link

beef331 commented Jun 21, 2023

This is the case for any array that does not start at 0 or use a data type that is an integer, it's probably best to just have an openArray and a array[Idx, T] search.

@dlesnoff
Copy link
Collaborator Author

dlesnoff commented Jun 21, 2023

Having two functions for each would be contrary to the DRY - Don't Repeat Yourself principle. That feels like unnecessary duplicated code for me.

@beef331
Copy link

beef331 commented Jun 21, 2023

Sure but they have to be specialized. array[bool, T] or array[MyEnum, T] gets Option[Natural] which requires a type conversion back to index type by the user. The most reusable that should work for all types and the least amount of DRY breaking is as follows:

func linearSearchImpl[T](arr: openArray[T], key: T): int =
  for i, val in arr.pairs():
    if val == key:
      return i
  -1
  
func linearSearch*[T](arr: openArray[T], key: T): Option[Natural] =
  let val = linearSearchImpl(arr, key)
  if val >= 0:
    some(Natural(val))
  else:
    none(Natural)
    
func linearSearch*[Idx, T](arr: array[Idx, T], key: T): Option[Idx] =
  let val = linearSearchImpl(arr, key)
  if val >= 0:
    some(Idx(ord(arr.low) + val))
  else:
    none(Idx)  

@pietroppeter
Copy link
Contributor

Ah, I did not know that openarray did not support low and high. checked here indeed it has 0 as low always for openarray: https://play.nim-lang.org/#ix=4yJD

@beef331
Copy link

beef331 commented Jun 21, 2023

Well they support it as you've shown, but openArray is explicitly a type erasure so yea it loses the source type information. It's implemented as a ptr T, len afterall.

@dlesnoff
Copy link
Collaborator Author

@beef331 I do not want to merge your modifications. It adds much complexity to handle an often superfluous feature of array reindexing. I prefer to keep the implementation as simple as possible.

While one of our implementation's goals is « easy integration in one's code project », our primary goal is pedagogical algorithm teaching. I will use your code if indexed arrays reveal to be needed in the future.

@ZoomRmc
Copy link
Contributor

ZoomRmc commented Jun 21, 2023

@beef331 I do not want to merge your modifications. It adds much complexity to handle an often superfluous feature of array reindexing. I prefer to keep the implementation as simple as possible.

In this case it would be nice to document that the function does return the absolute index and not a corresponding index value for range/enum-indexed arrays.

dlesnoff and others added 2 commits June 21, 2023 15:50
Modified a bit the suggestions of comments. Please check them before approving.

Co-authored-by: Zoom <ZoomRmc@users.noreply.github.com>
@Panquesito7 Panquesito7 added the bug Something isn't working label Jun 23, 2023
Copy link
Member

@Panquesito7 Panquesito7 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approving to allow the merge. Thanks. 👍

@dlesnoff dlesnoff merged commit c0c6907 into TheAlgorithms:main Jun 23, 2023
dlesnoff added a commit to SatinWukerORIG/Nim that referenced this pull request Jun 27, 2023
* Use a dynamic allocated array (sequence) for strings

* Run nimpretty

* Add requested changes

* Fix documentation generation

* Fix test title according to changes

Co-authored-by: Satin Wuker <74630829+SatinWuker@users.noreply.github.com>

* Update comments to warn about indexing issues

Modified a bit the suggestions of comments. Please check them before approving.

Co-authored-by: Zoom <ZoomRmc@users.noreply.github.com>

---------

Co-authored-by: Dimitri LESNOFF <dimitri.lesnoff@lip6.fr>
Co-authored-by: Satin Wuker <74630829+SatinWuker@users.noreply.github.com>
Co-authored-by: Zoom <ZoomRmc@users.noreply.github.com>
dlesnoff added a commit to dlesnoff/Nim-Algorithms that referenced this pull request Jul 4, 2023
* Use a dynamic allocated array (sequence) for strings

* Run nimpretty

* Add requested changes

* Fix documentation generation

* Fix test title according to changes

Co-authored-by: Satin Wuker <74630829+SatinWuker@users.noreply.github.com>

* Update comments to warn about indexing issues

Modified a bit the suggestions of comments. Please check them before approving.

Co-authored-by: Zoom <ZoomRmc@users.noreply.github.com>

---------

Co-authored-by: Dimitri LESNOFF <dimitri.lesnoff@lip6.fr>
Co-authored-by: Satin Wuker <74630829+SatinWuker@users.noreply.github.com>
Co-authored-by: Zoom <ZoomRmc@users.noreply.github.com>
dlesnoff added a commit that referenced this pull request Sep 8, 2023
* Add a .github action to build DIRECTORY.md

* Update gh action build_directory_md

* Add ignored paths and git credentials

* chore: minor Gitpod improvements (#34)

Add Gitpod badge and prebuilds for all branches and forks

* Add binary search (#37)

* Add binary search

* Update binary search: add recursive version

* Update binary search: better description

* Update binary search: update runnableExamples

* Update binary search: improve tests, add overload for recursive func

* Update binary search: evaluate if-expression into result

* grammar

* Update binary search: improve description, add comments

* Update binary search: add missing test cases

* Update binary search: add info about pivot choice in description, rearrange it

* Update binary search: change int to Natural

* Update binary search: if block -> guard clause

* Update binary search: test cases

* Update binary search: simplify docs

* Update binary search: nimpretty

* Apply suggestions from code review

Co-authored-by: David Leal <halfpacho@gmail.com>

* Replace by an attempt of github pr create

* Fix branching and environment variable in the PR

Co-authored-by: David Leal <halfpacho@gmail.com>

* Create and populate the Maths directory (#4)

* Add a sample of maths basic algorithms

* Update maths/abs.nim

Co-authored-by: Zoom <ZoomRmc@users.noreply.github.com>

* Use openArray in absMaxSort

Co-authored-by: Zoom <ZoomRmc@users.noreply.github.com>

* Fix seq->openArray and int->SomeInteger

* Use Positive as input instead

* Update maths/addition_without_arithmetic.nim

Co-authored-by: Pietro Peterlongo <pietro.peterlongo@gmail.com>

* Name allocation number

* [maths/abs] Replace maxAbsSort by signed[Min/Max]Abs

* [Aliquot Sum] Add header

* Add empty line at end of file

* Remove Allocation number since it is a non standard algorithm

* Fix titles

* Run nimpretty on the files

* Rename file and add DIRECTORY.md



---------

Co-authored-by: Dimitri LESNOFF <dimitri.lesnoff@lip6.fr>
Co-authored-by: David Leal <halfpacho@gmail.com>

* Add arc length (#10)

* Fix linear search (#33)

* Use a dynamic allocated array (sequence) for strings

* Run nimpretty

* Add requested changes

* Fix documentation generation

* Fix test title according to changes

Co-authored-by: Satin Wuker <74630829+SatinWuker@users.noreply.github.com>

* Update comments to warn about indexing issues

Modified a bit the suggestions of comments. Please check them before approving.

Co-authored-by: Zoom <ZoomRmc@users.noreply.github.com>

---------

Co-authored-by: Dimitri LESNOFF <dimitri.lesnoff@lip6.fr>
Co-authored-by: Zoom <ZoomRmc@users.noreply.github.com>

* chore: run `apt-get update` before running other commands (#41)

This will run `sudo apt-get update` before running any other commands on the Gitpod prebuild image (`.gitpod.dockerfile`).

* Readme: fix gitter link, add Nim logo, formatting fixes (#42)

* Update README.md

Use more extended markdown syntax instead of HTML,
Add Matrix links
Superseed PR #40

* Actually fix gitter! Move img src links to footer.

Also changed the TheAlgorithms logo image link.

* Restore TheAlgorithms logo link

* More link fixes

---------

Co-authored-by: dlesnoff <54949944+dlesnoff@users.noreply.github.com>

* fix: nimpretty for `arc_length.nim` (#43)

* chore: `gc`->`mm`, move back to `config.nims` (#47)

* chore: revert #41 (#45)

* Update codeowners

* Fix: CONTRIBUTING.md links (#49)

Uppercase `directory.md` to `DIRECTORY.md`

* feat: add Levenshtein distance (#46)

* feat: add Levenshtein distance

* Apply suggestions from code review

Co-authored-by: Zoom <ZoomRmc@users.noreply.github.com>

* refactor: use toKey in initSubsolutions

* style: use .Natural

* style: remove blank line

* refactor: add Key type

* style: use descriptive variable names

* style: use a, b instead of strA, strB

* docs: add note about complexity

* refator: add name to TestCase

* docs: remove sentence about dp

* docs: update documentation of `levenshteinDistance`

Co-authored-by: Zoom <ZoomRmc@users.noreply.github.com>

* docs: rename initLevenshteinDistanceMatrix and add its documentation

* refactor: add fillLevenshteinDistanceMatrix

* tests: reorganise tests, remove TestCase type

* docs: add edit distance to module-level documentation

* docs: mention Wagner–Fischer algorithm

* docs: add comment in fillLevenshteinDistanceMatrix

* style: reformat fillLevenshteinDistanceMatrix

* docs: update DIRECTORY.md

---------

Co-authored-by: Zoom <ZoomRmc@users.noreply.github.com>

* docs: add missing `#` (#50)

* docs: add missing `#`

* docs: update DIRECTORY.md

* docs: remove ` of a Circle`

* docs: update DIRECTORY.md

---------

Co-authored-by: dlesnoff <54949944+dlesnoff@users.noreply.github.com>

* Fix: Remove unuseful date command

* chore: Update checkout version to v4 in build_directory_md

* Add error status checking + separate compilation and execution of directory.nim

---------

Co-authored-by: Dimitri LESNOFF <dimitri.lesnoff@lip6.fr>
Co-authored-by: David Leal <halfpacho@gmail.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

CI failure: linear search algorithm, string array and recursive algorithm.

6 participants