lundi 4 décembre 2023

Le Chat Sauvage

 =========

Il était une fois dans un petit village niché au cœur d'une vallée verdoyante, vivait une jeune fille nommée Mai. Mai était une petite fille au cœur tendre et à l'amour infini pour les animaux, en particulier les chats. Depuis son plus jeune âge, elle avait un lien spécial avec les félins et passait la plupart de ses journées à jouer avec les chats errants du village.

Un jour, alors qu'elle se promenait près de la lisière de la forêt, Mai découvrit un chaton abandonné, frêle et affamé. Son petit cœur se serra de compassion en voyant l'état du chaton. Sans hésitation, elle prit le chaton dans ses bras et décida de le ramener chez elle.


Chez elle, Mai nourrit le chaton, lui donna de l'eau fraîche et lui offrit un endroit douillet pour se reposer. Le chaton, reconnaissant pour cet acte de bonté, se blottit contre Mai et ronronna doucement. Mai décida de nommer le chaton "Luna" en raison de ses yeux brillants comme la lune.

Au fil des jours, Mai et Luna devinrent inséparables. Ils passaient leurs journées à explorer la nature ensemble, à jouer dans les champs et à se reposer à l'ombre des grands arbres. Mai prenait grand soin de Luna, veillant à ce qu'il soit toujours heureux et en bonne santé.


Cependant, un jour, Mai apprit l'existence d'un mystérieux "Chat Sauvage", qui était le roi des chats de la forêt. On disait qu'il vivait au cœur de la forêt dense, régnant sur tous les félins des environs. Malgré les avertissements des adultes, Mai était déterminée à rencontrer le Chat Sauvage et à lui offrir de la nourriture.


Armée de courage et de détermination, Mai se mit en route vers la forêt profonde, Luna à ses côtés. Après une longue marche à travers les sentiers sinueux de la forêt, ils arrivèrent enfin au repaire du Chat Sauvage.


Le Chat Sauvage était imposant et majestueux, avec un pelage aussi noir que la nuit. Mai s'approcha lentement de lui, lui offrant humblement un bol de nourriture savoureuse. Le Chat Sauvage, touché par l'acte de générosité de Mai, accepta gracieusement le don et lui permit de rester un moment avec lui.

Mai et Luna passèrent le reste de la journée à jouer avec le Chat Sauvage et les autres chats de la forêt. À la fin de la journée, le Chat Sauvage remercia Mai pour sa gentillesse et lui promit de veiller sur elle et sur Luna.


De retour chez elle, Mai réalisa que l'amour et la compassion qu'elle avait pour les animaux étaient plus forts que jamais. Elle savait maintenant que peu importe les obstacles ou les dangers, tant qu'elle avait Luna à ses côtés, elle pouvait surmonter n'importe quoi. Et ainsi, Mai et Luna continuèrent à partager leur amour et leur amitié, jour après jour, dans la vallée verdoyante qui était leur foyer.

======

=======================

Attention CODE: 2G5Fo68vOAx4scGTrDdI1w

=======================

vendredi 1 décembre 2023

autoIT - auto click

#cs ----------------------------------------------------------------------------

 AutoIt Version: 3.3.14.5


#ce ----------------------------------------------------------------------------

; Script Start - Add your code below here

#cs -----------------
Local $aPos = MouseGetPos()
MsgBox(0, "Mouse x, y:", $aPos[0] & ", " & $aPos[1])

Local $Mouse1_x =  $aPos[0]
Local $Mouse1_y =  $aPos[1]

#ce -----------
#include <GUIConstantsEx.au3>
#include <WindowsConstants.au3>
#Include <Misc.au3>
#include <ImageSearchEasy.au3>


HotKeySet("{ESC}", "MyExit")
CreateWindows()

; Vi tri ban hang tren ban do nho : 1879 , 1000
;Vi tri mo ban hang: 1122, 740

Func CreateWindows()
    ; Crée une interface graphique avec un contrôle bouton
    Global $main = GUICreate("rage_mage",280, 250)
    WinSetOnTop($main, "", 1)
    Local $idOK = GUICtrlCreateButton("Close", 90, 120, 50, 25)
    Local $idMousePos = GUICtrlCreateButton("Mouse Pos", 5, 120, 80, 25)

   Local $idRune = GUICtrlCreateButton("auto click", 5, 90, 85, 25)
   Local $idRune2 = GUICtrlCreateButton("auto elite", 95, 90, 85, 25)



    ; Affiche l'interface graphique.
    GUISetState(@SW_SHOW, $main)
    ; Boucle jusqu'à ce que l'utilisateur quitte.
       While 1
        Switch GUIGetMsg()
            Case $GUI_EVENT_CLOSE, $idOK
                ExitLoop

            Case $idRune
               Sleep(1000)
               $il = 1
               While $il < 2202
                  GUICtrlCreateLabel("auto click: " & $il, 5, 5, 150, 20)
                  Sleep(1000)
                  MouseClick("left", 777, 480, 1,5)
                  Sleep(45000)
                  MouseClick("left", 767, 884, 1,5);
                  Sleep(5000)
                  $il = $il + 1
               WEnd

            Case $idRune2
               Sleep(1000)
               $il = 1
               While $il < 2202
                  GUICtrlCreateLabel("auto elite: " & $il, 5, 5, 150, 20)
                  Sleep(1000)
                  MouseClick("left", 769, 783, 1,5)
                  Sleep(45000)
                  MouseClick("left", 768, 914, 1,5);
                  Sleep(10000)
                  $il = $il + 1
               WEnd

            Case $idMousePos
                ; Run getMousePosition
                Local $mPos = getMousePosition()
                Local $tmp3 = "Mouse x: " & $mPos[0] & ", Mouse y: " & $mPos[1]
                GUICtrlCreateLabel($tmp3, 5, 5, 300, 20) ;message, column, row, width, heigh
        EndSwitch
     WEnd


    ; Supprime la GUI précédente et tous les contrôles.
    GUIDelete($main)
 EndFunc   ;==>CreateWindows


