โŒ

Normal view

There are new articles available, click to refresh the page.
Before yesterdayMain stream

Find remaining queens for nqueens problem

As the title says, I have to find the remaining queens for the nqueens problem, but I have not use recursive calls and I have to use stacks and backtracking. Currently I have:

#include <stdio.h>
#include <stdbool.h>

#define MAX_N 11

typedef struct {
    int row;
    int col;
} Queen;

typedef struct {
    int top;
    Queen items[MAX_N];
} Stack;

void initStack(Stack* stack) {
    stack->top = -1;
}

void push(Stack* stack, Queen queen) {
    if (stack->top < MAX_N - 1) {
        stack->top++;
        stack->items[stack->top] = queen;
    }
}

Queen pop(Stack* stack) {
    if (stack->top >= 0) {
        stack->top--;
        return stack->items[stack->top];
    }
    Queen emptyQueen = { -1, -1 }; // Return an invalid queen
    return emptyQueen;
}

// Helper function to check if a queen can be placed at (row, col)
bool isValid(Queen queens[], int numQueens, int row, int col) {
    for (int i = 0; i < numQueens; i++) {
        if (queens[i].row == row || queens[i].col == col ||
            queens[i].row - queens[i].col == row - col ||
            queens[i].row + queens[i].col == row + col) {
            return false; // Queens attack each other
        }
    }
    return true;
}

void solveQueens(int max_queens, Queen* initQs, int numInitQ) {
    Queen queens[MAX_N];
    Stack stack;
    initStack(&stack);

    // Initialize with initial queens
    for (int i = 0; i < numInitQ; i++) {
        queens[i] = initQs[i];
    }

    int numQueens = numInitQ;
    int row = numInitQ; // Start from the next row

    while (numQueens < max_queens) {
        bool found = false;
        for (int col = 0; col < max_queens; col++) {
            if (isValid(queens, numQueens, row, col)) {
                queens[numQueens] = (Queen){ row, col };
                numQueens++;
                found = true;
                break;
            }
        }
        if (!found) {   //backtrack, pop the queen
            queens[numQueens - 1] = pop(&stack);
            numQueens--;
            row = queens[numQueens - 1].row + 1;
            if(numQueens <= numInitQ){  //there are not enough queens in total, therefore no solution
                printf("no solution\n");
                return;
            }
        } else {
            push(&stack, queens[numQueens - 1]);
            row++;
        }
    }

    // Print the solution
    for (int i = 0; i < numQueens; i++) {
        printf("%d %d\n", queens[i].row, queens[i].col);
    }
}

for testing, I have used the main function:

int main() {
    Queen initialQueens[] = { {0, 0} }; // Example initial queens
    int numInitialQueens = 1;
    int maxQueens = 4; // Change this to the board size
    solveQueens(maxQueens, initialQueens, numInitialQueens);
    return 0;
}

Which expectedly prints No Solution. However, when I try to make the board size 5 (setting maxQueens to 5) the function enters an infinite loop. My theory is that this is probably caused by the function finding a valid queen, but the total number of queens is not enough, which causes it to backtrack repeatedly. Don't take my word for the error, I could be way off but it might be a lead. Anyone got any fixes and suggestions?

How to perform mmrm model and get the lsmean results in loop in sas?

I am a R user and new to SAS. I tried to write a do loop to run MMRM model and append the results. So far I had a general idea to perform the loop, but still couldn't figure out how to implement it in SAS.

I have a dataset have including variables as: subjid, treatment, baseline, visit, age_gr, gender_gr, bmi_gr

The steps that I want to run the loop are as below:

Step 1: set the name=age_gr, and generate a empty data called result;

Step 2: run the MMRM model where &name=1 as below:

proc mixed data = have;
     where &name=1;
     class subjid treatment visit;
     model chg = baseline treatment visit treatment*visit/ ddfm = KR;
     repeated visit/ subject = subjid type = UN;
     lsmeans treat*visit/ cl alpha = 0.05 diff e;
     ods output lsmeans = lsmeans diffs=diffs;
     run;

Step 3: save the result of lsmeans and 95% CI using a macro called %format_result(lsmeans,diffs,&name); I have completed the macro, so just need to know the result was saved at a file called &name, i.e it should called age_gr in the first loop;

