简体   繁体   English

如何解决带有负索引移位的数组交换? (Javascript)

[英]How can I solve array swap with negative index shifting? (Javascript)

I am learning JS and doing exercises.我正在学习JS并做练习。 I came across this exercise, I will post the text for clarity:我遇到了这个练习,为了清楚起见,我将发布文本:

You're a magician and you handle a deck of cards.你是一个魔术师,你处理一副纸牌。 In order to correctly execute your magic trick, you need to be able to move a card from one position to another position.为了正确执行您的魔术,您需要能够将卡从一个 position 移动到另一个 position。 That is, you need to be able to rearrange the deck.也就是说,您需要能够重新排列牌组。 Naturally, you want to be able to move cards in both directions, and be able to say "from the top of the deck" or "from the bottom of the deck".自然,您希望能够双向移动卡片,并且能够说“从牌堆顶部”或“从牌堆底部”。

Create a function arrange that takes:创建一个 function 排列,需要:

an array (of length n) of items, a from position (whole number, -n <= from < n), and to position (whole number, -n <= to < n) Positive numbers means that you move cards from the bottom of the deck (the left hand side) and negative numbers refer to starting at the top of the deck (the right hand side).项目数组(长度为 n),从 position(整数,-n <= 从 < n)到 position(整数,-n <= 到 < n) 正数表示您从甲板底部(左侧)和负数是指从甲板顶部(右侧)开始。

It returns a new array with the item moved from the position from to the position to:它返回一个新数组,其中项目从 position 移动到 position 到:

const before = ['❤ A', '❤ 9', '❤ 3', '❤ 6', '♣ A']
const magics = arrange(before, 1, -2)
magics
// => ['❤ A', '❤ 3', '❤ 6', '❤ 9', '♣ A']
//                          ^--- has moved from position 1 to -2 (from the right side)
Create a second function rearrange that does the same thing, but mutates the original input array:

const before = ['❤ A', '❤ 3', '❤ 6', '❤ 9', '♣ A']
const magics = rearrange(before, 4, 0)
magics
// => ['♣ A', '❤ A', '❤ 3', '❤ 6', '❤ 9']
//      ^--- has moved from position 4 to 0
magics === before
// => true

So my solution for the arrange function was like this using the simplest method, a temp variable:所以我对排列 function 的解决方案是使用最简单的方法,一个临时变量:

function arrange(array, from, to) {

         var temp = array[from];
         array[from] =array[to];
array[to] = temp;

 return array
  }

var cards =['♠', '♣', '♥', '♦', '✨']
arrange(cards, 3,0)

I understand this only shifts positive indexes' position, as saying, for instance, arrange(cards,4,-1) will return undefined instead of the position desired.我知道这只会改变正索引的 position,例如,arrange(cards,4,-1) 将返回 undefined 而不是所需的 position。

Is there a way to make this work?有没有办法使这项工作? I have tried with the splice method and didn't seem to work either.我已经尝试过拼接方法,但似乎也没有工作。 thank you very much.非常感谢您。

Please mind that it is asking you a new array请注意,它正在询问您一个新数组

 function arrange(array, from, to) { const count = array.length; from = (from<0)?count+from:from; to = (to<0)?count+to:to; const newArr = array.filter((_,i)=> (i;==from)). newArr,splice(to,0;array[from]); return newArr, } var cards =['A', 'B', 'C', 'D', 'E'] const newCards = arrange(cards, -1.0) console,log("before",cards,"after";newCards);

with filter you get a new array (there are several other options of course) and in the same step i remove the item in the original position ( from ) then with splice i add it to its new position ( to )使用过滤器,您将获得一个新数组(当然还有其他几个选项),在同一步骤中,我删除原始 position( from )中的项目,然后使用拼接将其添加到新的 position( to )中

in order to be able to use filter i need to convert negative indices into positive ones.为了能够使用过滤器,我需要将负索引转换为正索引。 a solution with two splice may be done, but then you need to copy the array beforehand可以完成具有两个拼接的解决方案,但是您需要事先复制数组