Func getMousePosition()
    Local $x = 1, $pos
    While $x = 1 ; Loop until the mouse is clicked.
            if _IsPressed("01") then ; If left mouse is pushed.
                $pos = MouseGetPos() ; Record the position.
                $x = 0 ; Change x to end loop.
            EndIf
    WEnd
    Return $pos
 EndFunc;==>getMousePosition



Func MyExit()
  Exit
EndFunc

mardi 21 novembre 2023

doc co cuu kiem

 


<br/> 

<a href="https://ydepdeploihayhay.blogspot.com/2023/11/oc-co-cuu-kiem-chuong-3.html">Chương trước </a> &nbsp;&nbsp;&nbsp;

<a href="https://ydepdeploihayhay.blogspot.com/2023/11/oc-co-cuu-kiem.html">Trang chủ</a>&nbsp;&nbsp;&nbsp;

  <a href="https://ydepdeploihayhay.blogspot.com/2023/11/oc-co-cuu-kiem-chuong-5.html">Chương sau</a>&nbsp;&nbsp;&nbsp;


https://ydepdeploihayhay.blogspot.com/2023/11/oc-co-cuu-kiem-chuong-2.html

https://ydepdeploihayhay.blogspot.com/2023/11/oc-co-cuu-kiem-chuong-3.html

https://ydepdeploihayhay.blogspot.com/2023/11/oc-co-cuu-kiem-chuong-4.html

https://ydepdeploihayhay.blogspot.com/2023/11/oc-co-cuu-kiem-chuong-5.html

lundi 13 novembre 2023

Il était une fois

 

==========

Il était une fois, dans une grande maison luxueuse au cœur de la ville, vivait un jeune garçon nommé Hải. Issu d'une famille aisée, Hải avait toujours eu tout ce qu'il désirait matériellement, mais il possédait également un cœur généreux et une compassion profonde pour les moins fortunés.

Un jour, alors qu'il se promenait dans les rues animées de la ville, Hải fut frappé par la vue des personnes sans-abri qui mendiaient pour survivre. Son cœur se serra en voyant leur souffrance et leur détresse. Il se sentit inspiré à faire quelque chose pour les aider.


De retour chez lui, Hải décida de demander à ses parents s'ils pouvaient acheter de la nourriture pour distribuer aux sans-abri. Ses parents furent d'abord surpris par sa demande, mais ils furent également touchés par sa compassion et son désir d'aider les autres.


Après une discussion en famille, ses parents décidèrent de soutenir l'initiative de Hải. Ils achetèrent une grande quantité de nourriture, y compris des sandwichs, des fruits, de l'eau et d'autres denrées non périssables, pour distribuer aux personnes dans le besoin.

Le lendemain, Hải et ses parents se rendirent dans les quartiers les plus défavorisés de la ville, portant avec eux des sacs remplis de nourriture. Ils distribuèrent généreusement les repas aux sans-abri, offrant un peu de réconfort et d'espoir à ceux qui en avaient désespérément besoin.


Au fur et à mesure que la journée avançait, Hải fut rempli de joie en voyant les sourires sur les visages des personnes qu'il aidait. Il se sentait reconnaissant d'avoir la chance de faire une différence dans la vie des autres, même si c'était simplement en leur offrant un repas chaud et nourrissant.

De retour chez lui ce soir-là, Hải se sentit rempli d'un profond sentiment de satisfaction. Il savait que même en tant que jeune garçon, il pouvait avoir un impact positif sur le monde qui l'entourait en partageant son amour et sa compassion avec ceux qui étaient dans le besoin. Et ainsi, avec le soutien de sa famille, Hải continua à aider les moins fortunés de sa communauté, apportant un peu de lumière dans les moments sombres de leur vie.

=============

=======================

=======================

mardi 31 octobre 2023

Find in list the entities have SUM= k

 

Find in list the entities have SUM= k

ex: [1,5,8,1,2]

k = 13


 should return 5,8


using System;

using System.Collections.Generic;

using System.Linq;

public class Program

{

public static void Main()

{

int[] numbers = new int[5]{1,5,8,3,7}; 

int k = 13;

var originearray = numbers;

var toReturn = new List<int>();

int sum = 0;

while(sum != k && numbers.Length > 0){

for(int i =0; i< numbers.Length ; i++){

var tmp = sum;

sum = sum + numbers[i];

if(sum <= k){

toReturn.Add(numbers[i]);

}

if(sum > k){

sum = tmp;

}

}

if(sum != k){

sum =0;

numbers = numbers.Skip(1).ToArray();

toReturn = new List<int>();

}

}

foreach(var item in toReturn){

Console.WriteLine(item);

}

if(sum == k){

Console.WriteLine("Found");

}

else{

Console.WriteLine("Not Found");

}

var possitions = new List<int>();

for(int i = 0; i<toReturn.Count; i++ ){

for(int j = 0; j < originearray.Length; j++){

if(toReturn[i] == originearray[j] && !possitions.Contains(j)){

possitions.Add(j);

}

}

}

foreach(var item in possitions){

Console.WriteLine(item);

}

}

}