Step 4: append the result &name to the data result as below:

data result;
set result &name;
run;

Step 5: run the MMRM model where &name=2 as below:

proc mixed data = have;
     where &name=2;
     class subjid treatment visit;
     model chg = baseline treatment visit treatment*visit/ ddfm = KR;
     repeated visit/ subject = subjid type = UN;
     lsmeans treat*visit/ cl alpha = 0.05 diff e;
     ods output lsmeans = lsmeans diffs=diffs;
     run;

Step 6: Same as Step 3, save the result of lsmeans and 95% CI using a macro called %format_result(lsmeans,diffs,&name), and the result was saved at a file called &name;

Step 7: Same as Step 4: append the result &name to the data result as below:

data result;
set result &name;
run;

Step 8๏ผšrepeat step1-7 by setting the name=gender_gr;

Step 9: repeat step1-7 by setting the name=bmi_gr, and finally get the result file;

I was thinking of performing the loop using something like array in SAS but failed:

data want;
  set have;
  array vars age_gr--bmi_gr;
  do i=1 to dim(vars);
     name=vars(i);
     ... have no idea how to continue

Really appreciated if anyone can help!

Input a string to a int variable inside a loop

im new to C++ and i just find out that if i ask a user input for a variable with int data type in a while loop, the loop just keep repeating without asking for another input, why can this happen?

#include <iostream>
using namespace std;
int main(){
   while(true){
      int x;
      cout<<"Enter x: ";
      cin>>x;
      cout<<"You enter"<<x<<endl;
   }
   return 0;
}

I tried to make menu inside a loop called menu, the menu contains options that are numbers so i declared an integer variable. I think if i enter string, it will just execute the code in the default case of the switch and continues the loop normally.

Python: best way to iterate through lists and store which has max value for each index

In Python (3.8), I have 15 lists of floats of the same length.

