Jump to content

Merge even-numbered and odd-numbered items from two arrays


leuce
 Share

Recommended Posts

G'day everyone

Is there a simple way to merge two arrays in a way that merges only odd-numbered items from the one and only even-numbered items from the other? I have no idea how to code that.

Here's my situation:

I need to change selected elements in a string of text to match the sequence of those elements in a reference text.

For example, my reference text is:

The {1/}rain in {2/}{3/}Spain falls mainly on {0/}the{1/} plains.

and my required output text is:

Die {1/}reën in {2/}{3/}Spanje val saggies op {0/}die{1/} blanje.

As you can see, it consists of words and tags -- the tags are always an opening curly quote, followed by a number (anything from 0 to 99), followed by a forward slash and a closing curly quote. The words in the output text will usually be different from the words in the reference text, but the tags and the sequence of the tags must be identical.

The input text would be something like this:

Die {4/}reën in {2/}{3/}Spanje val saggies op {5/}die{5/} blanje.

The words in the output text must be the same as in the input text, but the tags in the output text must be the same as in the reference text. The number of tags in these three texts is always the same, but it can be any number, and the tags are not necessarily unique.

So, to sum up, I want to change the tags in this:

Die {4/}reën in {2/}{3/}Spanje val saggies op {5/}die{5/} blanje.

so that they are the same (and in the same sequence) as in this:

The {1/}rain in {2/}{3/}Spain falls mainly on {0/}the{1/} plains.

so that the resulting output I'm looking for would be this:

Die {1/}reën in {2/}{3/}Spanje val saggies op {0/}die{1/} blanje.

Do you have any idea how to do this cleanly?

At the moment my idea is to change { into _{, change /} into {_, and then split the reference text and input text by {, and then merge the two arrays into one output array, while skipping and alternating the items that get merged, and finally removing the _ again.

In other words, I want to create two arrays and then merge only odd-numbered items from the one and only even-numbered items from the other, without knowing beforehand how big the arrays will be.

Can you show me how to do that?

Thanks

Samuel

Link to comment
Share on other sites

Actually, I figured out one way to do it (though I'm not sure if this is the most "elegant"):

#include <Array.au3>

$reftext0 = "The {1/}rain in {2/}{3/}Spain falls mainly on {0/}the{1/} plains."
$imptext0 = "Die {4/}reën in {2/}{3/}Spanje val saggies op {5/}die{5/} blanje."

$reftext1 = StringReplace ($reftext0, "{", "_{")
$reftext2 = StringReplace ($reftext1, "/}", "{_")

$reftextarr = StringSplit ($reftext2, "{", 1)

$imptext1 = StringReplace ($imptext0, "{", "_{")
$imptext2 = StringReplace ($imptext1, "/}", "{_")

$imptextarr = StringSplit ($imptext2, "{", 1)

Local $output0[1]

For $i = 1 to $imptextarr[0]

If Mod($i, 2) = 0 Then
_ArrayAdd ($output0, $reftextarr[$i])
Else
_ArrayAdd ($output0, $imptextarr[$i])
EndIf

Next

$output1 = _ArrayToString($output0, "{")
$output2 = StringTrimLeft ($output1, 1)

$output3 = StringReplace ($output2, "_{", "{")
$output4 = StringReplace ($output3, "{_", "/}")

MsgBox (0, "", "R: " & $reftext0 & @CRLF & "I: " & $imptext0 & @CRLF & "O: " & $output4, 0)
Link to comment
Share on other sites

That's a job for StringRegExp calls.

First, extract the tags in your reference text with one call. Apply only once for every reference text. You can make that a 2D array if there are a number of them.

$reftags =  StringRegExp($reftext, '{d+/}', 3)

$reftags should now be an array of the wanted output tags in order of appearance.

Now loop thru your input text (no need to check bounds if you're certain the number of tags is identical between input and reference).

Local $ofs, $tag
For $i = 0 To UBound($reftags) - 1
$tag = StringRegExp($inputtext, '{d+/}', 1, $ofs)   ; find next tag in input text
$ofs = @extended   ; this is the offset of that tag in input
$inputtext = StringLeft($inputtext, $ofs - 1) &amp; $reftags[$i] &amp; StringMid($inputtext, $ofs + StringLen($tag))  ; replace this tag only
Next

Untested (no AutoIt on this tablet). Sorry for typos and multiple edits.

Edited by jchd

This wonderful site allows debugging and testing regular expressions (many flavors available). An absolute must have in your bookmarks.
Another excellent RegExp tutorial. Don't forget downloading your copy of up-to-date pcretest.exe and pcregrep.exe here
RegExp tutorial: enough to get started
PCRE v8.33 regexp documentation latest available release and currently implemented in AutoIt beta.

SQLitespeed is another feature-rich premier SQLite manager (includes import/export). Well worth a try.
SQLite Expert (freeware Personal Edition or payware Pro version) is a very useful SQLite database manager.
An excellent eBook covering almost every aspect of SQLite3: a must-read for anyone doing serious work.
SQL tutorial (covers "generic" SQL, but most of it applies to SQLite as well)
A work-in-progress SQLite3 tutorial. Don't miss other LxyzTHW pages!
SQLite official website with full documentation (may be newer than the SQLite library that comes standard with AutoIt)

Link to comment
Share on other sites

Thanks, MPV... I understand what you did. I should really learn how to use StringLeft and StringMid, because I often deal with text that must be concatenated in complex ways.

Edited by leuce
Link to comment
Share on other sites

The help file is your best friend, as usual!

This wonderful site allows debugging and testing regular expressions (many flavors available). An absolute must have in your bookmarks.
Another excellent RegExp tutorial. Don't forget downloading your copy of up-to-date pcretest.exe and pcregrep.exe here
RegExp tutorial: enough to get started
PCRE v8.33 regexp documentation latest available release and currently implemented in AutoIt beta.

SQLitespeed is another feature-rich premier SQLite manager (includes import/export). Well worth a try.
SQLite Expert (freeware Personal Edition or payware Pro version) is a very useful SQLite database manager.
An excellent eBook covering almost every aspect of SQLite3: a must-read for anyone doing serious work.
SQL tutorial (covers "generic" SQL, but most of it applies to SQLite as well)
A work-in-progress SQLite3 tutorial. Don't miss other LxyzTHW pages!
SQLite official website with full documentation (may be newer than the SQLite library that comes standard with AutoIt)

Link to comment
Share on other sites

Thanks, MPV... I understand what you did. I should really learn how to use StringLeft and StringMid, because I often deal with text that must be concatenated in complex ways.

MVP is what jchd is, but his username is jchd not MVP or MPV!

UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 22/04/2018

Link to comment
Share on other sites

In clear: Most Venturesome Poster ;)

For those who wonder, jchd = Jean-Christophe Deschamps but it's a bit of a keyboardful for a logon name.

This wonderful site allows debugging and testing regular expressions (many flavors available). An absolute must have in your bookmarks.
Another excellent RegExp tutorial. Don't forget downloading your copy of up-to-date pcretest.exe and pcregrep.exe here
RegExp tutorial: enough to get started
PCRE v8.33 regexp documentation latest available release and currently implemented in AutoIt beta.

SQLitespeed is another feature-rich premier SQLite manager (includes import/export). Well worth a try.
SQLite Expert (freeware Personal Edition or payware Pro version) is a very useful SQLite database manager.
An excellent eBook covering almost every aspect of SQLite3: a must-read for anyone doing serious work.
SQL tutorial (covers "generic" SQL, but most of it applies to SQLite as well)
A work-in-progress SQLite3 tutorial. Don't miss other LxyzTHW pages!
SQLite official website with full documentation (may be newer than the SQLite library that comes standard with AutoIt)

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...