Pogo Stick, bâton Sauteur pour Enfants à partir de 5 Ans, Conception Tendance, Poids Max. 50 kg

vendredi 20 octobre 2023

The Next methode should return the smallest integer which is > n

 The Next methode should return the smallest integer which is > n , and whose digits are different from all n's digits


Ex:

Console.WriteLine(Solution.Next(2)); // 3
Console.WriteLine(Solution.Next(901));// 2222
Console.WriteLine(Solution.Next(958));// 1000
Console.WriteLine(Solution.Next(3025));// 4111
Console.WriteLine(Solution.Next(654321));// 700000



// C# code​​​​​​‌​‌​​‌‌​‌‌‌​​​‌​‌​‌​‌​​​‌ below

using System;

using System.IO;

using System.Collections.Generic;

using System.Collections;

using System.Linq;

using System.Text;

using System.Threading;


class Solution

{

    public static int Next(int n)

    {

        if(n <= 0){

            throw new ArgumentException("n must be integer possitive");

        }

        int m = n + 1;

        while (!CompareDigits2number(n,m)){

            m = m +1;

        }        

        if(m >= Math.Pow(2,31)){

            return -1;

        }

        return m;

    }


    public static char[] numberToArray(int n){

        var nStr = n.ToString();

        var nArray = new char[nStr.Length];

        for(int i = 0; i < nStr.Length; i++){

            nArray[i] = nStr[i];

        }

        return nArray;

    }


    public static bool CompareDigits2number(int n, int m){

        var arrayN = numberToArray(n);

        var arrayM = numberToArray(m);


        foreach(var item in arrayN){

            if(arrayM.Contains(item)){

                return false;

            }

        }

        return true;

    }

}

mercredi 18 octobre 2023

10 câu hỏi về Python - 5


111. **Python có hỗ trợ module nào để làm việc với dữ liệu JSON không? Nếu có, làm thế nào để sử dụng module đó?**

    - Trả lời mẫu: Có, Python có module `json` để làm việc với dữ liệu JSON. Bạn có thể sử dụng `json.loads()` để phân tích một chuỗi JSON thành cấu trúc dữ liệu Python và `json.dumps()` để chuyển đổi một cấu trúc dữ liệu Python thành chuỗi JSON.

112. **Làm thế nào để kiểm tra xem một chuỗi có chứa một từ cụ thể không trong Python?**

    - Trả lời mẫu: Để kiểm tra xem một chuỗi có chứa một từ cụ thể không trong Python, bạn có thể sử dụng từ khóa `in`. Ví dụ: `if "word" in my_string:`.

113. **Python có hỗ trợ module nào để làm việc với dữ liệu XML không? Nếu có, làm thế nào để sử dụng module đó?**

    - Trả lời mẫu: Có, Python có module `xml.etree.ElementTree` để làm việc với dữ liệu XML. Bạn có thể sử dụng module này để phân tích và xử lý cấu trúc XML.


114. **Làm thế nào để tạo một chuỗi ngẫu nhiên độ dài cố định trong Python?**

    - Trả lời mẫu: Để tạo một chuỗi ngẫu nhiên độ dài cố định trong Python, bạn có thể sử dụng module `random` kết hợp với các ký tự có thể xuất hiện trong chuỗi. Ví dụ: 

    ```python

    import random

    import string

    random_string = ''.join(random.choices(string.ascii_letters + string.digits, k=10))

    ```

115. **Python có hỗ trợ module nào để làm việc với dữ liệu HTML không? Nếu có, làm thế nào để sử dụng module đó?**

    - Trả lời mẫu: Có, Python có module `BeautifulSoup` từ thư viện BeautifulSoup để làm việc với dữ liệu HTML. Bạn có thể sử dụng BeautifulSoup để phân tích và trích xuất thông tin từ HTML.


116. **Làm thế nào để đọc một tệp văn bản dài nhiều dòng trong Python?**

    - Trả lời mẫu: Để đọc một tệp văn bản dài nhiều dòng trong Python, bạn có thể mở tệp bằng hàm `open()` và sau đó sử dụng vòng lặp để đọc từng dòng. Ví dụ:

    ```python

    with open('file.txt', 'r') as file:

        for line in file:

            print(line)

    ```

117. **Python có hỗ trợ module nào cho việc gửi HTTP requests không? Nếu có, làm thế nào để sử dụng module đó?**

    - Trả lời mẫu: Có, Python có module `requests` để gửi HTTP requests. Bạn có thể sử dụng `requests.get()` để gửi yêu cầu GET và `requests.post()` để gửi yêu cầu POST.


118. **Làm thế nào để kiểm tra xem một biến có tồn tại trong Python hay không?**

    - Trả lời mẫu: Để kiểm tra xem một biến có tồn tại trong Python hay không, bạn có thể sử dụng từ khóa `in` kết hợp với hàm `globals()` hoặc `locals()`. Ví dụ:

    ```python

    if 'my_var' in globals():

        print("Variable exists!")

    ```

