# Reverse Alphabet

### Description

**Reverse Alphabet is a simple yet powerful tool that takes any individual word as input and promptly returns its reverse.**

### Executing Reverse Alphabet <a href="#using-bacalhau-to-execute-duckdb-processing" id="using-bacalhau-to-execute-duckdb-processing"></a>

We use Truebit to execute the Reverse Alphabet task to get a verified result.

### The Code

You can find the Reverse Alphabet example within the folder *truebit-nextgen-examples/function-tasks/\<language>/reverse-alphabet.*

{% tabs %}
{% tab title="Rust" %}
📁 src \
└─ 📄 main.rs \
📄 Cargo.toml\
📄 Cargo.lock

{% hint style="info" %}
The target folder and the Cargo.lock file are going to be generated after running the [build](#step-2-build-the-source-code) command within the truebit-cli.
{% endhint %}
{% endtab %}

{% tab title="C" %}
📁 src \
└─ 📄 main.c\
📄 compile.sh

{% hint style="info" %}
The xxx folder and the xxxx file are going to be generated after running the [build](#step-2-build-the-source-code) command within the truebit-cli.
{% endhint %}
{% endtab %}

{% tab title="C++" %}
📁 src \
└─ 📄 main.cpp\
📄 compile.sh

{% hint style="info" %}
The xxx folder and the xxxx file are going to be generated after running the [build](#step-2-build-the-source-code) command within the truebit-cli.
{% endhint %}
{% endtab %}

{% tab title="Js" %}
📁 src \
└─ 📄 main.js\
📄 package-lock.json\
📄 package.json
{% endtab %}

{% tab title="Python" %}
📁 src \
└─ 📄 task.py
{% endtab %}
{% endtabs %}

#### Source

{% tabs %}
{% tab title="Rust" %}
**main.rs**

{% code overflow="wrap" lineNumbers="true" %}

```rust
fn run_task(input: String) -> String {
    input.chars().rev().collect()
}

fn main() {
    let input: String =
        std::fs::read_to_string("input.txt").expect("Could not read from input.txt");
    let output = run_task(input);
    std::fs::write("output.txt", output).expect("Could not write to output.txt");
}
```

{% endcode %}
{% endtab %}

{% tab title="C" %}
**main.c**

```c
#include <stdio.h>
#include <stdlib.h>

int fibonacci(int n) {
    int a = 0, b = 1, c;
    for (int i = 2; i <= n; i++) {
        c = a + b;
        a = b;
        b = c;
    }
    return b;
}

int main() {
    FILE *inputFile = fopen("input.txt", "r");
    if (inputFile == NULL) {
        perror("Error opening input.txt");
        return 1;
    }

    int input;
    if (fscanf(inputFile, "%d", &input) != 1) {
        perror("Error reading input.txt");
        fclose(inputFile);
        return 1;
    }

    fclose(inputFile);

    int result = fibonacci(input);

    FILE *outputFile = fopen("output.txt", "w");
    if (outputFile == NULL) {
        perror("Error opening output.txt");
        return 1;
    }

    fprintf(outputFile, "%d", result);
    fclose(outputFile);

    return 0;
}
```

{% endtab %}

{% tab title="C++" %}
**main.cpp**

```cpp
#include <iostream>
#include <fstream>

int fibonacci(int n) {
    int a = 0, b = 1, c;
    for (int i = 2; i <= n; i++) {
        c = a + b;
        a = b;
        b = c;
    }
    return b;
}

int main() {
    std::ifstream inputFile("input.txt");
    if (!inputFile.is_open()) {
        std::cerr << "Error opening input.txt" << std::endl;
        return 1;
    }

    int input;
    if (!(inputFile >> input)) {
        std::cerr << "Error reading input.txt" << std::endl;
        inputFile.close();
        return 1;
    }

    inputFile.close();

    int result = fibonacci(input);

    std::ofstream outputFile("output.txt");
    if (!outputFile.is_open()) {
        std::cerr << "Error opening output.txt" << std::endl;
        return 1;
    }

    outputFile << result;
    outputFile.close();

    return 0;
}
```

{% endtab %}

{% tab title="Js" %}
**main.js**

```javascript
import fs from 'fs';

function run_task(input) {
    return input.split('').reverse().join('');
}

let input = fs.readFileSync('input.txt', 'utf8');
const output = run_task(input);
fs.writeFileSync('output.txt', output);
```

{% endtab %}

{% tab title="Python" %}
{% code overflow="wrap" lineNumbers="true" %}

```python
def run_task(input_str):
    """Reverses the input string.

    Args:
        input_str: The string to be reversed. 

    Returns:
        The reversed string.
    """

    return input_str[::-1]

if __name__ == "__main__":
    with open("input.txt", "r") as input_file:
        input_str = input_file.read()

    output_str = run_task(input_str)

    with open("output.txt", "w") as output_file:
        output_file.write(output_str)

    print(output_str)
```

{% endcode %}
{% endtab %}
{% endtabs %}

#### In/Out Parameters

In order to send parameters to the Truebit task, you need to open the *"input.txt"* file and get the value from there. For now, only one input parameter is allowed.

{% tabs %}
{% tab title="Rust" %}
{% code overflow="wrap" %}

```rust
let input: String = std::fs::read_to_string("input.txt").expect("Could not read from input.txt");
```

{% endcode %}
{% endtab %}

{% tab title="C" %}

```c
FILE* inputFile = fopen("input.txt", "r");
if (inputFile == NULL) {
    perror("Error opening input.txt");
    return 1;
}

char inputBuffer[256]; 
if (fgets(inputBuffer, sizeof(inputBuffer), inputFile) == NULL) {
    perror("Could not read from input.txt");
    fclose(inputFile);
    return 1;
}

fclose(inputFile);
```

{% endtab %}

{% tab title="C++" %}

```cpp
ifstream inputFile("input.txt");
if (!inputFile) {
    cerr << "Could not read from input.txt" << endl;
    return 1;
}

string input;
getline(inputFile, input);
inputFile.close();
```

{% endtab %}

{% tab title="Js" %}

```javascript
let data = fs.readFileSync('input.txt', 'utf8')   
```

{% endtab %}

{% tab title="Python" %}

```python
with open("input.txt", "r") as file:
input_string = file.read().strip()
```

{% endtab %}
{% endtabs %}

To retrieve the output value from the Truebit task, you need save it in the *"output.txt"* file.

{% tabs %}
{% tab title="Rust" %}
{% code overflow="wrap" %}

```rust
std::fs::write("output.txt", output).expect("Could not write to output.txt");
```

{% endcode %}
{% endtab %}

{% tab title="C" %}

```c
FILE* outputFile = fopen("output.txt", "w");
if (outputFile == NULL) {
    perror("Error opening output.txt");
    free(output);
    return 1;
}

fprintf(outputFile, "%s", output);
fclose(outputFile);
free(output);tr    
```

{% endtab %}

{% tab title="C++" %}

```cpp
ofstream outputFile("output.txt");
if (!outputFile) {
    cerr << "Could not write to output.txt" << endl;
    return 1;
}

outputFile << output << endl;
outputFile.close();
```

{% endtab %}

{% tab title="Js" %}

```javascript
fs.writeFileSync('output.txt', output)
```

{% endtab %}

{% tab title="Python" %}

```python
with open("output.txt", "w") as file:
file.write(output_string)
```

{% endtab %}
{% endtabs %}

### Trying Out

We will use the [Truebit CLI](https://devs.truebit.io/developing-truebit-tasks/truebit-cli-reference) to [compile](#step-2-build-the-source-code) and [test](#step-3-try-the-code) our source code. Once finalized, we will [deploy](#step-4-deploy-the-task) it to the Coordination Hub so that any user with the `namespace` and `taskname` can access or execute it.

#### Step 1: Create The Reverse Alphabet Source Code

Within the *src folder* you will find a file called main in the case of *Rust, C, C++, JS,* and *task.py* in the case of *Python*. This is the Reverse Alphabet implementation that will be used for testing purpose.

#### Step 2: Build The Source Code

Execute the [build](https://devs.truebit.io/truebit-cli-reference#build) command against Truebit node to get an instrumented Truebit task

{% hint style="info" %}
This in an example of how to build a JS task.&#x20;
{% endhint %}

{% code overflow="wrap" %}

```bash
truebit build truebit-nextgen-examples/function-tasks/js/reverse-alphabet/dist -l js
```

{% endcode %}

#### Output

{% code overflow="wrap" %}

```bash
Building the function task
Your function task is ready.
Use the following TaskId for execution or deployment: <taskId>
```

{% endcode %}

{% hint style="info" %}
The taskId will always starts with the language prefix + "\_" + cID
{% endhint %}

#### Step 3: Try The Code

Execute the [start](https://devs.truebit.io/truebit-cli-reference#start) command against the Truebit node to test our Algorithm. You will need to submit the instrumented task id + the input parameter.

{% code overflow="wrap" %}

```bash
truebit start js_d9254bbb26c626f7b1c6d20550aed4df34cbd6a9bf7558ae42396e6a4676d5a9 Hello_World
```

{% endcode %}

\[taskId]: Add the `taskId` generated in the previous step.&#x20;

#### Output

```bash
Executing the function Task
Execution Id: 50e9408a-2a04-469d-b493-d9b27a12c771
Task executed with status: succeed
Task executed with result: dlroW_olleH
Task resource usage:
┌───────────────┬───────────────┬───────────────┬───────┬─────────────┬──────────┐
│ (index)       │ Unit          │ Limits        │ Peak  │ Last status │ Capacity │
├───────────────┼───────────────┼───────────────┼───────┼─────────────┼──────────┤
│ Gas           │ 'Steps'       │ 1099511627776 │ 'N/A' │ 1906503210  │ 577      │
│ Nested calls  │ 'Calls'       │ 65536         │ 6372  │ 6339        │ 10       │
│ Frame memory  │ 'Bytes'       │ 524288        │ 20023 │ 19034       │ 26       │
│ System memory │ '64 Kb pages' │ 2048          │ 87    │ '𝚫 1'       │ 24       │
└───────────────┴───────────────┴───────────────┴───────┴─────────────┴──────────┘
```

#### Step 4: Deploy the task

Last, but not least, execute the [deploy](https://devs.truebit.io/truebit-cli-reference#deploy) command to effectively deploy our task to the coordination hub, so that anyone with the namespace, taskname and the [API key](https://devs.truebit.io/task-authorization#task-authorization-process) can execute it.

{% code overflow="wrap" %}

```bash
truebit deploy <namespace> <taskname> --taskId 
```

{% endcode %}

* \[`taskId`]: Add the taskId generated in step 2

#### Output

{% code overflow="wrap" %}

```bash
The function task has been deployed successfully.
The Task <taskName> version <version> was registered successfully in namespace <namespace>
```

{% endcode %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://devs.truebit.io/developing-truebit-tasks/how-to-create-function-tasks/function-task-examples/reverse-alphabet.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
