1

i need help for fix my code from the lesson i get, i try to create simple script for scramble words in sentences like "the house is broken" became "broken the is house"..my code work as well but it scramble only by one word, like "THE" became "H.T.E", i try to use string.split method but i dont understand where i must change the code was into array. here my code and the result is

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;

[System.Serializable]
public class Word
{
    public string word;

    [Header("biarkan kosong untuk acak otomatis")]
    public string desiredRandom;

    public string GetString()
    {
        if (!string.IsNullOrEmpty(desiredRandom))
        {
            return desiredRandom;
        }

        string result = word;

        // **I'm try to split string here where i try to input that into array**
        string[] array = result.Split(' ');
        foreach (string token in array)
        {
            Debug.Log((token).ToString());
            word = token;
        }

        result = "";

        List<char> characters = new List<char>(word.ToCharArray());
        while (characters.Count > 0)
        {
            int indexChar = Random.Range(0, characters.Count - 1);
            result += characters[indexChar];
            characters.RemoveAt(indexChar);
        }
        return result;
    }
}

public class WordScramble : MonoBehaviour
{
    public Word[] words;

    [Header("UI Reference")]
    public CharObject prefab;
    public Transform container;
    public float space;
    public float lerpSpeed = 5;

    List<CharObject> charObjects = new List<CharObject>();
    CharObject firstSelected;

    public int currentWord;
    public static WordScramble main;

    void Awake()
    {
        main = this;
    }

    // Use this for initialization
    void Start()
    {
        ShowScramble(currentWord);
    }

    // Update is called once per frame
    void Update()
    {
        RepositionObject();
    }

    void RepositionObject()
    {
        if (charObjects.Count == 0)
        {
            return;
        }

        float center = (charObjects.Count - 1) / 2;
        for (int i = 0; i < charObjects.Count; i++)
        {
            charObjects[i].rectTransform.anchoredPosition
                = Vector2.Lerp(charObjects[i].rectTransform.anchoredPosition,
                new Vector2((i - center) * space, 0), lerpSpeed * Time.deltaTime);
            charObjects[i].index = i;
        }
    }

    public void ShowScramble()
    {
        ShowScramble(Random.Range(0, words.Length - 1));
    }

    public void ShowScramble(int index)
    {
        charObjects.Clear();
        foreach (Transform child in container)
        {
            Destroy(child.gameObject);
        }

        if (index > words.Length - 1)
        {
            Debug.LogError("index out of range between 0-" + (words.Length - 1).ToString());
            return;
        }

        // string result = huruf ;

        //  foreach (string words is word());

        char[] chars = words[index].GetString().ToCharArray();

        foreach (char c in chars)
        {
            CharObject clone = Instantiate(prefab.gameObject).GetComponent<CharObject>();
            clone.transform.SetParent(container);
            charObjects.Add(clone.Init(c));
        }
        currentWord = index;
    }

    public void Swap(int indexA, int indexB)
    {
        CharObject tmpA = charObjects[indexA];
        charObjects[indexA] = charObjects[indexB];

        charObjects[indexB] = tmpA;

        charObjects[indexA].transform.SetAsLastSibling();
        charObjects[indexB].transform.SetAsLastSibling();

        CheckWord();
    }

    public void Select(CharObject charObject)
    {
        if (firstSelected)
        {
            Swap(firstSelected.index, charObject.index);

            // unselect
            //firstSelected = null;
            firstSelected.Select();
            charObject.Select();
        }
        else
        {
            firstSelected = charObject;
        }
    }

    public void UnSelect()
    {
        firstSelected = null;
    }

    public void CheckWord()
    {
        StartCoroutine(CoCheckWord());
    }

    IEnumerator CoCheckWord()
    {
        yield return new WaitForSeconds(0.5f);

        string word = "";
        foreach (CharObject charObject in charObjects)
        {
            word += charObject.character;
        }

        if (word == words[currentWord].word)
        {
            currentWord++;
            ShowScramble(currentWord);
        }
    }
}

this for a result

no. 1 is a result for this code and no.2 is log from split string i try to add into array

maybe i can get help for this problem, i'm still learn for C#, i'm sorry if my code is mess up

derHugo
  • 83,094
  • 9
  • 75
  • 115

2 Answers2

3

Your code is assigning the splits in a loop to the word variable over and over, overwriting word at each time. Then you are splitting word into its chars and try to shuffle them. You should instead shuffle the array of splits.

Example using LINQ:

public static string[] ScrambleSentence(string sentence)
{
    var random = new Random();
    return sentence.Split(' ').OrderBy(x => random.Next()).ToArray();
}
adjan
  • 13,371
  • 2
  • 31
  • 48
0

Here is a simple way to randomize word positions in a text

var rd = new Random();
string[] words = text.Split(' ').OrderBy(w => rd.Next()).ToArray();

// If you want a simple string instead of an array of words
string rdText = string.Join(" ", words);
  • This is basically a douplicate of [this answer](https://stackoverflow.com/a/52792060/7111561). Additionally the OP explicitely needed the output to be an array and not a new string. – derHugo Oct 15 '18 at 06:16