119. **Python có hỗ trợ module nào cho việc gửi và nhận email không? Nếu có, làm thế nào để sử dụng module đó?**

    - Trả lời mẫu: Có, Python có module `smtplib` cho việc gửi email và module `imaplib` hoặc `poplib` cho việc nhận email. Bạn có thể sử dụng `smtplib` để gửi email thông qua SMTP và `imaplib` hoặc `poplib` để nhận email thông qua IMAP hoặc POP3.


120. **Làm thế nào để kiểm tra xem một chuỗi có phải là một số nguyên không âm trong Python?**

    - Trả lời mẫu: Để kiểm tra xem một chuỗi có phải là một số nguyên không âm trong Python, bạn có thể sử dụng phương thức `isdigit()` để kiểm tra xem chuỗi có chứa toàn bộ là các chữ số không và sử dụng `int()` để chuyển đổi chuỗi thành số nguyên. Ví dụ:

    ```python

    my_string = "123"

    if my_string.isdigit() and int(my_string) >= 0:

        print("Positive integer!")

    ```

CODE: DsG3CiXpiA6Vfb7UHV57sw

=======================

dimanche 15 octobre 2023

find file universe-formula

 You don’t remember where you saved the file universe-formula . 

The only thing you remember about this file is you put it somewhere in a sub-folder of /tmp/documents . 

Implement the method string LocateUniverseFormula() to locate universe-formula and then return the absolute path of the file (from the file system root). 

/tmp/documents can contain nested sub-folders and universe-formula can belong to any one of them. 

If universe-formula cannot be found, then your program should return null . 

Example : LocateUniverseFormula() returns /tmp/documents/a/b/c/universe-formula if universeformula is found into the folder /tmp/documents/a/b/c .



using System; 

using System.IO; 

using System.Collections.Generic; 

using System.Linq;

public class Answer {

    public static string LocateUniverseFormula() 

 { 

 List toReturns = new List(); 

 List files = Directory.GetFiles("documents", "*",SearchOption.AllDirectories).ToList(); 

 foreach (var item in files)

 var toReturn = Path.Combine("/tmp", item); 

 if(item.Contains("universe-formula")){ 

 toReturns.Add(toReturn); 

 } 

 } 

 if(toReturns.Count() == 0)

{ return null; } 

 return toReturns.FirstOrDefault(); 

 } 

}

samedi 14 octobre 2023

Implémentez la méthode LongestProfit(data) - Longest sequence

 Objectif On vous donne un tableau d'entiers, qui représentent les bénéfices nets mensuels d'une entreprise. L'entreprise souhaite que vous recherchiez la plus longue séquence de mois (ordonnés chronologiquement) dont le bénéfice augmente, et que vous retourniez la longueur. 

La séquence peut contenir des mois non adjacents.   

 Implémentation Implémentez la méthode LongestProfit(data) qui prend comme entrée un tableau d'entiers ( data ), représentant des bénéfices mensuels consécutifs. 

Par example : [-1, 9, 0, 8, -5, 6, -24] 

Votre méthode LongestProfit  doit renvoyer un nombre entier représentant la longueur de la plus longue séquence de bénéfices mensuels croissants. 

Pour l'exemple ci-dessus, la sortie correcte serait le nombre entier suivant : 3  (la séquence pourrait être [-1, 0, 6] ou [-1, 0, 8] ).



using System;

using System.Collections.Generic;

using System.Linq;

public class Program

{

public static void Main()

{

int[] seq = new int[] { -1, 9, 0, 8, -5, 6, -24 };

        var result = longestSeq3(seq);

foreach(var i in result){

Console.WriteLine(i);

}

}

private static List<int> longestSeq3(int[] seq)

    {

        int maxDist = 2;

        List<int> result = new List<int>();


        for (int i = 0; i < seq.Length; i++)

        {

            int current = seq[i];

            int dist = Math.Abs(i - current);

            if (dist >= 0 && dist <= maxDist)

            {

                if (result.Count > 0 && current <= result.Last())

                {

                    continue;

                }

                result.Add(current);

            }

        }


        return result;

    }

}

vendredi 13 octobre 2023

Implémentez la méthode ComputeCheckDigit(identificationNumber)

 Afin de détecter des erreurs dans des identifiants numériques, une clé de contrôle est souvent ajoutée à cet identifiant. 