For each index of the lists, I want to find the maximum in the lists, find the corresponding list, and add the information to a new list. So my new list would give me the information, for each index, of the list with the maximum value (I don't care about the actual max value, just need to know the list that has it at each index).

Right now I have the following code to do this (maxList is my list with this information). It works, but it feels very tedious to look at and I guess there is a better and more compact/efficient way to do this.

myMax=0
maxList=0
for i in range(len(List1)):
    myMax=max(List1[i])
    maxList=1
    if(max(List2[i]) > max(List1[i])):
        myMax=max(List2[i])
        maxList=2
    if(max(List3[i]) > max(List2[i])):
        myMax=max(List3[i])
        maxList=3
        ....

My question would be is there a better way to achieve the same result without repeating 15 times the same if loop?

Problem with Python Loops: `for` and `while`

Write a program that polls users about their dream vacation. Write a prompt similar to If you could visit one place in the world, where would you go? Include a block of code that prints the results of the poll.

# Empty dictionary where we'll store the results of the poll.
poll = {}

polling_active = True

while polling_active:
    prompt_1 = "\nWhat is your name? "
    response_1 = input(prompt_1)

    prompt_2 = "If you could visit one place in the world, where would you go? "
    response_2 = input("Hello" + " " + response_1 + "!" + " " + prompt_2)

    # store name/place in dictionary.
    poll[response_1] = response_2

    prompt_3 = "Would you like to let another person respond? (yes/no) "
    response_3 = input(prompt_3)
    while response_3 == 'yes':
#    if response_3 == 'no':  
        polling_active = True

print(f"\n {poll}")

I have noticed that the program does not compile in that case (I mean when the line if response_3 == 'no': is commented out). However, if I uncomment it and comment out the line while response_3 == 'yes':, it works perfectly. I am very confused about this. Can anyone explain to me why the while loop does not give the desired result here? Perhaps I do not understand the real difference between the for and while loops.

I have spent about 30 minutes trying to solve this problem, and I have finally solved it. However, I cannot understand why the while loop gives an error here, while the for loop works perfectly. Apologies if my question seems too simple, as I only started coding about a week ago.

Efficient way to use apply a function on Pandas rows [duplicate]

I am looking for an efficient way to apply a function on each row of a dataframe to perform some operation and repeat the row by a number defined in other column. Currently, I am doing it by iterate on each row, but it takes too long on a large dataframe.

Sample code is as below:

`import pandas as pd
def my_func(row):
    row = row.to_frame().T
    repeated_row = row.loc[row.index.repeat(row['col2'])]
    return repeated_row
df = pd.DataFrame(data = {'col1':list('abc'),
                          'col2': [2,2,3]})
df_comb = pd.DataFrame()
for i, row in df.iterrows():
    df_rep = my_func(row)
    df_comb = pd.concat([df_comb, df_rep], axis=0)`

However, I want a solution that's not using the for loop as above and I couldn't find an answer for this historically. I imagine there will be an equivalent way to use "apply" function to this df, such as:

df_comp = pd.concat([df.apply(lambda row: my_func(row)), axis=1], axis=0)

But at the moment this syntax does not work properly.

Much appreciated if you could point out the correct solution.

Pause loop to refresh API access token then resume

I have an API that uses an access token, and a loop to update users in the system using that API:

while (socketerror == 0 && i < usersJson.length) {
for (let user of usersJson) {
functions.push(() =>
   userFunctions.updateUser(
   url,
   accessToken,
   user,
  )
 );
}}

I am looping through the users to update them, but the access token is expiring and I need to refresh it before I put it in the function.

I thought of putting the refresh call before each user:

if (new Date.now() < okapiExpiration) {
  accessToken = function refreshToken(accessToken);
}

but since they are running simultaneously, I fear that I will start asking for refreshed tokens for each one and get errors when I make the call.

Then I thought of using a while loop before I run through the users, but that will restart the loop of all the users each time.

Any idea how I can pause my loop, refresh the token, then continue the loop?

Type error while looping through array in PL/pgSQL

I am beginner with PostgreSQL. Trying to loop here the values that I pass:

companyregistration just calling the companyRegistrationValidator

The function call:

SELECT companyregistration(
'876786576544', 
'TraderAnalytics',
'[email protected],
'@kjvfhjh88976',
ARRAY['86578657865','Natali','Vladimirov','[email protected]', '+@jvfhjh88976'],
ARRAY [['Maks','Burkov'],['Yan','Burkov']],
'Netherlands',
'Company');
[2018-10-28 18:29:15] [42804] ERROR: FOREACH expression must yield an array, not type text
[2018-10-28 18:29:15] Where: PL/pgSQL function companyregistrationvalidator(character varying,character varying,character varying,character varying,text[],text[],character varying) line 28 at FOREACH over array

The function definition:

CREATE OR REPLACE FUNCTION companyRegistrationValidator (company_id VARCHAR, comp_name VARCHAR, comp_email VARCHAR, comp_password VARCHAR, employees text[], creators text[], country VARCHAR)
  RETURNS BOOLEAN AS $$
DECLARE
    checked BOOLEAN := FALSE ;
    r_id VARCHAR; r_name VARCHAR; r_email VARCHAR; r_password VARCHAR; r_country VARCHAR;
    cr_counter INTEGER = 0; em_counter INTEGER = 0; c_ar_length INTEGER  = 0; e_ar_length INTEGER = 0;
    ar_index text; creator text; val text;

BEGIN
    SELECT id_r , email_r , password_r , country_r , firstname_r INTO r_id , r_email , r_password, r_country , r_name FROM regex;

    c_ar_length := cardinality(creators);
    e_ar_length := cardinality(employees);

    FOREACH val IN ARRAY employees LOOP
        IF val ~ r_id THEN em_counter := +1;
        ELSEIF val ~ r_name THEN  em_counter := +1;
        ELSEIF val ~ r_email THEN em_counter := +1;
        ELSEIF val ~ r_password THEN em_counter := +1;
        END IF;
    END LOOP;

    FOREACH creator IN ARRAY creators LOOP
        FOREACH ar_index IN ARRAY creator LOOP
            IF ar_index ~ r_name THEN cr_counter := +1;
            END IF;
        END LOOP;
    END LOOP;

    IF cr_counter = c_ar_length AND em_counter = e_ar_length AND company_id ~ r_id AND comp_name ~ r_name AND comp_email ~ r_email AND comp_password ~ r_password AND country ~ r_country
        THEN checked := TRUE;
    END IF;

    RETURN checked;
 END;
$$ LANGUAGE plpgsql;

What's the error in my code?

Map coordinates of a matrix to number of samples unequal to length of one matrix line

I'm trying to map items from a list to coordinates of a matrix. A pair of rows in the matrix should hold the same items, but with different suffixes. If the remaining number of items is less than the length of the row, the mapping should fill the row accordingly and then continue in the next row.

Here is what I came along for now:

my_list = ['Item {}'.format(i) for i in range(30)]

# Create matrix of 8 rows and 12 columns and coordinates
rows = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']
columns = range(1, 13)
coordinates = [row + str(column) for row in rows for column in columns]

# Map items to coordinates, with each pair of rows (A & B, C & D, etc.) holding
# the same items, but with two different suffixes (e. g.)
suffixes = ['_one', '_two']
full_rows = len(my_list) // len(columns) * len(suffixes)
remaining_items = len(my_list) % len(columns)

for i in range(full_rows):
    for j in range(len(columns)):
        if i % len(suffixes) == 0:
            suffix = suffixes[0]
        else:
            suffix = suffixes[1]
        coordinate = rows[i] + str(columns[j])

The above's code works to create the coordinates and assign the suffixes correctly. However, the items from my_list are still missing. I was thinking about determining an index within the loop. Something like simply counting up index = j + len(columns) * i will not work, as every second row will be the same items as the one before.

I'm somehow stuck. Thus, I would be happy, if someone has input what I'm missing here or what to look at.

Python Dictonary parsing

I have nested python dict in the below format and I need to print specific values based on a condition using for loop -

"powerSupplySlots": {
        "1": {
            "name": "PWR-500AC-R",
            "serialNum": "XXXXXXXXXXX"
        },
        "2": {
            "name": "PWR-500AC-R",
            "serialNum": "XXXXXXXXXXX"
        }
    },

I tried the below code but somehow not able to print the values in the below format

output

PowerSupply 1 with SerialNo - XXXXXXXXXX

Am I overengineering this? (loop in T-SQL)

My code works - I'd just like an honest opinion on how I'm approaching this. Could someone have a look?

I work for a financial institution that launched a digital customer interface. I want to check whether customers who make use of the interface have a higher customer lifetime value (clv) than other customers. Specifically, I want to see how clv changes after customers sign up for our online service.

The clv values are computed on the first of January of every year. Whether customers sign up for our online service is not centrally stored. Therefore, I create a temp table for each of the years 2020-2024 and then stack these together.

The code below works, but I'll have to repeat it for each year in 2020-2024:

DROP TABLE IF EXISTS #tempclv2024;

WITH clvs AS (
    SELECT
        clv.CustID
        , CASE
              WHEN AccountId IS NULL THEN 'No'
              ELSE 'Yes'
          END AS account_active
          , AccountId
        , ROUND(clv.clv,2) AS clv_eur
        , '2024' AS year_clv
    FROM
        BD.CLV AS clv
    LEFT JOIN
        KAD.Customer AS mi
    ON 
        clv.CustID = mi.id
    WHERE 
        clv.date = '2024-01-01'
) 
SELECT 
    CustID
    , account_active
    , clv_eur
    , year_clv
INTO 
    #tempclv2024
FROM
    clvs

SELECT * FROM #tempclv2020

To keep the code succinct, my first instinct is to create a loop to iterate over all of the years 2020-2024. I created the code below, and it works, however I am wondering if I am overengineering this? I have not seen other people use loops in SQL before and I do not know if there are any disadvantages/special considerations to looping in SQL like this.

Could someone have a look and give their honest opinion?

Many thanks! (note: I am using Transact-SQL on SQL Server)

DECLARE @Year INT = 2020;
DECLARE @TableName NVARCHAR(50);
DECLARE @SQL NVARCHAR(MAX);
DECLARE @FinalQuery NVARCHAR(MAX);

DROP TABLE IF EXISTS #tempclv2020;
DROP TABLE IF EXISTS #tempclv2021;
DROP TABLE IF EXISTS #tempclv2022;
DROP TABLE IF EXISTS #tempclv2023;
DROP TABLE IF EXISTS #tempclv2024;
DROP TABLE IF EXISTS ##tempfinal; 

WHILE @Year <= 2024
BEGIN
    SET @TableName = '##tempclv' + CAST(@Year AS NVARCHAR(4));

    PRINT 'Year' + CAST(@Year AS NVARCHAR(4)); 

    -- Drop the temporary table if it exists
    SET @SQL = 'DROP TABLE IF EXISTS ' + @TableName;
    EXEC sp_executesql @SQL;

    -- Create the temporary table for the specific year
    SET @SQL = '
        WITH clvs AS (
            SELECT
                clv.CustID,
                CASE
                    WHEN mi.AccountId IS NULL THEN ''No''
                    ELSE ''Yes''
                END AS account_active,
                AccountId,
                ROUND(clv.clv, 2) AS clv_eur,
                ''' + CAST(@Year AS NVARCHAR(4)) + ''' AS year_clv
            FROM
                BD.CLV AS clv
            LEFT JOIN
                KAD.Cust AS mi
            ON
                clv.CustID = mi.id
            WHERE
                clv.date= ''' + CAST(@Year AS NVARCHAR(4)) + '-01-01''
        )
        SELECT
            CustID,
            account_active,
            clv_eur,
            year_clv
        INTO
            ' + @TableName + '
        FROM
            clvs';

    EXEC sp_executesql @SQL;

    SET @Year = @Year + 1;
END

-- Combine the results using UNION ALL
SET @FinalQuery = '
    SELECT * INTO ##tempfinal FROM (
        SELECT * FROM ##tempclv2020
        UNION ALL
        SELECT * FROM ##tempclv2021
        UNION ALL
        SELECT * FROM ##tempclv2022
        UNION ALL
        SELECT * FROM ##tempclv2023
        UNION ALL
        SELECT * FROM ##tempclv2024
    ) AS CombinedData

    SELECT *
    FROM ##tempfinal 
    ORDER BY CustID, year_clv ASC';

-- Execute the final query
EXEC sp_executesql @FinalQuery;

How do I construct and sending personalized emails using information from a spreadsheet that has duplicates?

I am trying to send personalized emails to a large list of people to provide them links to their project reports. The data is stored in an Excel spreadsheet and read into python

The project number, the corresponding link to that project numbers report, and the persons name all appear in an excel spreadsheet like so

Project number link name email address

 1234         link for 1234      Mickey Mouse         [email protected]
 5678         link for 5678      Donald Duck          [email protected]
 9101         link for 9101      Donald Duck          [email protected]
 1213         link for 1213      Bugs Bunny           [email protected]
 1415         link for 1415      Bugs Bunny           [email protected]
 1617         link for 1617      Bugs Bunny           [email protected]
 1819         link for 1819      Bugs Bunny           [email protected] 
 2021         link for 2021      Minnie Mouse         [email protected]

While I can definitely iterate through the name column and construct a message based on that I don't want to send a person multiple emails if they are on multiple projects. As you can see from above while Mickey Mouse and Minnie mouse each have 1 project, Donald duck has 2 projects and Bugs Bunny has 4.

For Mickey Mouse, the email should read...

Hello Mickey Mouse

For project 1234 please use link: link for 1234

For Bugs Bunny, the email should read...

Hello Bugs Bunny

For project 1213 please use link: link for 1213 For project 1415 please use link: link for 1415 For project 1617 please use link: link for 1617 For project 1819 please use link: link for 1819

Again the idea is to not send people multiple emails because some are on alot of projects and it would just spam their inbox.

Couldn't quite work out how to get it to go through the list of names ignore when a name is duplicated but extract the corresponding project numbers and links and put them into one email for that person.

Essentially I need the code to send 1 email per person but potentially list multiple project numbers and links if that person is on multiple projects.

Couldn't paste the code because it didn't like the format no matter what I did. I'll attach a screenshot. enter image description here

Hope this all makes sense. Any help would be appreciated

How to add row data under columns using POI

My first time using POI. I'm attempting to add row data under their perspective columns. The columns and the data are coming from two different sets of data.

Columns were added like this.

XSSFSheet sheet = wb.createSheet(" Sheet name");
XSSFCell cell;

String[] columns = columnArr;

int rowIndex = 0;
XSSFRow row = sheet.createRow(rowIndex);
sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, columns.length - 1));

cell = row.createCell(0);
POIExcelUtilities.setCellValue(cell, "Page Title");
row.setHeightInPoints(15);

row = sheet.createRow(rowIndex);
for (int i = 0; i < columns.length; i++) {

    POIExcelUtilities.setCellValue(cell, columns[i]);  //columns look good
}
rowIndex++;
        

This works fine as I have 2 columns from left to right. Now I'm trying to add that data under their respective columns.

For example: (1)Home Type and (2)Car Type are the name of the '2' columns and underneath is (1)Townhouse and (2)Ford.

I have 3 for loops. The first loop is on id of the items the second is for the column elements (rows) and third to place the items in the spreadsheet. I may have too many loops...

List<String> myList = new ArrayList<>();
String[] myStringArrayColumns //string array used below it has correct data

for( int i = 0; id != null && i < id.length(); i++ ) {
    Long myId = id.getLong(i);


    if (myId != null) {

        for (int l = 0; l < myStringArrayColumns.length; l++) {
            String myStringArrayColumnsElement = myStringArrayColumns[l];
            String dataForRows = myStringArrayColumnsElement;  
            //myStringArrayColumnsElement is different per iteration
                    
            myList.add(dataForRows);
            String[] columnArr2 = new String[myList.size()];
            String[] lastArray = myList.toArray(columnArr2);

            row = sheet.createRow(rowIndex);
            for (int g = 0; g < lastArray.length; g++) {
                rowIndex++;
                cell = row.createCell(g);
                cell.setCellStyle(cellStyles.get("default"));
                POIExcelUtilities.setCellValue(cell, lastArray[g]);  
                //tried with dataForRows string as well since cellValue accepts Objects
            }

My excel sheet was ok until I tried to add the data underneath the columns. Am I close to doing this correctly? After trying to add the data it destroyed the columns and data repeats.

Any help will be appreciated.

How do I make the code ask me to choose the folder I want to save a file in?

import os
import tkinter as tk
from tkinter import filedialog

def add_numbers():
    attempts = 0
    results = []

    while attempts < 3:
        try:
            num1 = float(input("Enter the first number: "))
            num2 = float(input("Enter the second number: "))

            result = num1 + num2
            equation = f"{num1} + {num2} = {result}"

            print(equation)
            results.append(equation)
            attempts += 1

        except ValueError:
            attempts += 1
            print("Invalid input. Please enter valid numbers.")

    save_filename = "results.txt"
    folder = filedialog.askdirectory()
    save_location = os.path.join(folder, save_filename)
    
    with open(save_location, 'w') as file:
        for equation in results:
            file.write(equation + '\n')
    

    print(f"Results have been saved to {save_location}")
    print("You have reached the maximum number of attempts. Exiting.")


if __name__ == "__main__":
    add_numbers()

Hi, I would like it to let me choose the location in my computer to save the result file named result.txt. This is what I've written so far, in Python.

Here are the requirements:

Write a program that continually asks the user for two numbers to add (and quits when they are finished). For each addition the program performs, store the results in a file โ€œdata//results.txtโ€. The entire equation should be added, not just the sum. For example, if the user enters โ€œ2โ€ and โ€œ4โ€, the following text should be appended to the file: 2 + 4 = 6 The program should be looping so try running a test for 3 entries that would be stored in result.txt.

Thank you in advance.

How to iterate over Array or nil ([]?) type in Ballerina?

I have a variable of type Array or nil([]?) and I am trying to iterate over each element.

mysql:Client db = check new (host, user, password, database, port);
stream<Brewery, sql:Error?> rez = db->query(query);
Brewery[]? brewery = check from Brewery brwr in rez select brwr;

Brewery[]? does not look like it can be iterated. What should I change in above code to iterate over each element in Brewery[]? brewery

Additionally, is there a way to take only the top 5 items in the statement, Brewery[]? brewery = check from Brewery brwr in rez select brwr;?

โŒ
โŒ