If end is negative, the index will be the length of the array + end , for example ['❤ A', '❤ 9', '❤ 3', '❤ 6', '♣ A'] length is 5. if end is -2 , that index would be 5 + -2 , 3 .如果 end 为负数,则索引将是the length of the array + end ,例如['❤ A', '❤ 9', '❤ 3', '❤ 6', '♣ A']长度为 5。如果end 是-2 ,该索引将是5 + -2 , 3

 function getIndex(array, position) { return position < 0? array.length + position: position; } const before = ['❤ A', '❤ 9', '❤ 3', '❤ 6', '♣ A']; console.log(getIndex(before, 1)); console.log(getIndex(before, -2));


Now, the problem is not about swapping the elements from and to , but shifting them.现在,问题不在于交换元素fromto ,而是移动它们。

For example, [ '❤ 9', '❤ 3', '❤ 6' ] , you remove the first one [ '❤ 3', '❤ 6' ] and push it to the end: [ '❤ 3', '❤ 6', '❤ 9' ]例如[ '❤ 9', '❤ 3', '❤ 6' ] ,你删除第一个[ '❤ 3', '❤ 6' ]并将其推到最后: [ '❤ 3', '❤ 6', '❤ 9' ]

The shift() method removes the first element and returns it shift()方法删除第一个元素并返回它

 function shiftArray(array) { const elem = array.shift(); // remove the first element array.push(elem); // push it to the end // changes are made in place, nothing to return } const arr = [ '❤ 9', '❤ 3', '❤ 6' ]; shiftArray(arr); console.log(arr);

Now, you need to apply that shifting to a slice of the array.现在,您需要将该转换应用于数组的一部分。

The slice(from, to) method does exactly that. slice(from, to)方法正是这样做的。

And it accepts negative indexes, so you won't even need the previously written getIndex() function:它接受负索引,因此您甚至不需要之前编写的getIndex() function:

 function shiftArray(array) { const elem = array.shift(); // remove the first element array.push(elem); // push it to the end // changes are made in place, nothing to return } function arrange(array, from, to) { // get the first part of the array const firstpart = array.slice(0, from); // get the part to do the "magic" const partToShift = array.slice(from, to + 1); // get the last part const lastPart = array.slice(to + 1); shiftArray(partToShift); // return a new array, combining all parts return firstpart.concat(partToShift, lastPart); } let before = ['❤ A', '❤ 9', '❤ 3', '❤ 6', '♣ A']; let magics = arrange(before, 1, -2); console.log("original"); console.log(before); console.log("modified"); console.log(magics); // some edge cases magics = arrange(before, 0, -2); console.log(magics); magics = arrange(before, 1, 4); console.log(magics); magics = arrange(before, 1, 1); console.log(magics);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Javascript:如何交换对象数组的元素(通过引用而不是索引)? - Javascript: How can I swap elements of an array of objects (by reference, not index)? 如何使用JavaScript交换图片 - How can I swap a picture using javascript 我如何用数组解决 javascript 排序问题 - How can i solve the javascript sorting problem with array 如何解决数组中的 javascript map 问题 - How can i solve the javascript map problem in a array 如何使用JavaScript在数组中查找负数索引 - How to find index of negative numbers in an array using JavaScript 如何检查JavaScript中对象数组中的索引是否存在? - How can I check index in object array exist or no in javascript? 如何更快地索引 Javascript 中的对象数组? - How can I index an array of objects in Javascript faster? Javascript将数组元素交换到另一个索引并删除旧索引 - Javascript swap array element to another index and removing the old index 如何在javaScript中创建一个带有索引和键的二维数组? - How can I create a two dimensional array with index and with key in javaScript? 如果旋转数为负,如何将数组向左旋转,如果旋转数为正,如何使用 JAVASCRIPT - How can I rotate an array to the left if the number of rotation is negative and to the right if number of rotation is positive using JAVASCRIPT
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM