Trying to "move" elements in an array
$req=@("a","b","c","d")
$current=@("c","a","d","b")
i'm trying accomplish:
$req order elements *must* in. $current order elements in.
need take $current, , figure out "moves" need make come $req.
so, above:
1. $current[0] needs moved down 3 spots.
2. $current[1] needs moved 1 spot.
3. $current[2] needs moved down 1 spot.
4. $current[3] needs moved 2 spots.
based on #1-4 above, gives me number of spots need move element around, , "direction" match $req.
i've tried below, able take $current , create $new in proper order.
--------------------------
$req=@("a","b","c","d")
$current=@("c","a","d","b")
$new=@()
while($new.length -lt 4){
$i=0
foreach($item in $current){
$looking=$new.length
if($item -eq $req[$looking]){
$new+=$item
$diff=$i-$looking
"move $item $diff"
break
}
$i++
}
}
--------------------------
result:
move 1
move b 2
move c -2
move d -1
thought home free, ran "jaykul", , pointed won't work.
problem once move "a" 1, array changes, , moves b, c , d no longer valid.
simple example of i'm trying accomplish private script. in end, need determine specific number of moves need place right, including whether i'm moving left (+) or right (-).
here take on it:
$req=@("a","b","c","d")
[collections.arraylist]$current=@("c","a","d","b")
$sortorder = @{}
$i=0
$req | %{ $sortorder[$_] = $i++}
1..($req.count-1) | %{
$currentelement = $current[$_];
$currentorder = $sortorder[$currentelement]
$newposition=-1
$i=0
while(($newposition -lt 0) -and ($i -lt $_)) {
if ($currentorder -le $sortorder[$current[$i]]) { $newposition = $i }
$i++
}
if ($newposition -ge 0) {
"move $currentelement $($newposition-$_)" | write-host
$current.removeat($_)
$current.insert($newposition,$currentelement)
}
}
a few things note
- elements travel right left, hence, direction "-"
- insertion sort used in implementation. not efficient
- quicksort better, , hence, question, can swaps?
- choose insertion sort because resembled original description/attempt most
Windows Server > Windows PowerShell
Comments
Post a Comment