Implémentez la méthode ComputeCheckDigit(identificationNumber) qui prend en entrée un identifiant (sous la forme d'une chaîne de caractères) et qui retourne la clé de contrôle en utilisant l'algorithme qui suit : 

Faites la somme des chiffres situés à des positions paires (positions 0, 2, 4, etc.). 

Multipliez le résultat par trois. 

Ajoutez à ce nombre la somme des chiffres situés à des positions impaires (positions 1, 3, 5, etc.). 

Prenez le dernier chiffre de ce résultat. 

Si ce nombre n'est pas 0, soustrayez le à 10. Sinon, gardez 0. 

Retournez le chiffre résultant (On suppose que le premier chiffre situé à gauche a pour position 0) 

Exemple: Soit l'identifiant 39847 : 

Sommez les chiffres aux positions paires : 3 + 8 + 7 = 18 

Multipliez par trois : 18 x 3 = 54 

Ajoutez les chiffres situées aux positions impaires : 54 + (9 + 4) = 67 

Le dernier chiffre est 7 

Soustrayez 7 à 10 : 10 - 7 = 3 

Le résultat attendu pour 39847  est 3 . 

Contraintes: La longueur de identificationNumber peut varier de 1 à 12 caractères.



public static int ComputeCheckDigit(string identificationNumber)  

        // Write your code here

        // To debug: Console.Error.WriteLine("Debug messages...");

        if(identificationNumber.Length < 1 || identificationNumber.Length > 12){

            throw new ArgumentException("invalid input");

        }

        int totalPair = 0;

        for(int i = 0; i < identificationNumber.Length; i = i +2){

            //Console.WriteLine(identificationNumber[i]);

            totalPair = totalPair + int.Parse(identificationNumber[i].ToString());

        }

        int multipleValue= totalPair * 3;

        int tmp = multipleValue;

        for(int i = 1; i < identificationNumber.Length; i = i +2){

            //Console.WriteLine(identificationNumber[i]);

            tmp = tmp + int.Parse(identificationNumber[i].ToString());

        }


        var lastdigit = tmp % 10;

int toReturn = 0;

if(lastdigit != 0){

toReturn = 10 - lastdigit;

}


        return toReturn;

jeudi 12 octobre 2023

Find smallest interval between 2 entity in one List

Find smallest interval between 2 entity in one List<int>




 using System;

using System.Linq;

using System.IO;

using System.Text;

using System.Collections;

using System.Collections.Generic;

using System.Text.Json;

using System.Text.Json.Serialization;

using System.Runtime.Serialization;


public class Solution {


    public static int FindSmallestInterval(List<int> numbers) {

        // Write your code here

        if(numbers.Count < 2 || numbers.Count >100000){

            throw new ArgumentException("invalid input");

        }

        

        var arrayNumbers = numbers.ToArray();

        Array.Sort(arrayNumbers);


        int toReturn = int.MaxValue;

        for (int i = 1; i < arrayNumbers.Length; i++)

        {

            toReturn = Math.Min(toReturn, arrayNumbers[i] - arrayNumbers[i - 1]);

        }


        return toReturn;

    }


auto play

mardi 3 octobre 2023

Goal: compute the "size on disk"

 You may have noticed that files have two sizes. 

The "file size" and the "size on disk", which is always greater or equal than the file size. Storage media are divided into "clusters". 

A file can occupy many clusters, but a cluster can only be allocated to one single file. The "size on disk" corresponds to the total size of all the clusters allocated to that file. Given the cluster size of a disk and a file size, compute its size on disk. 

Example A disk has a cluster size of 512 bytes. A file has a size of 1500 bytes. 2 clusters (512*2 = 1024 bytes) would not be enough to store this file. 4 clusters (2048 bytes) would be too much, one of the cluster would be empty. The correct number of clusters is 3. The total size of these clusters is (512 * 3 = 1536 bytes), which is the size on disk of this file.


using System;
public class Program
{
public static void Main()
{
int clusterSize = 512;
int fileSize = 1500;
var toReturn = 0;
if(fileSize % clusterSize > 0){
int nbCluster = (int) (fileSize / clusterSize);
toReturn = (nbCluster + 1) * clusterSize;
}

                if(fileSize % clusterSize == 0){
toReturn = fileSize;
}
Console.WriteLine(toReturn);
}
}

apprenons une nouvell danse

 apprenons une nouvell danse ! (problem: optimiser RAM)



using System;


public class Dancer

{

    /// <summary>Computes the position of the dancer.</summary>

    /// <returns>the position at step​​​​​​‌​‌​​‌‌​​​‌‌‌‌​‌​​‌​​‌‌​​ <c>n</c>.</returns>

    public static int GetPositionAt(int n)

    {

        if(n < 0 || n > 2147483647){

            throw new ArgumentException("invalid input");

        }


        int position = 0;

        int step1 = 1;

        position = position + step1;

        n = n - 1;

        int step2 = -2;

        position = position + step2;

        n -= 1;

        while( n > 0 )

        {

            position = position + ( step2 - step1 );

            int buffer = step1;

            step1 = step2;

            step2 = step2 - buffer;

            n -= 1;

        }

        return position;

}

}


calcul total price after discount with smallest price

 calcul total price after discount with smallest price



public static int CalculateTotalPrice(int[] prices, int discount)

    {

        // Write your code here

        // To debug: Console.Error.WriteLine("Debug messages...");

        if(discount < 0 || discount > 100 || prices.Length <= 0 || prices.Length >=100){

            throw new ArgumentException("invalid input!");

        }

        

        double total = 0.0;

        Array.Sort(prices);

        for (int i = 1; i< prices.Length ; i++){

            //Console.WriteLine(prices[i]);

            if(prices[i] <= 0 || prices[i] >= 100000){

                throw new ArgumentException("invalid price!");

            }

            total = total + prices[i];

        }


        double toReturn = total + prices[0] * ((double)(100 - discount)/100);

        

        return (int)toReturn;

    }





Calculate the total number of chess pairs among n players

 Calculate the total number of chess pairs among n players


class Solution

{

    /// Counts the number of pairs for n​​​​​​‌​‌​​‌‌​​​‌‌‌​‌​‌‌​​​​‌​​ players.

    public static int Count(int n)

    {

        if(n< 2 || n > 10000){

            throw new ArgumentException("invalid input!");

        }

        double toReturn = n * (n-1) /2 ;

        return (int)toReturn; 

    }


    

}

lundi 2 octobre 2023

the sum of integers whose index is between n1 and​​​​​​‌​‌​​‌‌​​​‌​‌​​​​​‌​‌​​‌‌ n2

the sum of integers whose index is between n1 and​​​​​​‌​‌​​‌‌​​​‌​‌​​​​​‌​‌​​‌‌ n2


 using System;

class Solution

{

    /// <returns>the sum of integers whose index is between n1 and​​​​​​‌​‌​​‌‌​​​‌​‌​​​​​‌​‌​​‌‌ n2</returns>

public static int Calc(int[] array, int n1, int n2) {

        if(n1 < 0 || n1 > n2 || n2 > array.Length || n1 > array.Length){

            throw new ArgumentException("invalid input");

        }

        int sum = 0;

        for(int i = n1; i <= n2; i++){

            sum = sum + array[i];

        }

        return sum;

    }

}

Anagrame: 2 word with the sema letters but different of order

 Anagrame: 2 word with the sema letters but different of order


using System;

using System.Linq;

using System.IO;

using System.Text;

using System.Collections;

using System.Collections.Generic;

using System.Text.Json;

using System.Text.Json.Serialization;

using System.Runtime.Serialization;


public class Solution {


    /**

     * @param wordA The first word, contains only uppercase and lowercase letters.

     * @param wordB The second word, contains only uppercase and lowercase letters.

     * @return True if the two words are anagrams, false otherwise.

     */

    public static bool IsAnagram(string wordA, string wordB) {

        // Write your code here

        if(wordA.Length > 30 || wordB.Length > 30){

            throw new ArgumentException("string is too long");

        }

        

        wordA = wordA.ToLower();

        wordB = wordB.ToLower();


        char[] arrayA = new char[wordA.Length]; 

        for (int i = 0; i < wordA.Length; i++) {  

            arrayA[i] = wordA[i];  

        }  


        char[] arrayB = new char[wordB.Length]; 

        for (int j = 0; j < wordB.Length; j++) {  

            arrayB[j] = wordB[j];  

        }  


        if(arrayA.Length != arrayB.Length){

            return false;

        }


        Array.Sort(arrayA);

        Array.Sort(arrayB);


        if (arrayA.SequenceEqual(arrayB))

        {

            return true;

        }


        return false;

    }


    /* Ignore and do not change the code below */


    /**

     * Try a solution

     * @param output True if the two words are anagrams, false otherwise.

     */

    private static void TrySolution(bool output) {

        Console.WriteLine("" + JsonSerializer.Serialize(output));

    }


    public static void Main(string[] args) {

        TrySolution(IsAnagram(

            JsonSerializer.Deserialize<string>(Console.ReadLine()),

            JsonSerializer.Deserialize<string>(Console.ReadLine())

        ));

    }

    /* Ignore and do not change the code above */

}


============================================

solution 2:


public static bool IsAnagram(string wordA, string wordB) {
        // Write your code here
         if(wordA.Length > 30 || wordB.Length > 30){
            throw new ArgumentException("word is too long");
        }    
       
        if (wordA.Length != wordB.Length)
        {
            return false;
        }

        wordA = wordA.ToLower();
        wordB = wordB.ToLower();
        char[] arrayA = wordA.ToCharArray();
        char[] arrayB = wordB.ToCharArray();
       
        Array.Sort(arrayA);
        Array.Sort(arrayB);
       
        return arrayA.SequenceEqual(arrayB);
    }

DouDigits

 DouDigits

ex: 12, 110, 373333


using System;

using System.Linq;

using System.IO;

using System.Text;

using System.Collections;

using System.Collections.Generic;


class Solution

{


    public static string IsDuoDigit(int number)

    {

        // Write your code here

        // To debug: Console.Error.WriteLine("Debug messages...");

        var sbsNum = Math.Abs(number);

        var numStr = sbsNum.ToString();

        List<string> list = new List<string>();

        for(int i = 0; i< numStr.Length; i++){

            if(!list.Contains(numStr[i].ToString())){

                list.Add(numStr[i].ToString());

            }

        }


        if(list.Count <= 2 ){

            return "y";

        }

        

        return "n";

    }


    /* Ignore and do not change the code below */

    static void Main(string[] args)

    {

        int number = int.Parse(Console.ReadLine());

        var stdtoutWriter = Console.Out;

        Console.SetOut(Console.Error);

        string result = IsDuoDigit(number);

        Console.SetOut(stdtoutWriter);

        Console.WriteLine(result);

    }

    /* Ignore and do not change the code above */

}



dimanche 1 octobre 2023

Merge stones 1 & 1 --> 2

 Merge stones  1  & 1  --> 2



using System;

using System.Collections.Generic;

using System.Linq;

public class Program

{

public static void Main()

{

List<int> stones = new List<int>() {1,1,2,4,5,5};

var max = stones.Max();

for(int j = 1; j <= max +1 ; j++){

var count = 0;

        for (int i = 0; i < stones.Count; i ++){

            if(stones[i] == j){

                count = count + 1;

            }

        }


        while (count > 1){

            merge(stones, j);

            count = count - 2;

        }

}

foreach(var i in  stones){

Console.WriteLine(i);

}

Console.WriteLine(stones.Count());

}

public static bool merge(List<int> stones, int number){

        var toReturn = false;

        var count = 0;

        for (int i = 0; i < stones.Count; i ++){

            if(stones[i] == number){

                count = count + 1;

            }

        }

        if(count >= 2){

            toReturn = true;

            stones.Remove(number);

            stones.Remove(number);

            stones.Add(number + 1);

        }


        return toReturn; 

    }

}

AddDrama - If number of "!" is odd , add 1 more "!" anf Change "." to "!"

AddDrama 

Change  "."  to "!"

If number of "!" is odd , add 1 more "!"



using System;

public class Program

{

public static void Main()

{

string text = "hello. mot! hai!! ba!!!";

string toReturn = "";

        var temp = text.Split(' ');

        foreach (var item in temp){

            int count = 0;

            for (int i = 0; i < item.Length; i ++){

                

                if(item[i] == '!'){

                    count = count + 1;

                }                

            }

if(count % 2 == 1){

toReturn = string.Format("{0}{1}{2}",toReturn,item,"!" );

}

else{

toReturn = string.Format("{0}{1}",toReturn,item );

}

            

        }

        toReturn = toReturn.Replace('.','!');

Console.WriteLine(toReturn);

}

}

FindingPath of list of string to print a word (ex: codingame)

 public class Program

{
      public static void Main()
      {
            List<string> listStr = new List<string>();
            listStr.Add("***a    ");
            listStr.Add("   e*    ");
            listStr.Add("    ***d**    ");
            listStr.Add("         e****    ");
            listStr.Add("             hgj***    ");
            
            string[,] grid = new string[35,35];
            
            for (int i = 0; i < listStr.Count; i++){
                  for(int j = 0; j < listStr[i].Length; j++){
                        grid[i,j] = listStr[i][j].ToString();
                        
                  }
            }
            
            Console.WriteLine(grid[0,0]);
            Console.WriteLine(grid[0,3]);
            Console.WriteLine(grid[1,3]);
            
            Dictionary<string, string> dict = new Dictionary<string, string>();
            
            for(int k = 0; k<35;k++){
                  for (int m = 0; m<35; m++){
                        //Console.WriteLine(grid[k,m]);
                        var sub_dict = SearchPath (k, m, grid);
                        foreach(var item in sub_dict){
                              if(!dict.ContainsKey(item.Key)){
                                    dict.Add(item.Key, item.Value);
                              }
                        }
                  }     
            }
            
            string strReturn = "";
            
            foreach(var dic in dict){
                  if(dic.Value != "*" && dic.Value != null){
                        //Console.Write(dic.Value);
                        strReturn = strReturn + dic.Value;
                  }
            }
            
            Console.WriteLine(strReturn.Replace(" ",""));
            
      }
      
      public static Dictionary<string,string> SearchPath (int x, int y, string[,] grid){
            Dictionary<string,string> toRetrun = new Dictionary<string,string>();
            if(grid[x,y] != null){
                  toRetrun.Add(String.Format("{0}{1}",(x).ToString(),y.ToString()), grid[x,y].ToString());
                  if(x - 1 >= 0 && x -1 < 35){
                        if(grid[x-1,y] != null && grid[x-1,y] != ""){
                              toRetrun.Add(String.Format("{0}{1}",(x-1).ToString(),y.ToString()), grid[x-1,y].ToString());
                        }
                  }
                  
                  if(x + 1 >= 0 && x+1 < 35){
                        if(grid[x+1,y] != null && grid[x+1,y] != ""){
                              toRetrun.Add(String.Format("{0}{1}",(x+1).ToString(),y.ToString()), grid[x+1,y].ToString());
                        }
                  }
                  
                  if(y - 1 >= 0 && y -1 < 35){
                        if(grid[x,y - 1] != null && grid[x,y - 1] !=""){
                              toRetrun.Add(String.Format("{0}{1}",x.ToString(),(y - 1).ToString()), grid[x,y - 1].ToString());
                        }
                  }
                  
                  if(y + 1 >= 0 && y+1 < 35){
                        if(grid[x,y + 1] != null && grid[x,y + 1] != ""){
                              toRetrun.Add(String.Format("{0}{1}",x.ToString(),(y+1).ToString()), grid[x,y+1].ToString());
                        }
                  }
                  
                  
            }
            
            
            return toRetrun;
      }
}

ClosestToZero(int[] ints)

 //return gia tri gan 0 nhat

using System;

using System.Linq;

class A 

{

    /// This method finds the number closest to​​​​​​‌​‌​​‌​‌‌‌‌‌‌‌​‌‌‌​​‌​‌‌‌ zero.

    public static int ClosestToZero(int[] ints) 

    {

        foreach(int i in ints){

            if(i < -2147483647 || i> 2147483647){

                throw new ArgumentException("Out of Range!");

            }

        }

        

        if(ints == null || ints.Length == 0){

            throw new ArgumentException("ints can not null or empty");

        }


        var nearest = ints.OrderBy(x => Math.Abs((long) x - 0)).First();

        int toReturn = nearest;

        for(int i = 0; i < ints.Length; i++){

            if(Math.Abs(ints[i])  == Math.Abs(nearest) && ints[i] > 0){

                toReturn = ints[i];

            }

        }


        return toReturn;



    }

}

Dans la culture chinoise, il est commun lors des célébrations de donner des "enveloppes rouges"

 Dans la culture chinoise, il est commun lors des célébrations de donner des "enveloppes rouges" (##) contenant un peu d'argent. Le plus souvent, les générations adultes donnent aux générations plus jeunes. Vous souhaitez construire une application WeChat pour aider les grand-parents à répartir leur budget de don entre leurs petits-enfants. Écrivez un programme qui calcule le nombre de dons "porte-bohneur" (égaux à 8) en fonction du budget, money , et du nombre de petits-enfants, giftees .  Fonctionnement De nombreuses règles, mêlant tradition et superstition, encadre ce don : Les dons ne doivent pas contenir le montant 4 (#), car cela sonne comme "mort" (#).  Il est de bonne augure de donner un montant de 8 (#), car cela sonne comme "fortune" (#).  Il serait mal vu de ne rien donner à l'un des petits-enfants.  Votre algorithme doit donc retourner le nombre de dons égaux à 8 en respectant les règles suivantes :  Dépenser l'intégralité du budget (sauf s'il y a suffisamment de budget pour donner 8 à tout le monde) Ne donner aucun 4 (par tradition, le budget ne sera jamais à 4). Ne donner aucun 0 (sauf si le budget n'est pas suffisant). Donner un maximum de 8 une fois les règles ci-dessus respectées Implémentation Implémentez la méthode LuckyMoney(money, giftees) qui : prend en entrées les entiers money et giftees avec : 0 <= money < 100 0 < giftees < 10 et retourne le nombre de dons égaux à 8 sous forme d'un entier.



using System;

using System.Linq;

using System.IO;

using System.Text;

using System.Collections;

using System.Collections.Generic;


class Solution

{


    public static int LuckyMoney(int money, int giftees)

    {

        // Write your code here

        // To debug: Console.Error.WriteLine("Debug messages...");

        if(money < 0 || money >= 100 || giftees <= 0 || giftees >= 10){

            //throw new ArgumentException("Invalid input");

return giftees;

        }


        if(money < 8 ){

            return 0;

        }

        

        if((money / 8) == giftees){

            return money / 8;

        }


        if(money % 8 == 0 && money/8 < giftees){

            return (int)money/8 - 1;

        }


        if(money/8 < giftees && (money % 8) % 4 == 0 ){

            return 0;

        }


        if(money/8 < giftees && (money % 8) % 4 != 0 ){

            return (int)money/8;

        }


        return -1;

    }


    /* Ignore and do not change the code below */

    static void Main(string[] args)

    {

        int money = int.Parse(Console.ReadLine());

        int giftees = int.Parse(Console.ReadLine());

        var stdtoutWriter = Console.Out;

        Console.SetOut(Console.Error);

        int gifts = LuckyMoney(money, giftees);

        Console.SetOut(stdtoutWriter);

        Console.WriteLine(gifts);

    }

    /* Ignore and do not change the code above */

}


samedi 23 septembre 2023

sự mạnh mẽ và đẹp đẽ của tình yêu

 ======

Có một chàng trai tên là Minh, sinh ra và lớn lên trong một gia đình nghèo ở một vùng quê xa xôi. Dù trong hoàn cảnh khó khăn, Minh luôn có niềm đam mê và tài năng với lập trình máy tính. Ông bà ngoại của Minh từng là những người thợ may, và từ khi còn nhỏ, Minh đã tự học lập trình từ những cuốn sách cũ và tìm kiếm trên Internet.

Những khả năng lập trình của Minh phát triển mạnh mẽ theo thời gian. Dù phải đối mặt với nhiều khó khăn trong cuộc sống, nhưng Minh không bao giờ từ bỏ ước mơ của mình. Anh cứ tiếp tục học và làm việc chăm chỉ, hy vọng một ngày nào đó sẽ có thể thay đổi số phận của mình và gia đình.


Trong khi Minh đang làm việc tại một công ty phần mềm nhỏ trong thành phố, anh đã gặp được Linh - một cô gái xinh đẹp và giàu có. Dù sống trong thế giới xa hoa và sang trọng, Linh vẫn biết đến giá trị thực sự của tình yêu và sự chân thành.

Minh và Linh đã dần dần trở thành bạn bè, và rồi một tình bạn chuyển biến thành tình yêu. Linh bắt đầu cảm thấy sự quý trọng và sự chân thành từ Minh, không chỉ là một người bạn tốt mà còn là một người bạn đồng hành trên con đường của mình.

Dù Minh không có gì ngoài tài năng và sự chân thành, nhưng đó cũng là những điều mà Linh trân trọng và yêu quý. Và sau bao nhiêu thử thách và khó khăn, Minh đã dám mơ ước và nói lời yêu Linh, dù biết rằng họ thuộc hai thế giới hoàn toàn khác nhau.


Cuối cùng, Linh cũng nhận ra rằng tình yêu không phân biệt giai cấp và địa vị xã hội. Linh đã từ bỏ mọi sự hoài nghi và tiếp tục cuộc sống cùng với Minh, bên nhau với tình yêu chân thành và sự quý trọng.


Câu chuyện về Minh và Linh là minh chứng rõ ràng cho sự mạnh mẽ và đẹp đẽ của tình yêu, và nhắc nhở chúng ta rằng đôi khi tình yêu có thể xuất phát từ những nơi không ngờ đến nhất, và không bao giờ bị hạn chế bởi địa vị hay tài sản.

=======

=======================

Attention CODE: q272caIs_qTDCBvNoGt5bw

=======================