# Get and replace elements in 2d array using recursion

**URL:** <https://swi-prolog.discourse.group/t/get-and-replace-elements-in-2d-array-using-recursion/5315>\
**Category:** Predicate\
**Tags:** list, prolog-usage\
**Created:** [April 20, 2022, 1:56pm UTC](https://swi-prolog.discourse.group/t/get-and-replace-elements-in-2d-array-using-recursion/5315 "2022-04-20T13:56:50Z")\
**Posts on this page:** 1\
**Showing post:** 2

<div class="post-metadata">

**Author:** ![brebs](https://avatars.discourse-cdn.com/v4/letter/b/e9c0ed/32.png) [@brebs](https://swi-prolog.discourse.group/u/brebs)\
**Post date:** [April 20, 2022, 6:01pm UTC](https://swi-prolog.discourse.group/t/get-and-replace-elements-in-2d-array-using-recursion/5315/2 "2022-04-20T18:01:14Z")

</div>

```prolog
replace_matrix(INth0, JNth0, NewVal, Matrix, NewMatrix) :-
    must_be(nonneg, INth0), 
    must_be(nonneg, JNth0),
    % I and J becomes the list of levels
    replace_matrix_(Matrix, [INth0, JNth0], NewVal, NewMatrix).

replace_matrix_([H|T], [Nth0|LevelsT], NewVal, NewMatrix) :-
    % Nth0 is the current position on current level
    ( Nth0 > 0
    -> Nth0Prev is Nth0 - 1,
        NewMatrix = [H|NewMatrix1],
        Levels1 = [Nth0Prev|LevelsT],
        % Iterate through the list to the desired element
        replace_matrix_(T, Levels1, NewVal, NewMatrix1)
    ; LevelsT = []
        % Replace this element, because am at the lowest level
    -> NewMatrix = [NewVal|T]
    ; NewMatrix = [NewElem|T],
        % Drill down into next level of the matrix
        replace_matrix_(H, LevelsT, NewVal, NewElem)
    ).

```

Result:

```prolog
?- time(replace_matrix(0, 1, X, [[1,2,3],[4,5,6],[7,8,9]],Result)).
% 15 inferences, 0.000 CPU in 0.000 seconds (88% CPU, 319373 Lips)
Result = [[1,X,3],[4,5,6],[7,8,9]].

```

Note the changed [argument order](https://swi-prolog.discourse.group/t/split-list/4836/8).

---

_[View the full topic](https://swi-prolog.discourse.group/t/get-and-replace-elements-in-2d-array-using-recursion/5315)._
